refactor(test): colocate pure-domain tests and reduce test debt (#471)
* refactor(test): colocate pure-domain tests and reduce test debt Move focused immutable domain/contracts/adapter tests from tests/composition/** beside their production owners under src/** as colocated *.test.ts/*.fixture.ts, and relocate persistence-shaped composition tests under tests/boundary/filesystem/**. Update import paths, the Vitest project topology (shared worker context for pure domain/contracts and recording-port service projects), the test migration ledger, testing docs, and AGENTS.md to match. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: remove test migration ledger The cutover is complete and the ledger is no longer referenced anywhere in source, scripts, or the docs gate. Drop the standalone artifact. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * docs: clean up stale migration artifacts Remove empty directories left by the test migration and replace the "final cutover" language in docs/testing.md with standing PR guidance that no longer references the completed migration. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> * fix: repair CI failures from schema, knip, and stale generated artifacts Three root causes fixed: 1. catalog-schemas.mjs: valuesAt only traversed anyOf from Zod's toJSONSchema, not oneOf. The webScreenshotDiffSchema change to a discriminated union produces oneOf, so the product catalog generator could not derive the web_screenshot_diff schema version. Add oneOf traversal. 2. conformancePackage.ts: the test rewrite removed the only imports of ScenarioManifest, ReplayPlan, ShimPlan, and ExpectedEvidence, making them unused exports that knip flags. Remove the dead type aliases. 3. Regenerate stale artifacts (product catalog, MCP tool catalog, skill metadata, conformance manifest) that drifted from the source changes. Generated with [Devin](https://devin.ai) Co-Authored-By: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com> --------- Co-authored-by: Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
This commit is contained in:
co-authored by
Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent
344b9b6dff
commit
e91c8c39c2
+22
-2
@@ -18,7 +18,27 @@
|
||||
},
|
||||
"overrides": [
|
||||
{
|
||||
"files": ["tests/**/*.ts", "src/**/*.test.ts"],
|
||||
"files": [
|
||||
"src/{contracts,domain,server}/**/*.ts",
|
||||
"src/application/**/*.ts"
|
||||
],
|
||||
"excludeFiles": ["src/application/runtime.ts"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
{
|
||||
"patterns": [
|
||||
{
|
||||
"group": ["**/ghidra/**", "**/hopper/**"],
|
||||
"message": "Deep-provider imports belong behind adapters or in the application composition root."
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["tests/**/*.ts", "src/**/*.test.ts", "src/**/*.fixture.ts"],
|
||||
"rules": {
|
||||
"max-lines": [
|
||||
"error",
|
||||
@@ -31,7 +51,7 @@
|
||||
}
|
||||
},
|
||||
{
|
||||
"files": ["src/domain/**/*.test.ts"],
|
||||
"files": ["src/domain/**/*.{fixture,test}.ts"],
|
||||
"rules": {
|
||||
"no-restricted-imports": [
|
||||
"error",
|
||||
|
||||
@@ -38,7 +38,7 @@ See [docs/architecture.mermaid](docs/architecture.mermaid) for a visual architec
|
||||
- `src/application/`: shared CLI/MCP session composition, setup and diagnostics, and enhanced workflows. `AnalysisProviderRegistry` discovers overlapping deep candidates without starting them; `SessionProviderRouter` binds one candidate per target and composes it with disjoint auxiliary providers; `JavaScriptArtifactReconstruction.ts` safely projects local directories/ASARs and inert bundle syntax into the application graph without adding a caller-visible tool yet.
|
||||
- `src/server/`: MCP request translation. `createServer.ts` assembles the MCP server, `registerOfficialTools.ts`/`registerEnhancedTools.ts` register each tool set, `toolResult.ts` maps `Result` values to MCP content.
|
||||
- `docs/product-catalog.json`: generated package, tool-family, provider, setup-client, schema-version, and CLI facts. Regenerate it from source; do not edit it by hand.
|
||||
- `tests/`: Vitest suite. `tests/fixtures/` holds reusable provider-process fixtures, source-owned synthetic JavaScript graph and Electron/Webpack/Rspack artifact trees, and the fake launcher, Hopper bridge, and CDP seams.
|
||||
- `tests/`: Vitest suite. Focused immutable domain builders live beside their production owner as `src/domain/*.fixture.ts`; `tests/fixtures/` holds reusable provider-process fixtures, source-owned Electron/Webpack/Rspack artifact trees, and the fake launcher, Hopper bridge, and CDP seams.
|
||||
- `scripts/verify-real-hopper.mjs`: real-Hopper end-to-end verifier.
|
||||
- `scripts/verify-real-ghidra.mjs`: real Linux Ghidra verifier for x86-64 debug/stripped ELF, AArch64 ELF, PE, and Mach-O function semantics plus complete cleanup.
|
||||
- `scripts/verify-real-ghidra-windows.mjs`: real Windows x64 Ghidra P0 verifier for the source-owned native PE fixture, all 19 admitted operations, digest linkage, loopback transport, and cleanup.
|
||||
|
||||
@@ -680,10 +680,10 @@
|
||||
"mcp_resource_templates": 11
|
||||
},
|
||||
"digests": {
|
||||
"tools_sha256": "b0e8b9c894ef347b6680a3a5bfdb4cba5c10e9129eeaa43a5ea22ce4d398d417",
|
||||
"tools_sha256": "1a4533fef9cbe075fdca76b19a138924bd69d93a6413cdb767b2a9240a46fd04",
|
||||
"prompts_sha256": "3886a3bf55a448def79e3eb429e6a56eb2ba075423c5cb1e5747642b389ef8fe",
|
||||
"resources_sha256": "e0e872276ebf6f88e916ef24930a99eed27ce4c93e494e60820e9bd8cc8497c3",
|
||||
"combined_sha256": "bab5657d9525ec4f798d0a9ef6001412d9c11f77fb0ddc925c7076fd10921dc9",
|
||||
"combined_sha256": "8bd40516d78875cb75ba1c4a8786286311036742ad660914d7327c2941b2f73a",
|
||||
"providers_sha256": "7446b51788734ebf6f4f702e3a5a8c9f0b61967490c245f30bd37b2060827e6b"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
# Test architecture migration ledger
|
||||
|
||||
This ledger records how the flat test suite was classified during the
|
||||
coordinated architecture cutover. It is an evidence index, not a declaration
|
||||
that every test became independent merely because its path changed.
|
||||
|
||||
## Classification batches
|
||||
|
||||
The following mappings are grounded in the current moved paths. They describe
|
||||
ownership only; decomposition and evidence replacement must be recorded in the
|
||||
per-suite table below.
|
||||
|
||||
| Previous path | Current path | Classification |
|
||||
| --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | ----------------------------------- |
|
||||
| `tests/applicationWorkflowCli.test.ts` | `tests/acceptance/applications/applicationWorkflowCli.test.ts` | Acceptance application workflow |
|
||||
| `tests/setupLifecycle.test.ts` | `tests/acceptance/setup/setupLifecycle.test.ts` | Acceptance setup workflow |
|
||||
| `tests/cdpBrowserProvider.test.ts` | `tests/boundary/browser/cdpBrowserProvider*.test.ts` | Browser boundary |
|
||||
| `tests/ghidraClient.test.ts` | `tests/boundary/providers/ghidra/ghidraClient.test.ts` | Ghidra provider boundary |
|
||||
| `tests/processOwnership.test.ts` | `tests/boundary/process/processOwnership*.test.ts` | Process boundary |
|
||||
| `tests/binarySession.test.ts` | `tests/composition/analysis-sessions/binarySession.*.test.ts` | Analysis-session composition |
|
||||
| `tests/javascriptSemanticAnalysis.test.ts` | `tests/composition/javascript-applications/javascriptSemanticAnalysis.*.test.ts` | JavaScript-application composition |
|
||||
| `tests/config.test.ts` | `tests/composition/setup-lifecycle/config.test.ts` | Setup-lifecycle composition |
|
||||
| `tests/composition/analysis-sessions/runtime.test.ts` | `tests/acceptance/applications/runtime.test.ts` | Compiled MCP acceptance workflow |
|
||||
| `tests/composition/runtime-observation/webCaptureDiff.test.ts` | `tests/boundary/browser/webCaptureDiff.test.ts` | Browser boundary |
|
||||
| `tests/conformanceFixtures.test.ts` | `tests/conformance/providers/conformanceFixtures.test.ts` | Provider conformance |
|
||||
| `tests/codexAgentEval.test.ts` | `tests/evaluation/model-evals/codexAgentEval.test.ts` | Deterministic model-evaluator logic |
|
||||
| `tests/composition/analysis-sessions/{boundedCartesianProjection,symbolAnalysis,jsonShape}.test.ts` | `src/domain/{boundedCartesianProjection,symbolAnalysis,jsonShape}.test.ts` | Colocated pure-domain behavior |
|
||||
|
||||
The same directory mapping applies to the other files moved in each batch:
|
||||
`tests/acceptance/{analysis,applications,investigations,setup}`,
|
||||
`tests/boundary/{browser,cli,filesystem,mcp,process,providers}`,
|
||||
`tests/composition/{analysis-sessions,evidence-investigations,javascript-applications,process-capture,runtime-observation,setup-lifecycle}`,
|
||||
`tests/conformance`, and `tests/evaluation`. Git rename detection remains the
|
||||
canonical source for the complete old-to-new path list.
|
||||
|
||||
## Per-suite evidence record
|
||||
|
||||
Add a row when a legacy suite is materially decomposed, consolidated, replaced,
|
||||
or removed. “Replacement evidence” must identify executable behavior, a
|
||||
generated artifact comparison, a protocol probe, or an explicit verifier; a new
|
||||
path alone is not replacement evidence.
|
||||
|
||||
| Legacy suite or claim | Disposition | Replacement evidence | Validation | Remaining gap |
|
||||
| ----------------------------------------------- | ------------ | ------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------- |
|
||||
| Flat path classification | Moved | Vitest configuration contract proves every deterministic test belongs to exactly one project | Configuration contract test | Record any exceptions discovered during cutover |
|
||||
| Direct session construction outside owner tests | Consolidated | `composeBinarySession` and `composeBinarySessionFromProvider` are the shared production/test seams | Repository search plus session-composition and acceptance tests | None |
|
||||
| Repeated temporary-directory setup | Consolidated | `createTestTempDirectory` delegates every test-owned root to the typed workspace fixture with HOME/XDG projection and awaited cleanup | Repository search plus filesystem, process, runtime suites, and the Vitest topology hygiene contract | None; direct `mkdtemp` remains only in the workspace fixture and package-canary source text |
|
||||
| Repeated CLI/MCP connection helpers | Consolidated | Typed CLI and MCP fixtures under `tests/support`; CLI output, dispatcher, and server tests use them | Acceptance startup, typed failure, lifecycle, and teardown tests | Provider-specific protocol harnesses remain local |
|
||||
| Implementation-shaped assertions | Replaced | Recording adapters, executable bridge/protocol probes, generated-artifact comparisons, and supported configuration contracts | Focused boundary/conformance tests and repository search | None identified in the final audit |
|
||||
| Module mocks and spies | Replaced | Recording adapters and caller-visible outcomes | Repository search plus focused reload, Ghidra, and enhanced-tool tests | None |
|
||||
| `processCapture.test.ts` | Consolidated | Ten lifecycle, observation, reactive, replay, terminal, validation, and trace suites | 42 focused boundary tests | None |
|
||||
| `cdpBrowserProvider.test.ts` | Consolidated | Five discovery, document/script, network, lifecycle, and sensitive-data suites | 36 focused browser-boundary tests | None |
|
||||
| `javascriptSemanticAnalysis.test.ts` | Consolidated | Six structure, call, dataflow, runtime, native-binding, and rejection suites | 29 focused composition tests | None |
|
||||
| `binarySession.test.ts` | Consolidated | Nine provider binding, lifecycle, cache, Evidence, permissions, and shutdown suites | Focused composition tests and shared composition-seam test | None |
|
||||
| MCP mega-suites | Consolidated | Tool/resource-family suites plus catalog-wide identity and lifecycle coverage | Focused MCP tests and complete deterministic run | None |
|
||||
| Provider client mega-suites | Consolidated | Capability-named protocol, timeout, ownership, error, and cleanup suites | 85 focused provider tests | Real systems remain in `verify:*` lanes |
|
||||
| Pure domain proofs | Moved | Colocated bounded projection, symbol classification, and JSON-shape tests | Domain Vitest project | Continue moving only tests with no external boundary dependency |
|
||||
|
||||
Use these dispositions consistently:
|
||||
|
||||
- **Moved**: the same material claim now has depth-appropriate ownership.
|
||||
- **Replaced**: stronger executable evidence supersedes the old assertion.
|
||||
- **Consolidated**: one retained test proves a claim previously duplicated.
|
||||
- **Intentionally removed**: the claim was not public or independent; the row
|
||||
must still name the retained evidence or explain why none is warranted.
|
||||
- **In progress**: classification exists but the replacement audit is not
|
||||
complete. No final-cutover row may retain this disposition.
|
||||
|
||||
The exact old-to-new inventory is mechanically enforced by the project
|
||||
classification contract and retained in Git rename metadata. Real-system lanes,
|
||||
coverage, repeated-run stability, and benchmark timing are release evidence;
|
||||
they are reported separately because they depend on the execution host and
|
||||
installed external systems.
|
||||
+11
-3
@@ -25,6 +25,11 @@ registries but do not cross production filesystem, process, socket, or browser b
|
||||
Boundary tests cross one production boundary. Only acceptance tests assemble
|
||||
the complete runtime or invoke the compiled product surface.
|
||||
|
||||
Focused immutable builders shared by a domain test family live beside their
|
||||
production owner as `src/domain/*.fixture.ts`. They are typechecked with the
|
||||
suite and excluded from package builds; broader runtime and provider fixtures
|
||||
remain under `tests/fixtures/**`.
|
||||
|
||||
`tests/process-global/**` is reserved for cases with a demonstrated dependency
|
||||
on process-global state. Those tests run without file parallelism. Reusable,
|
||||
test-scoped fixtures live under `tests/support/**`; immutable source artifacts
|
||||
@@ -64,6 +69,9 @@ Use `npm run check:pr` before handing off a contribution.
|
||||
Local full-suite Vitest runs are intentionally capped at one worker and one
|
||||
project at a time. Boundary fixtures own real subprocesses, and this local cap
|
||||
keeps aggregate memory predictable; CI retains the existing two-worker budget.
|
||||
The pure domain/contracts and recording-port service projects share one worker
|
||||
module context because their tests own no mutable runtime resources; adapter,
|
||||
composition, and boundary projects retain per-file isolation.
|
||||
`npm test`, `npm run docs:check`, and `npm run docs:generate` share
|
||||
repository-local locks and fail fast when the same class of command is already
|
||||
running. The `npm test` build is inside that lock. `check:pr` runs its test task
|
||||
@@ -101,6 +109,6 @@ for another.
|
||||
|
||||
The PR acceptance target is a median `npm run check:pr` wall time below three
|
||||
minutes across three warm-build runs on the benchmark host. Keep Vitest caches
|
||||
cold unless separately identified. The final cutover also requires three
|
||||
consecutive deterministic passes without retries, `npm run verify:package`, and
|
||||
the applicable real-system lanes.
|
||||
cold unless separately identified. A PR that touches packaging or real-system
|
||||
behavior also requires `npm run verify:package` and the applicable
|
||||
`verify:*` lanes.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"manifest_id": "ecm_c44391ed8e365e21871664422aa38fa6c12598006cde731d65a9d9e271b0fa5f",
|
||||
"manifest_id": "ecm_5add7389cf00e86bfec005df9e0e0cf8d7aceb2f3ec3e5f6b74edb5f880bd9a7",
|
||||
"verifier": {
|
||||
"id": "rea-managed-conformance",
|
||||
"version": "1"
|
||||
@@ -14,7 +14,7 @@
|
||||
"skill_digests": [
|
||||
{
|
||||
"skill_id": "reverse-engineer-anything",
|
||||
"sha256": "97a5bc5d29f162fe171ddbb8f4f5ba9fcba34ad336d4cdcae0c564223aa4cfe8"
|
||||
"sha256": "2cca31c9550fe32c24adcb8134edb4b077aa772fb0f0f1057c99964cac6d9a8f"
|
||||
}
|
||||
],
|
||||
"claims": [
|
||||
|
||||
@@ -4,6 +4,8 @@ const valuesAt = (node, path) => {
|
||||
if (typeof node !== "object" || node === null) return [];
|
||||
if ("anyOf" in node && Array.isArray(node.anyOf))
|
||||
return node.anyOf.flatMap((alternative) => valuesAt(alternative, path));
|
||||
if ("oneOf" in node && Array.isArray(node.oneOf))
|
||||
return node.oneOf.flatMap((alternative) => valuesAt(alternative, path));
|
||||
if (path.length === 0)
|
||||
return "const" in node &&
|
||||
(typeof node.const === "number" || typeof node.const === "string")
|
||||
|
||||
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, an
|
||||
metadata:
|
||||
version: "23"
|
||||
tool_count: 116
|
||||
catalog_digest: "bab5657d9525ec4f798d0a9ef6001412d9c11f77fb0ddc925c7076fd10921dc9"
|
||||
catalog_digest: "8bd40516d78875cb75ba1c4a8786286311036742ad660914d7327c2941b2f73a"
|
||||
---
|
||||
|
||||
# REA
|
||||
|
||||
+4
-4
@@ -3,16 +3,16 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getNavigationContext,
|
||||
inspectAddressContext,
|
||||
} from "../../../src/application/AnalysisContextQueries.js";
|
||||
} from "./AnalysisContextQueries.js";
|
||||
import {
|
||||
createAnalysisExecution,
|
||||
type AnalysisOperationPort,
|
||||
} from "../../../src/application/AnalysisProvider.js";
|
||||
} from "./AnalysisProvider.js";
|
||||
import {
|
||||
AnalysisCancelledError,
|
||||
AnalysisProtocolError,
|
||||
} from "../../../src/domain/errors.js";
|
||||
import { err, ok } from "../../../src/domain/result.js";
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createAnalysisProfile } from "../domain/analysisProfile.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
} from "../domain/analysisSnapshot.fixture.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { createAnalysisExecution } from "./AnalysisProvider.js";
|
||||
import { AnalysisSnapshotCache } from "./AnalysisSnapshotCache.js";
|
||||
|
||||
describe("analysis snapshot cache partitioning", () => {
|
||||
it("returns detached data only from the exact provider/profile partition", () => {
|
||||
const cache = new AnalysisSnapshotCache();
|
||||
const execution = createAnalysisExecution(
|
||||
"main",
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{ analysisProfile: ANALYSIS_SNAPSHOT_PROFILE },
|
||||
);
|
||||
cache.record({
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
profile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
operation: "address_name",
|
||||
parameters: { address: "0x1000", document: "fixture" },
|
||||
execution,
|
||||
});
|
||||
const exported = cache.export(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
createEvidenceBundle([]),
|
||||
);
|
||||
expect(exported.ok).toBe(true);
|
||||
if (!exported.ok) return;
|
||||
const entry = exported.value.entries[0];
|
||||
if (entry !== undefined) {
|
||||
Reflect.set(entry.execution, "provider", {
|
||||
id: "forged",
|
||||
name: "Forged",
|
||||
version: "9",
|
||||
});
|
||||
entry.execution.limitations.push("forged");
|
||||
}
|
||||
|
||||
expect(
|
||||
cache.lookup(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
"address_name",
|
||||
{ address: "0x1000", document: "fixture" },
|
||||
),
|
||||
).toMatchObject({
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
limitations: [expect.stringContaining("local REA analysis snapshot")],
|
||||
});
|
||||
const changedProfile = createAnalysisProfile(
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
1,
|
||||
{ loader: "configured-override" },
|
||||
);
|
||||
expect(
|
||||
cache.lookup(ANALYSIS_SNAPSHOT_TARGET, changedProfile, "address_name", {
|
||||
address: "0x1000",
|
||||
document: "fixture",
|
||||
}),
|
||||
).toBeUndefined();
|
||||
const changedProviderProfile = createAnalysisProfile(
|
||||
{ id: "other", name: "Other", version: "1" },
|
||||
1,
|
||||
{ loader: "mach-o-arm64" },
|
||||
);
|
||||
expect(
|
||||
cache.lookup(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
changedProviderProfile,
|
||||
"address_name",
|
||||
{ address: "0x1000", document: "fixture" },
|
||||
),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
resolveArtifactIntegrityPolicy,
|
||||
resolveNativeMountPolicy,
|
||||
} from "../../../src/application/ArtifactInventory/policy.js";
|
||||
} from "./ArtifactInventory/policy.js";
|
||||
|
||||
describe("artifact inventory policy resolution", () => {
|
||||
it("admits native mounting only when caller and operator both allow it", () => {
|
||||
@@ -15,12 +15,8 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type {
|
||||
AnalysisClient,
|
||||
AnalysisExecution,
|
||||
AnalysisClientFactory,
|
||||
ExecutionOptions,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisOperationPort,
|
||||
AnalysisProvider,
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { AnalysisOperation } from "./AnalysisProvider.js";
|
||||
@@ -80,23 +76,9 @@ export class BinarySession
|
||||
>();
|
||||
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
constructor(
|
||||
readonly provider:
|
||||
| AnalysisProvider
|
||||
| AnalysisClientFactory
|
||||
| SessionProviderRouter,
|
||||
options: {
|
||||
readonly resolveAnalysisProfile?: (
|
||||
target: BinaryTarget,
|
||||
options?: AnalysisProfileResolutionOptions,
|
||||
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
} = {},
|
||||
) {
|
||||
constructor(providerRouter: SessionProviderRouter) {
|
||||
super();
|
||||
this.#providerRouter =
|
||||
provider instanceof SessionProviderRouter
|
||||
? provider
|
||||
: SessionProviderRouter.legacy(provider, options);
|
||||
this.#providerRouter = providerRouter;
|
||||
}
|
||||
|
||||
/** Identify the provider producing evidence for this session. */
|
||||
|
||||
@@ -1,33 +1,7 @@
|
||||
import type {
|
||||
AnalysisClientFactory,
|
||||
AnalysisProfileResolution,
|
||||
AnalysisProfileResolutionOptions,
|
||||
AnalysisProvider,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { AnalysisProvider } from "./AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
import { SessionProviderRouter } from "./SessionProviderRouter.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { AnalysisError } from "../domain/errors.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
|
||||
type BinarySessionOptions = {
|
||||
readonly resolveAnalysisProfile?: (
|
||||
target: BinaryTarget,
|
||||
options?: AnalysisProfileResolutionOptions,
|
||||
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
|
||||
};
|
||||
|
||||
type BinarySessionOptionsOrResolver =
|
||||
| BinarySessionOptions
|
||||
| BinarySessionOptions["resolveAnalysisProfile"];
|
||||
|
||||
const normalizeBinarySessionOptions = (
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySessionOptions =>
|
||||
typeof optionsOrResolver === "function"
|
||||
? { resolveAnalysisProfile: optionsOrResolver }
|
||||
: (optionsOrResolver ?? {});
|
||||
|
||||
/**
|
||||
* Compose one provider-neutral session from deep-provider selection and
|
||||
@@ -42,21 +16,3 @@ export const composeBinarySession = (
|
||||
? registry
|
||||
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
|
||||
);
|
||||
|
||||
/**
|
||||
* Compose a session through the same internal seam for focused adapter tests.
|
||||
* The constructor remains private to this composition module, so callers test
|
||||
* provider behavior without coupling to BinarySession construction.
|
||||
*/
|
||||
export const composeBinarySessionFromFactory = (
|
||||
provider: AnalysisProvider | AnalysisClientFactory | SessionProviderRouter,
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySession =>
|
||||
new BinarySession(provider, normalizeBinarySessionOptions(optionsOrResolver));
|
||||
|
||||
/** Compose a focused session from any provider-shaped test seam. */
|
||||
export const composeBinarySessionFromProvider = (
|
||||
provider: AnalysisProvider | AnalysisClientFactory | SessionProviderRouter,
|
||||
optionsOrResolver?: BinarySessionOptionsOrResolver,
|
||||
): BinarySession =>
|
||||
new BinarySession(provider, normalizeBinarySessionOptions(optionsOrResolver));
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listBrowserTargetsInputSchema } from "../domain/browserObservation.js";
|
||||
import { listBrowserTargets } from "./BrowserObservationService.js";
|
||||
import { createPermissionAuthority } from "./PermissionAuthority.js";
|
||||
|
||||
describe("browser observation authorization", () => {
|
||||
it("requests loopback authority for an IPv6-only browser origin", async () => {
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "http://[::1]:3000";
|
||||
const ceiling = {
|
||||
capability: "browser_observe" as const,
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [endpoint, origin],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:browser_observe",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
|
||||
const result = await listBrowserTargets(
|
||||
undefined,
|
||||
authority.value,
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
describe("capability inventory contract", () => {
|
||||
it("produces valid availability and rejects contradictory states", () => {
|
||||
const inventory = buildCapabilityInventory(
|
||||
{ open: false, capabilities: [] },
|
||||
{
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
},
|
||||
);
|
||||
const unavailable = inventory.find(({ available }) => !available);
|
||||
expect(unavailable).toBeDefined();
|
||||
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
|
||||
expect(
|
||||
toolAvailability.safeParse({ ...unavailable, available: true }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
toolAvailability.safeParse({
|
||||
...unavailable,
|
||||
available: false,
|
||||
reason: "available",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
|
||||
import { buildCapabilityInventory } from "./CapabilityInventory.js";
|
||||
|
||||
const enabledPolicy: Parameters<typeof buildCapabilityInventory>[1] = {
|
||||
processCaptureEnabled: true,
|
||||
@@ -8,14 +8,37 @@ import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
|
||||
import { supportedClients } from "./SupportedClients.js";
|
||||
|
||||
export interface ClientRegistrationStatus {
|
||||
interface ClientRegistrationStatusBase {
|
||||
readonly client: string;
|
||||
readonly config_path: string;
|
||||
readonly command: readonly string[];
|
||||
readonly state: "aligned" | "stale" | "missing" | "invalid";
|
||||
readonly remediation: string | null;
|
||||
}
|
||||
|
||||
type RegistrationCommand = readonly [string, ...string[]];
|
||||
|
||||
export type ClientRegistrationStatus = ClientRegistrationStatusBase &
|
||||
(
|
||||
| {
|
||||
readonly command: RegistrationCommand;
|
||||
readonly state: "aligned";
|
||||
readonly remediation: null;
|
||||
}
|
||||
| {
|
||||
readonly command: RegistrationCommand;
|
||||
readonly state: "stale";
|
||||
readonly remediation: string;
|
||||
}
|
||||
| {
|
||||
readonly command: readonly [];
|
||||
readonly state: "missing" | "invalid";
|
||||
readonly remediation: string;
|
||||
}
|
||||
);
|
||||
|
||||
export type UnhealthyClientRegistrationStatus = Exclude<
|
||||
ClientRegistrationStatus,
|
||||
{ readonly state: "aligned" }
|
||||
>;
|
||||
|
||||
const objectSchema = z.record(z.string(), z.unknown());
|
||||
const registrationSchema = z
|
||||
.object({
|
||||
@@ -44,13 +67,18 @@ export const readClientRegistrationStatuses = async (
|
||||
);
|
||||
const raw = servers[PRODUCT_IDENTITY.mcpServerKey];
|
||||
if (raw === undefined) {
|
||||
statuses.push(status(client.name, client.configPath, [], "missing"));
|
||||
statuses.push(
|
||||
unavailableStatus(client.name, client.configPath, "missing"),
|
||||
);
|
||||
continue;
|
||||
}
|
||||
const registration = registrationSchema.parse(raw);
|
||||
const command = [registration.command, ...registration.args];
|
||||
const command: RegistrationCommand = [
|
||||
registration.command,
|
||||
...registration.args,
|
||||
];
|
||||
statuses.push(
|
||||
status(
|
||||
configuredStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
command,
|
||||
@@ -61,10 +89,9 @@ export const readClientRegistrationStatuses = async (
|
||||
);
|
||||
} catch (cause: unknown) {
|
||||
statuses.push(
|
||||
status(
|
||||
unavailableStatus(
|
||||
client.name,
|
||||
client.configPath,
|
||||
[],
|
||||
isMissing(cause) ? "missing" : "invalid",
|
||||
),
|
||||
);
|
||||
@@ -102,20 +129,29 @@ const registrationAligned = (
|
||||
);
|
||||
};
|
||||
|
||||
const status = (
|
||||
const remediation =
|
||||
"Run rea setup to refresh this registration, then restart the client.";
|
||||
|
||||
const configuredStatus = (
|
||||
client: string,
|
||||
configPath: string,
|
||||
command: readonly string[],
|
||||
state: ClientRegistrationStatus["state"],
|
||||
command: RegistrationCommand,
|
||||
state: "aligned" | "stale",
|
||||
): ClientRegistrationStatus =>
|
||||
state === "aligned"
|
||||
? { client, config_path: configPath, command, state, remediation: null }
|
||||
: { client, config_path: configPath, command, state, remediation };
|
||||
|
||||
const unavailableStatus = (
|
||||
client: string,
|
||||
configPath: string,
|
||||
state: "missing" | "invalid",
|
||||
): ClientRegistrationStatus => ({
|
||||
client,
|
||||
config_path: configPath,
|
||||
command,
|
||||
command: [],
|
||||
state,
|
||||
remediation:
|
||||
state === "aligned"
|
||||
? null
|
||||
: "Run rea setup to refresh this registration, then restart the client.",
|
||||
remediation,
|
||||
});
|
||||
|
||||
const exists = async (path: string | undefined): Promise<boolean> => {
|
||||
|
||||
@@ -19,6 +19,7 @@ import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
|
||||
import {
|
||||
readClientRegistrationStatuses,
|
||||
type ClientRegistrationStatus,
|
||||
type UnhealthyClientRegistrationStatus,
|
||||
} from "./ClientRegistrationStatus.js";
|
||||
import {
|
||||
inspectRuntimeExecutables,
|
||||
@@ -214,7 +215,10 @@ const collectDoctorIdentity = async (
|
||||
checks: [
|
||||
...(skillAligned ? [] : [skillIdentityCheck(installedSkillIdentity)]),
|
||||
...registrations
|
||||
.filter(({ state }) => state !== "aligned")
|
||||
.filter(
|
||||
(registration): registration is UnhealthyClientRegistrationStatus =>
|
||||
registration.state !== "aligned",
|
||||
)
|
||||
.map(registrationCheck),
|
||||
],
|
||||
value: {
|
||||
@@ -283,15 +287,13 @@ const skillIdentityCheck = (
|
||||
});
|
||||
|
||||
const registrationCheck = (
|
||||
registration: ClientRegistrationStatus,
|
||||
registration: UnhealthyClientRegistrationStatus,
|
||||
): DoctorCheck => ({
|
||||
name: `registration:${registration.client}`,
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: registration.config_path,
|
||||
remediation:
|
||||
registration.remediation ??
|
||||
"Run rea setup, then restart the affected client.",
|
||||
remediation: registration.remediation,
|
||||
});
|
||||
|
||||
const installationState = (
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js";
|
||||
import type {
|
||||
ClientRegistrationStatus,
|
||||
UnhealthyClientRegistrationStatus,
|
||||
} from "./ClientRegistrationStatus.js";
|
||||
import type {
|
||||
DoctorCheck,
|
||||
DoctorProviderInspection,
|
||||
@@ -174,13 +177,14 @@ const selectedRegistrationCheck = (
|
||||
}
|
||||
: registrationCheck(status);
|
||||
|
||||
const registrationCheck = (status: ClientRegistrationStatus): DoctorCheck => ({
|
||||
const registrationCheck = (
|
||||
status: UnhealthyClientRegistrationStatus,
|
||||
): DoctorCheck => ({
|
||||
name: `registration:${status.client}`,
|
||||
ok: false,
|
||||
classification: "config_drift",
|
||||
detail: status.config_path,
|
||||
remediation:
|
||||
status.remediation ?? "Run rea setup, then restart the affected client.",
|
||||
remediation: status.remediation,
|
||||
});
|
||||
|
||||
const selectedSkillCheck = (
|
||||
|
||||
@@ -151,13 +151,15 @@ export const summarizeElectronBoundaries = (
|
||||
},
|
||||
sender_validation_observations: validations.length,
|
||||
utility_processes: utilities.length,
|
||||
resolved_utility_entrypoints: utilities.filter(({ file, finding }) =>
|
||||
resolvesToFile({
|
||||
file,
|
||||
specifier: finding.module_path,
|
||||
context: finding.module_resolution_context ?? "module-specifier",
|
||||
files,
|
||||
}),
|
||||
resolved_utility_entrypoints: utilities.filter(
|
||||
({ file, finding }) =>
|
||||
finding.module_path !== null &&
|
||||
resolvesToFile({
|
||||
file,
|
||||
specifier: finding.module_path,
|
||||
context: finding.module_resolution_context,
|
||||
files,
|
||||
}),
|
||||
).length,
|
||||
native_addon_bindings: nativeBindings.length,
|
||||
resolved_native_addon_bindings: nativeBindings.filter(({ file, finding }) =>
|
||||
@@ -195,14 +197,13 @@ const isMainHandler = ({ finding }: ElectronIpcRecord): boolean =>
|
||||
|
||||
interface ResolveToFileInput {
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly specifier: string | null;
|
||||
readonly specifier: string;
|
||||
readonly context: "module-specifier" | "filesystem-expression";
|
||||
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
|
||||
readonly kind?: JavaScriptArtifactFile["kind"];
|
||||
}
|
||||
|
||||
const resolvesToFile = (input: ResolveToFileInput): boolean => {
|
||||
if (input.specifier === null) return false;
|
||||
const resolved = resolveArtifactPathByContext({
|
||||
declaredPath: input.specifier,
|
||||
sourcePath: input.file.path,
|
||||
|
||||
@@ -162,7 +162,7 @@ const addHandlerNode = (input: IpcHandlerInput): ApplicationNode => {
|
||||
identity: artifactLocalIdentity(
|
||||
file.sha256,
|
||||
"electron-ipc-handler",
|
||||
`${finding.side}:${finding.operation}:${finding.channel ?? finding.channel_expression ?? "[missing]"}:${electronRangeKey(handlerRange)}`,
|
||||
`${finding.side}:${finding.operation}:${finding.channel ?? finding.channel_expression}:${electronRangeKey(handlerRange)}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
|
||||
@@ -110,12 +110,15 @@ const addWindowPreload = (
|
||||
input: FindingInput<ElectronBrowserWindowFinding>,
|
||||
window: ApplicationNode,
|
||||
): void => {
|
||||
const declared = input.value.preload_path;
|
||||
if (declared === null) return;
|
||||
if (input.value.preload_path === null) return;
|
||||
const {
|
||||
preload_path: declared,
|
||||
preload_resolution_context: resolutionContext,
|
||||
} = input.value;
|
||||
const resolution = resolveArtifactPathByContext({
|
||||
declaredPath: declared,
|
||||
sourcePath: input.file.path,
|
||||
context: input.value.preload_resolution_context ?? "module-specifier",
|
||||
context: resolutionContext,
|
||||
files: input.context.filesByPath,
|
||||
});
|
||||
const role = createElectronRoleNode(input.context, {
|
||||
@@ -210,7 +213,7 @@ const addUtilityProcess = (
|
||||
identity: artifactLocalIdentity(
|
||||
file.sha256,
|
||||
"electron-utility-process",
|
||||
`${value.module_path ?? value.module_expression ?? "[missing]"}:${electronRangeKey(value.location)}`,
|
||||
`${value.module_path ?? value.module_expression}:${electronRangeKey(value.location)}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
@@ -248,7 +251,7 @@ const addUtilityProcess = (
|
||||
const resolution = resolveArtifactPathByContext({
|
||||
declaredPath: value.module_path,
|
||||
sourcePath: file.path,
|
||||
context: value.module_resolution_context ?? "module-specifier",
|
||||
context: value.module_resolution_context,
|
||||
files: context.filesByPath,
|
||||
});
|
||||
const resolved = resolution.resolved_path;
|
||||
|
||||
+4
-4
@@ -1,19 +1,19 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { EvidenceLedger } from "../../../src/application/EvidenceLedger.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import {
|
||||
createEvidenceBundle,
|
||||
parseEvidenceBundle,
|
||||
serializeEvidenceBundle,
|
||||
} from "../../../src/domain/evidenceBundle.js";
|
||||
} from "../domain/evidenceBundle.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
recordUnknownInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
type RecordUnknownInput,
|
||||
type ResidualUnknown,
|
||||
} from "../../../src/domain/residualUnknown.js";
|
||||
} from "../domain/residualUnknown.js";
|
||||
|
||||
const provider = { id: "fixture", name: "Fixture", version: "1" };
|
||||
const ledger = (): EvidenceLedger =>
|
||||
@@ -0,0 +1,194 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence, evidenceSchema } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { recordUnknownInputSchema } from "../domain/residualUnknown.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
|
||||
const TARGET: BinaryTarget = {
|
||||
path: "/tmp/fixture",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
};
|
||||
const PROVIDER = { id: "fixture", name: "Fixture provider", version: "1" };
|
||||
|
||||
describe("evidence ledger recording", () => {
|
||||
it("deduplicates and atomically imports bounded bundles", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
const ledger = new EvidenceLedger({ maxRecords: 1, maxBytes: 1_000_000 });
|
||||
expect(ledger.record(evidence)).toEqual({ ok: true, value: "added" });
|
||||
expect(ledger.record(evidence)).toEqual({ ok: true, value: "duplicate" });
|
||||
const relocated = createEvidence(
|
||||
{ ...TARGET, path: "/relocated/different-name" },
|
||||
PROVIDER,
|
||||
{ operation: "health", parameters: {}, result: true },
|
||||
);
|
||||
expect(relocated.evidence_id).toBe(evidence.evidence_id);
|
||||
expect(ledger.record(relocated)).toEqual({
|
||||
ok: true,
|
||||
value: "duplicate",
|
||||
});
|
||||
expect(ledger.import(createEvidenceBundle([evidence]))).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
|
||||
});
|
||||
expect(ledger.export().records).toEqual([evidence]);
|
||||
ledger.clear();
|
||||
expect(ledger.export().records).toEqual([]);
|
||||
});
|
||||
|
||||
it("treats canonical JSON key order as semantically irrelevant", () => {
|
||||
const evidence = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: { alpha: 1, beta: 2 },
|
||||
result: { alpha: 1, beta: 2 },
|
||||
});
|
||||
const reordered = evidenceSchema.parse({
|
||||
...evidence,
|
||||
parameters: { beta: 2, alpha: 1 },
|
||||
normalized_result: { beta: 2, alpha: 1 },
|
||||
});
|
||||
const ledger = new EvidenceLedger({ maxRecords: 1, maxBytes: 1_000_000 });
|
||||
expect(ledger.record(evidence)).toEqual({ ok: true, value: "added" });
|
||||
expect(ledger.record(reordered)).toEqual({
|
||||
ok: true,
|
||||
value: "duplicate",
|
||||
});
|
||||
});
|
||||
|
||||
it("returns typed record and byte limit failures without eviction", () => {
|
||||
const first = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
const second = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: { changed: true },
|
||||
result: true,
|
||||
});
|
||||
const recordBound = new EvidenceLedger({
|
||||
maxRecords: 1,
|
||||
maxBytes: 1_000_000,
|
||||
});
|
||||
expect(recordBound.record(first).ok).toBe(true);
|
||||
expect(recordBound.record(second)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 1 },
|
||||
});
|
||||
expect(recordBound.export().records).toEqual([first]);
|
||||
|
||||
const byteBound = new EvidenceLedger({ maxRecords: 10, maxBytes: 1 });
|
||||
expect(byteBound.record(first)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError", limit: "bytes", maximum: 1 },
|
||||
});
|
||||
expect(byteBound.export().records).toEqual([]);
|
||||
});
|
||||
|
||||
it("counts unknown revisions when enforcing direct record limits", () => {
|
||||
const ledger = new EvidenceLedger({
|
||||
maxRecords: 2,
|
||||
maxBytes: 1_000_000,
|
||||
});
|
||||
const mutation = createEvidence(undefined, PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: {},
|
||||
result: { action: "record" },
|
||||
});
|
||||
const unknown = recordUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
question: "What remains unresolved?",
|
||||
severity: "high",
|
||||
domain: "record-limit-test",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "shipped-artifact",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
expect(ledger.recordUnknown(unknown, mutation).ok).toBe(true);
|
||||
|
||||
const direct = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
});
|
||||
expect(ledger.record(direct)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError", limit: "records", maximum: 2 },
|
||||
});
|
||||
expect(ledger.export()).toMatchObject({
|
||||
records: [mutation],
|
||||
unknowns: [expect.objectContaining({ domain: "record-limit-test" })],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("evidence bundle imports", () => {
|
||||
it("rejects conflicting duplicate IDs without mutating the ledger", () => {
|
||||
const ledger = new EvidenceLedger({ maxRecords: 2, maxBytes: 1_000_000 });
|
||||
const first = createEvidence(TARGET, PROVIDER, {
|
||||
operation: "health",
|
||||
parameters: {},
|
||||
result: true,
|
||||
rawResult: { pid: 1 },
|
||||
});
|
||||
expect(ledger.record(first).ok).toBe(true);
|
||||
const bundle = createEvidenceBundle([first]);
|
||||
expect(
|
||||
ledger.import({
|
||||
...bundle,
|
||||
records: [{ ...first, normalized_result: false }],
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceIntegrityError" },
|
||||
});
|
||||
expect(ledger.export().records).toEqual([first]);
|
||||
});
|
||||
|
||||
it("atomically rejects Evidence plus unknown when the batch exceeds limits", () => {
|
||||
const ledger = new EvidenceLedger({ maxRecords: 2, maxBytes: 1_000_000 });
|
||||
const output = createEvidence(undefined, PROVIDER, {
|
||||
operation: "derived",
|
||||
parameters: {},
|
||||
result: { status: "unknown" },
|
||||
});
|
||||
const mutation = createEvidence(undefined, PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation/v1",
|
||||
operation: "record_unknown",
|
||||
parameters: {},
|
||||
result: { action: "record" },
|
||||
});
|
||||
const unknown = recordUnknownInputSchema.parse({
|
||||
approved: true,
|
||||
question: "What remains unresolved?",
|
||||
severity: "high",
|
||||
domain: "atomic-test",
|
||||
supporting_evidence_ids: [],
|
||||
contradicting_evidence_ids: [],
|
||||
required_authority: "shipped-artifact",
|
||||
required_confidence: "observed",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
expect(ledger.recordWithUnknown(output, unknown, mutation)).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "EvidenceLimitError" },
|
||||
});
|
||||
expect(ledger.export()).toMatchObject({ records: [], unknowns: [] });
|
||||
});
|
||||
});
|
||||
@@ -277,7 +277,7 @@ const invalidPackage = (
|
||||
const unavailablePackage = (
|
||||
file: JavaScriptArtifactFile,
|
||||
limitation: string,
|
||||
): JavaScriptPackageObservation => ({
|
||||
): JavaScriptPackageObservation & { readonly status: "unavailable" } => ({
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "unavailable",
|
||||
@@ -394,17 +394,24 @@ const collectSourceMapOriginals = (
|
||||
}
|
||||
}
|
||||
const omitted = total - sources.length;
|
||||
return {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: omitted === 0 ? "included" : "truncated",
|
||||
sources,
|
||||
omitted_sources: omitted,
|
||||
limitation:
|
||||
omitted === 0
|
||||
? null
|
||||
: "Original-source inventory reached the approved source-map limit.",
|
||||
};
|
||||
return omitted === 0
|
||||
? {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "included",
|
||||
sources,
|
||||
omitted_sources: 0,
|
||||
limitation: null,
|
||||
}
|
||||
: {
|
||||
path: file.path,
|
||||
sha256: file.sha256,
|
||||
status: "truncated",
|
||||
sources,
|
||||
omitted_sources: omitted,
|
||||
limitation:
|
||||
"Original-source inventory reached the approved source-map limit.",
|
||||
};
|
||||
};
|
||||
|
||||
const unavailableSourceMap = (
|
||||
|
||||
@@ -8,18 +8,35 @@ import type {
|
||||
} from "../domain/javascriptSemanticIr.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
|
||||
/** Parsed package metadata used only for static entrypoint discovery. */
|
||||
export interface JavaScriptPackageObservation {
|
||||
interface JavaScriptStructuredObservation {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly status: "included" | "invalid" | "unavailable";
|
||||
}
|
||||
|
||||
interface JavaScriptPackageValues {
|
||||
readonly name: string | null;
|
||||
readonly version: string | null;
|
||||
readonly main: string | null;
|
||||
readonly renderer: string | null;
|
||||
readonly limitation: string | null;
|
||||
}
|
||||
|
||||
/** Parsed package metadata used only for static entrypoint discovery. */
|
||||
export type JavaScriptPackageObservation = JavaScriptStructuredObservation &
|
||||
(
|
||||
| (JavaScriptPackageValues & {
|
||||
readonly status: "included";
|
||||
readonly limitation: null;
|
||||
})
|
||||
| {
|
||||
readonly status: "invalid" | "unavailable";
|
||||
readonly name: null;
|
||||
readonly version: null;
|
||||
readonly main: null;
|
||||
readonly renderer: null;
|
||||
readonly limitation: string;
|
||||
}
|
||||
);
|
||||
|
||||
/** One HTML script source observed without building or executing a DOM. */
|
||||
export interface JavaScriptHtmlScriptObservation {
|
||||
readonly html_path: string;
|
||||
@@ -36,24 +53,50 @@ export interface JavaScriptSourceMapOriginal {
|
||||
}
|
||||
|
||||
/** Bounded local source-map parse result. */
|
||||
export interface JavaScriptSourceMapObservation {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly status: "included" | "truncated" | "invalid" | "not-approved";
|
||||
readonly sources: readonly JavaScriptSourceMapOriginal[];
|
||||
readonly omitted_sources: number | null;
|
||||
readonly limitation: string | null;
|
||||
}
|
||||
export type JavaScriptSourceMapObservation = JavaScriptStructuredObservation &
|
||||
(
|
||||
| {
|
||||
readonly status: "included";
|
||||
readonly sources: readonly JavaScriptSourceMapOriginal[];
|
||||
readonly omitted_sources: 0;
|
||||
readonly limitation: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "truncated";
|
||||
readonly sources: readonly JavaScriptSourceMapOriginal[];
|
||||
readonly omitted_sources: number | null;
|
||||
readonly limitation: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "invalid" | "not-approved";
|
||||
readonly sources: readonly [];
|
||||
readonly omitted_sources: 0;
|
||||
readonly limitation: string;
|
||||
}
|
||||
);
|
||||
|
||||
/** Bounded parse status for one inventoried JSON module. */
|
||||
export interface JavaScriptJsonModuleObservation {
|
||||
readonly path: string;
|
||||
readonly sha256: string;
|
||||
readonly status: "included" | "invalid" | "unavailable";
|
||||
readonly top_level_keys: readonly string[];
|
||||
readonly omitted_top_level_keys: number | null;
|
||||
readonly limitation: string | null;
|
||||
}
|
||||
export type JavaScriptJsonModuleObservation = JavaScriptStructuredObservation &
|
||||
(
|
||||
| {
|
||||
readonly status: "included";
|
||||
readonly top_level_keys: readonly string[];
|
||||
readonly omitted_top_level_keys: number;
|
||||
readonly limitation: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "invalid";
|
||||
readonly top_level_keys: readonly [];
|
||||
readonly omitted_top_level_keys: 0;
|
||||
readonly limitation: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "unavailable";
|
||||
readonly top_level_keys: readonly [];
|
||||
readonly omitted_top_level_keys: null;
|
||||
readonly limitation: string;
|
||||
}
|
||||
);
|
||||
|
||||
/** One relevant file plus optional AST-only JavaScript facts. */
|
||||
export interface AnalyzedJavaScriptArtifactFile {
|
||||
|
||||
@@ -20,9 +20,10 @@ import {
|
||||
addJavaScriptSourceModules,
|
||||
} from "./JavaScriptModuleRelationships.js";
|
||||
import {
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
completeApplicationCoverage,
|
||||
partialApplicationCoverage,
|
||||
truncatedApplicationCoverage,
|
||||
} from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
addJavaScriptArtifactContainers,
|
||||
addJavaScriptArtifactFiles,
|
||||
@@ -108,24 +109,21 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
|
||||
malformedStructuredData ||
|
||||
partialJavaScript;
|
||||
if (context.analysis.truncated_scopes > 0)
|
||||
return partialReconstructionCoverage(
|
||||
return truncatedApplicationCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
truncationOmittedCount(context),
|
||||
true,
|
||||
);
|
||||
if (exactLimitOmissions > 0)
|
||||
return partialReconstructionCoverage(
|
||||
return truncatedApplicationCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
exactLimitOmissions,
|
||||
true,
|
||||
);
|
||||
if (unknownGap)
|
||||
return partialReconstructionCoverage(
|
||||
return partialApplicationCoverage(
|
||||
reconstructionLimits(context.input),
|
||||
null,
|
||||
false,
|
||||
);
|
||||
return completeReconstructionCoverage(reconstructionLimits(context.input));
|
||||
return completeApplicationCoverage(reconstructionLimits(context.input));
|
||||
};
|
||||
|
||||
const truncationOmittedCount = (
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import type { ApplicationGraphEvidence } from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import {
|
||||
completeApplicationCoverage,
|
||||
partialApplicationCoverage,
|
||||
truncatedApplicationCoverage,
|
||||
type ApplicationGraphEvidence,
|
||||
} from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
@@ -12,8 +17,6 @@ import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAcc
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
astObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
staticInferenceEvidence,
|
||||
unavailableAstEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
@@ -117,7 +120,7 @@ export const addArtifactContainsEdge = (
|
||||
: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: input.operation,
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -186,7 +189,7 @@ export const addUnavailableStaticParseScope = (
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: input.operation,
|
||||
coverage: partialReconstructionCoverage([], null, false),
|
||||
coverage: partialApplicationCoverage([], null),
|
||||
limitation: input.limitation,
|
||||
}),
|
||||
},
|
||||
@@ -201,7 +204,7 @@ export const addUnavailableStaticParseScope = (
|
||||
sha256: input.file.sha256,
|
||||
path: input.file.path,
|
||||
operation: "associate-unavailable-parse-scope",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
});
|
||||
};
|
||||
@@ -214,13 +217,10 @@ export const javascriptAnalysisCoverage = (
|
||||
input: JavaScriptArtifactReconstructionInput,
|
||||
): JavaScriptArtifactGraphCoverage =>
|
||||
analysis.parse_status === "complete"
|
||||
? completeReconstructionCoverage(javaScriptAnalysisLimits(input))
|
||||
: {
|
||||
status: "partial",
|
||||
truncated: analysis.parse_status === "truncated",
|
||||
omitted_count: null,
|
||||
limits: javaScriptAnalysisLimits(input),
|
||||
};
|
||||
? completeApplicationCoverage(javaScriptAnalysisLimits(input))
|
||||
: analysis.parse_status === "truncated"
|
||||
? truncatedApplicationCoverage(javaScriptAnalysisLimits(input), null)
|
||||
: partialApplicationCoverage(javaScriptAnalysisLimits(input), null);
|
||||
|
||||
/** Stable identity for a fact scoped to one exact artifact. */
|
||||
export const artifactLocalIdentity = (
|
||||
@@ -274,7 +274,7 @@ export const createElectronRoleNode = (
|
||||
sha256: input.anchor.sha256,
|
||||
path: input.anchor.path,
|
||||
operation: "discover-electron-entrypoint",
|
||||
coverage: input.coverage ?? completeReconstructionCoverage(),
|
||||
coverage: input.coverage ?? completeApplicationCoverage(),
|
||||
limitations: input.resolution.limitations,
|
||||
...(input.range === undefined ? {} : { range: input.range }),
|
||||
}),
|
||||
@@ -305,7 +305,7 @@ export const linkElectronRoleToAsset = (
|
||||
sha256: input.anchor.sha256,
|
||||
path: input.anchor.path,
|
||||
operation: "resolve-electron-entrypoint",
|
||||
coverage: input.coverage ?? completeReconstructionCoverage(),
|
||||
coverage: input.coverage ?? completeApplicationCoverage(),
|
||||
limitations: input.resolution.limitations,
|
||||
...(input.range === undefined ? {} : { range: input.range }),
|
||||
}),
|
||||
|
||||
@@ -5,11 +5,11 @@ import {
|
||||
linkElectronRoleToAsset,
|
||||
type JavaScriptArtifactGraphContext,
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import { artifactObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
completeApplicationCoverage,
|
||||
truncatedApplicationCoverage,
|
||||
} from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
|
||||
|
||||
/** Project HTML renderer entrypoints and their local script assets. */
|
||||
@@ -68,7 +68,7 @@ export const addJavaScriptHtmlRoles = (
|
||||
target: resolved,
|
||||
file: html,
|
||||
range: script.location,
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
relation: "loads",
|
||||
properties: {
|
||||
script_path: script.script_path,
|
||||
@@ -93,7 +93,7 @@ export const addJavaScriptSourceMapOriginals = (
|
||||
if (mapFile === undefined || mapNode === undefined) continue;
|
||||
const coverage =
|
||||
sourceMap.status === "truncated"
|
||||
? partialReconstructionCoverage(
|
||||
? truncatedApplicationCoverage(
|
||||
[
|
||||
{
|
||||
name: "max-source-map-sources",
|
||||
@@ -102,9 +102,8 @@ export const addJavaScriptSourceMapOriginals = (
|
||||
},
|
||||
],
|
||||
sourceMap.omitted_sources,
|
||||
true,
|
||||
)
|
||||
: completeReconstructionCoverage();
|
||||
: completeApplicationCoverage();
|
||||
for (const original of sourceMap.sources) {
|
||||
const node = context.accumulator.addNode({
|
||||
kind: "source-module",
|
||||
|
||||
@@ -111,28 +111,6 @@ export const unavailableAstEvidence = (
|
||||
evidence_ids: [],
|
||||
});
|
||||
|
||||
/** Complete local projection coverage under named hard limits. */
|
||||
export const completeReconstructionCoverage = (
|
||||
limits: ReconstructionEvidenceCoverage["limits"] = [],
|
||||
): ReconstructionEvidenceCoverage => ({
|
||||
status: "complete",
|
||||
truncated: false,
|
||||
omitted_count: 0,
|
||||
limits: [...limits],
|
||||
});
|
||||
|
||||
/** Partial reconstruction coverage with either exact truncation or a policy gap. */
|
||||
export const partialReconstructionCoverage = (
|
||||
limits: ReconstructionEvidenceCoverage["limits"],
|
||||
omitted: number | null,
|
||||
truncated: boolean,
|
||||
): ReconstructionEvidenceCoverage => ({
|
||||
status: "partial",
|
||||
truncated,
|
||||
omitted_count: omitted,
|
||||
limits: [...limits],
|
||||
});
|
||||
|
||||
const artifactReference = (sha256: string) => ({
|
||||
available: true as const,
|
||||
artifact_id: `art_${sha256}`,
|
||||
|
||||
@@ -78,7 +78,7 @@ const addReference = (
|
||||
identity: artifactLocalIdentity(
|
||||
input.file.sha256,
|
||||
input.value.kind,
|
||||
input.value.specifier ?? input.value.expression ?? "[dynamic]",
|
||||
input.value.specifier ?? input.value.expression,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
@@ -406,7 +406,7 @@ const unresolvedReferenceNode = (
|
||||
identity: artifactLocalIdentity(
|
||||
file.sha256,
|
||||
"unresolved-reference",
|
||||
`${reference.kind}:${reference.specifier ?? reference.expression ?? "[dynamic]"}`,
|
||||
`${reference.kind}:${reference.specifier ?? reference.expression}`,
|
||||
),
|
||||
observations: [
|
||||
{
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import { completeApplicationCoverage } from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type {
|
||||
JavaScriptArtifactContainer,
|
||||
@@ -17,7 +18,6 @@ import {
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
artifactObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
|
||||
@@ -61,7 +61,7 @@ export const createJavaScriptArtifactRootNode = (
|
||||
sha256: root.sha256,
|
||||
path: "artifact-root",
|
||||
operation: "inventory-root",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
limitations: [
|
||||
"artifact-root is a path-independent alias; the application result retains the canonical local input path.",
|
||||
],
|
||||
@@ -91,7 +91,7 @@ export const addJavaScriptArtifactContainers = (
|
||||
sha256: container.sha256,
|
||||
path: container.path,
|
||||
operation: "inventory-nested-asar",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
@@ -106,7 +106,7 @@ export const addJavaScriptArtifactContainers = (
|
||||
sha256: context.snapshot.manifest.root_sha256,
|
||||
path: container.path,
|
||||
operation: "inventory-nested-asar",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -147,7 +147,7 @@ export const addJavaScriptArtifactFiles = (
|
||||
sha256: file.container_sha256,
|
||||
path: file.path,
|
||||
operation: "map-entry-content",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
});
|
||||
}
|
||||
@@ -167,16 +167,12 @@ export const addJavaScriptArtifactFiles = (
|
||||
const packageValue = context.analysis.packages.find(
|
||||
({ path }) => path === file.path,
|
||||
);
|
||||
if (
|
||||
packageValue?.status !== undefined &&
|
||||
packageValue.status !== "included"
|
||||
)
|
||||
if (packageValue !== undefined && packageValue.status !== "included")
|
||||
addUnavailableStaticParseScope(context, {
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-package-json",
|
||||
limitation:
|
||||
packageValue.limitation ?? "Package metadata could not be parsed.",
|
||||
limitation: packageValue.limitation,
|
||||
});
|
||||
const jsonValue = context.analysis.json_modules.find(
|
||||
({ path }) => path === file.path,
|
||||
@@ -186,8 +182,7 @@ export const addJavaScriptArtifactFiles = (
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-json-module",
|
||||
limitation:
|
||||
jsonValue.limitation ?? "JSON module content could not be parsed.",
|
||||
limitation: jsonValue.limitation,
|
||||
});
|
||||
const sourceMap = context.analysis.source_maps.find(
|
||||
({ path }) => path === file.path,
|
||||
@@ -200,8 +195,7 @@ export const addJavaScriptArtifactFiles = (
|
||||
file,
|
||||
asset: target,
|
||||
operation: "parse-local-source-map",
|
||||
limitation:
|
||||
sourceMap.limitation ?? "Source-map content could not be parsed.",
|
||||
limitation: sourceMap.limitation,
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -232,7 +226,7 @@ export const addJavaScriptPackageNodes = (
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "parse-package-json",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
limitations:
|
||||
packageValue.limitation === null ? [] : [packageValue.limitation],
|
||||
}),
|
||||
@@ -250,7 +244,7 @@ export const addJavaScriptPackageNodes = (
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "associate-package-artifact",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
});
|
||||
} else
|
||||
@@ -312,7 +306,7 @@ const createFileTarget = (
|
||||
sha256: file.sha256,
|
||||
path: file.path,
|
||||
operation: "inventory-relevant-file",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
@@ -348,7 +342,7 @@ const createAsarEntry = (
|
||||
sha256: file.container_sha256,
|
||||
path: file.path,
|
||||
operation: "inventory-asar-entry",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
}),
|
||||
},
|
||||
],
|
||||
@@ -390,7 +384,7 @@ const addPackageRole = (
|
||||
sha256: input.packageFile.sha256,
|
||||
path: input.packageFile.path,
|
||||
operation: "discover-package-entrypoint",
|
||||
coverage: completeReconstructionCoverage(),
|
||||
coverage: completeApplicationCoverage(),
|
||||
limitations: resolution.limitations,
|
||||
}),
|
||||
});
|
||||
|
||||
+3
-3
@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
resolveArtifactPathByContext,
|
||||
type ResolveArtifactPathInput,
|
||||
} from "../../../src/application/JavaScriptArtifactPathResolution.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
|
||||
import { analyzeJavaScriptStaticSource } from "../../../src/domain/javascriptStaticAnalysis.js";
|
||||
} from "./JavaScriptArtifactPathResolution.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
import { analyzeJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
|
||||
|
||||
describe("contextual JavaScript artifact path resolution", () => {
|
||||
it.each([
|
||||
@@ -3,33 +3,42 @@ import { posix } from "node:path";
|
||||
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
|
||||
/** Explicit outcome of bounded, artifact-confined path resolution. */
|
||||
export interface ArtifactPathResolution {
|
||||
type ArtifactPathResolutionContext =
|
||||
| "package-entrypoint"
|
||||
| "filesystem-expression"
|
||||
| "module-specifier"
|
||||
| "html-reference";
|
||||
|
||||
type UnresolvedArtifactPathStatus =
|
||||
| "not-found"
|
||||
| "unavailable"
|
||||
| "external"
|
||||
| "rejected";
|
||||
|
||||
interface ArtifactPathResolutionBase {
|
||||
readonly declared_path: string;
|
||||
readonly resolution_context:
|
||||
| "package-entrypoint"
|
||||
| "filesystem-expression"
|
||||
| "module-specifier"
|
||||
| "html-reference";
|
||||
readonly resolved_path: string | null;
|
||||
readonly resolution_status:
|
||||
| "resolved"
|
||||
| "not-found"
|
||||
| "unavailable"
|
||||
| "external"
|
||||
| "rejected";
|
||||
readonly resolution_context: ArtifactPathResolutionContext;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Explicit outcome of bounded, artifact-confined path resolution. */
|
||||
export type ArtifactPathResolution = ArtifactPathResolutionBase &
|
||||
(
|
||||
| {
|
||||
readonly resolved_path: string;
|
||||
readonly resolution_status: "resolved";
|
||||
}
|
||||
| {
|
||||
readonly resolved_path: null;
|
||||
readonly resolution_status: UnresolvedArtifactPathStatus;
|
||||
}
|
||||
);
|
||||
|
||||
/** Values needed to resolve a declaration without filesystem access. */
|
||||
export interface ResolveArtifactPathInput {
|
||||
readonly declaredPath: string;
|
||||
readonly sourcePath: string;
|
||||
readonly context:
|
||||
| "package-entrypoint"
|
||||
| "filesystem-expression"
|
||||
| "module-specifier"
|
||||
| "html-reference";
|
||||
readonly context: ArtifactPathResolutionContext;
|
||||
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
|
||||
readonly htmlBaseHref?: string | null;
|
||||
readonly moduleKind?: "import" | "require";
|
||||
@@ -50,11 +59,17 @@ const NODE_BUILTINS = new Set(
|
||||
builtinModules.map((name) => name.replace(/^node:/u, "")),
|
||||
);
|
||||
|
||||
interface CandidateResolution {
|
||||
readonly resolvedPath: string | null;
|
||||
readonly status: ArtifactPathResolution["resolution_status"];
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
type CandidateResolution =
|
||||
| {
|
||||
readonly resolvedPath: string;
|
||||
readonly status: "resolved";
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
| {
|
||||
readonly resolvedPath: null;
|
||||
readonly status: UnresolvedArtifactPathStatus;
|
||||
readonly limitations: readonly string[];
|
||||
};
|
||||
|
||||
/** Resolve one declaration under its exact syntax/metadata context. */
|
||||
export const resolveArtifactPathByContext = (
|
||||
@@ -72,12 +87,7 @@ const resolveAtDepth = (
|
||||
const confined = confineCandidate(input, candidate);
|
||||
if (typeof confined !== "string") return confined;
|
||||
const resolved = resolveCandidate(input, confined, packageDepth);
|
||||
return outcome(
|
||||
input,
|
||||
resolved.status,
|
||||
resolved.resolvedPath,
|
||||
resolved.limitations,
|
||||
);
|
||||
return outcome(input, resolved);
|
||||
};
|
||||
|
||||
const rejectDeclaration = (
|
||||
@@ -85,17 +95,19 @@ const rejectDeclaration = (
|
||||
): ArtifactPathResolution | null => {
|
||||
const declared = input.declaredPath;
|
||||
if (declared.length === 0)
|
||||
return outcome(input, "rejected", null, ["The declared path is empty."]);
|
||||
return unresolvedOutcome(input, "rejected", [
|
||||
"The declared path is empty.",
|
||||
]);
|
||||
if (declared.length > 4_096)
|
||||
return outcome(input, "rejected", null, [
|
||||
return unresolvedOutcome(input, "rejected", [
|
||||
"The declared path exceeds the 4096-character resolution bound.",
|
||||
]);
|
||||
if (declared.includes("\0") || declared.includes("\\"))
|
||||
return outcome(input, "rejected", null, [
|
||||
return unresolvedOutcome(input, "rejected", [
|
||||
"NUL and backslash path syntax are not admitted for canonical artifact paths.",
|
||||
]);
|
||||
if (/%(?:2e|2f|5c)/iu.test(declared))
|
||||
return outcome(input, "rejected", null, [
|
||||
return unresolvedOutcome(input, "rejected", [
|
||||
"Encoded dot or separator bytes are rejected before artifact path resolution.",
|
||||
]);
|
||||
return null;
|
||||
@@ -114,13 +126,13 @@ const contextualCandidate = (
|
||||
const fileUrl = fileUrlPath(declared);
|
||||
if (fileUrl !== undefined) return fileUrl;
|
||||
if (hasScheme(declared))
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"URL and Node builtin schemes are outside static artifact module resolution.",
|
||||
]);
|
||||
if (!declared.startsWith(".") && !declared.startsWith("/"))
|
||||
return bareModuleCandidate(input, declared);
|
||||
} else if (hasScheme(declared))
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"URL schemes are outside this local artifact path context.",
|
||||
]);
|
||||
const relative = declared.startsWith("/") ? declared.slice(1) : declared;
|
||||
@@ -139,11 +151,11 @@ const bareModuleCandidate = (
|
||||
NODE_BUILTINS.has(packageName) ||
|
||||
declared.startsWith("#")
|
||||
)
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"The bare specifier is a Node builtin, package import map, or invalid package name.",
|
||||
]);
|
||||
if (declared !== packageName)
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"Bare package subpaths remain unresolved unless an exact package-exports subpath model is available.",
|
||||
]);
|
||||
const source = input.files.get(input.sourcePath);
|
||||
@@ -155,7 +167,7 @@ const bareModuleCandidate = (
|
||||
if (directory === "." || directory === "") break;
|
||||
directory = posix.dirname(directory);
|
||||
}
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"No matching bare package was inventoried in an enclosing node_modules directory.",
|
||||
]);
|
||||
};
|
||||
@@ -190,7 +202,7 @@ const htmlCandidate = (
|
||||
): string | ArtifactPathResolution => {
|
||||
const declared = stripQueryAndFragment(input.declaredPath);
|
||||
if (hasScheme(declared))
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"External HTML references are not mapped to local artifact assets.",
|
||||
]);
|
||||
if (declared.startsWith("/")) return declared.slice(1);
|
||||
@@ -198,7 +210,7 @@ const htmlCandidate = (
|
||||
if (base === undefined || base === null || base === "")
|
||||
return posix.join(posix.dirname(input.sourcePath), declared);
|
||||
if (hasScheme(base))
|
||||
return outcome(input, "external", null, [
|
||||
return unresolvedOutcome(input, "external", [
|
||||
"The document base href is external, so its script reference is not a local artifact path.",
|
||||
]);
|
||||
const basePath = base.startsWith("/")
|
||||
@@ -218,7 +230,7 @@ const confineCandidate = (
|
||||
normalized.startsWith("../") ||
|
||||
normalized.startsWith("/")
|
||||
)
|
||||
return outcome(input, "rejected", null, [
|
||||
return unresolvedOutcome(input, "rejected", [
|
||||
"The resolved candidate escapes the canonical artifact root.",
|
||||
]);
|
||||
return normalized === "." ? "" : normalized;
|
||||
@@ -282,11 +294,17 @@ const resolveCandidate = (
|
||||
},
|
||||
packageDepth + 1,
|
||||
);
|
||||
return {
|
||||
resolvedPath: nested.resolved_path,
|
||||
status: nested.resolution_status,
|
||||
limitations: nested.limitations,
|
||||
};
|
||||
return nested.resolution_status === "resolved"
|
||||
? {
|
||||
resolvedPath: nested.resolved_path,
|
||||
status: nested.resolution_status,
|
||||
limitations: nested.limitations,
|
||||
}
|
||||
: {
|
||||
resolvedPath: null,
|
||||
status: nested.resolution_status,
|
||||
limitations: nested.limitations,
|
||||
};
|
||||
};
|
||||
|
||||
const directCandidates = (candidate: string): readonly string[] => [
|
||||
@@ -374,13 +392,27 @@ const stripQueryAndFragment = (value: string): string =>
|
||||
|
||||
const outcome = (
|
||||
input: ResolveArtifactPathInput,
|
||||
status: ArtifactPathResolution["resolution_status"],
|
||||
resolvedPath: string | null,
|
||||
resolution: CandidateResolution,
|
||||
): ArtifactPathResolution =>
|
||||
resolution.status === "resolved"
|
||||
? {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
resolved_path: resolution.resolvedPath,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
}
|
||||
: {
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
resolved_path: null,
|
||||
resolution_status: resolution.status,
|
||||
limitations: resolution.limitations,
|
||||
};
|
||||
|
||||
const unresolvedOutcome = (
|
||||
input: ResolveArtifactPathInput,
|
||||
status: UnresolvedArtifactPathStatus,
|
||||
limitations: readonly string[],
|
||||
): ArtifactPathResolution => ({
|
||||
declared_path: input.declaredPath,
|
||||
resolution_context: input.context,
|
||||
resolved_path: resolvedPath,
|
||||
resolution_status: status,
|
||||
limitations,
|
||||
});
|
||||
): ArtifactPathResolution =>
|
||||
outcome(input, { resolvedPath: null, status, limitations });
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { posix } from "node:path";
|
||||
|
||||
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
|
||||
import {
|
||||
completeApplicationCoverage,
|
||||
partialApplicationCoverage,
|
||||
truncatedApplicationCoverage,
|
||||
} from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type {
|
||||
JavaScriptModuleOrigin,
|
||||
JavaScriptSemanticIr,
|
||||
@@ -16,11 +21,12 @@ import {
|
||||
} from "./JavaScriptArtifactGraphContext.js";
|
||||
import {
|
||||
astObservationEvidence,
|
||||
completeReconstructionCoverage,
|
||||
partialReconstructionCoverage,
|
||||
staticInferenceEvidence,
|
||||
} from "./JavaScriptArtifactGraphEvidence.js";
|
||||
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
|
||||
import {
|
||||
resolveArtifactPathByContext,
|
||||
type ArtifactPathResolution,
|
||||
} from "./JavaScriptArtifactPathResolution.js";
|
||||
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
|
||||
|
||||
interface SemanticAnalysis {
|
||||
@@ -36,18 +42,24 @@ interface RelationshipInput {
|
||||
readonly link: JavaScriptSemanticModuleLink;
|
||||
}
|
||||
|
||||
interface ResolvedModuleTarget {
|
||||
type ResolvedModuleTarget = {
|
||||
readonly node: ApplicationNode;
|
||||
readonly path: string | null;
|
||||
readonly file: JavaScriptArtifactFile | null;
|
||||
readonly status:
|
||||
| "resolved"
|
||||
| "not-found"
|
||||
| "unavailable"
|
||||
| "external"
|
||||
| "rejected";
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
} & (
|
||||
| {
|
||||
readonly path: string;
|
||||
readonly file: JavaScriptArtifactFile;
|
||||
readonly status: "resolved";
|
||||
}
|
||||
| {
|
||||
readonly path: null;
|
||||
readonly file: null;
|
||||
readonly status: Exclude<
|
||||
ArtifactPathResolution["resolution_status"],
|
||||
"resolved"
|
||||
>;
|
||||
}
|
||||
);
|
||||
|
||||
/** Create one path-scoped source-module identity for every analyzed source file. */
|
||||
export const addJavaScriptSourceModules = (
|
||||
@@ -239,26 +251,32 @@ const resolveModuleTarget = (
|
||||
? "require"
|
||||
: "import",
|
||||
});
|
||||
const path = resolution.resolved_path;
|
||||
const file = path === null ? undefined : input.context.filesByPath.get(path);
|
||||
const node =
|
||||
path === null
|
||||
? undefined
|
||||
: (input.context.sourceModuleNodes.get(path) ??
|
||||
input.context.fileNodes.get(path));
|
||||
if (path !== null && file !== undefined && node !== undefined)
|
||||
if (resolution.resolution_status !== "resolved")
|
||||
return {
|
||||
node,
|
||||
path,
|
||||
file,
|
||||
status: "resolved",
|
||||
node: unresolvedModuleNode(
|
||||
input,
|
||||
specifier,
|
||||
resolution.resolution_status,
|
||||
),
|
||||
path: null,
|
||||
file: null,
|
||||
status: resolution.resolution_status,
|
||||
limitations: resolution.limitations,
|
||||
};
|
||||
const path = resolution.resolved_path;
|
||||
const file = input.context.filesByPath.get(path);
|
||||
const node =
|
||||
input.context.sourceModuleNodes.get(path) ??
|
||||
input.context.fileNodes.get(path);
|
||||
if (file === undefined || node === undefined)
|
||||
throw new TypeError(
|
||||
`Resolved artifact path ${path} is absent from its graph context.`,
|
||||
);
|
||||
return {
|
||||
node: unresolvedModuleNode(input, specifier, resolution.resolution_status),
|
||||
path: null,
|
||||
file: null,
|
||||
status: resolution.resolution_status,
|
||||
node,
|
||||
path,
|
||||
file,
|
||||
status: "resolved",
|
||||
limitations: resolution.limitations,
|
||||
};
|
||||
};
|
||||
@@ -266,7 +284,7 @@ const resolveModuleTarget = (
|
||||
const unresolvedModuleNode = (
|
||||
input: RelationshipInput,
|
||||
specifier: string,
|
||||
status: ResolvedModuleTarget["status"],
|
||||
status: Exclude<ResolvedModuleTarget["status"], "resolved">,
|
||||
): ApplicationNode =>
|
||||
input.context.accumulator.addNode({
|
||||
kind: "javascript-module",
|
||||
@@ -360,12 +378,10 @@ const semanticCoverage = (
|
||||
unit: "items" as const,
|
||||
}));
|
||||
if (semantic.ir.coverage.status === "complete")
|
||||
return completeReconstructionCoverage(limits);
|
||||
return partialReconstructionCoverage(
|
||||
limits,
|
||||
semantic.ir.coverage.omittedCount,
|
||||
semantic.ir.coverage.status === "truncated",
|
||||
);
|
||||
return completeApplicationCoverage(limits);
|
||||
return semantic.ir.coverage.status === "truncated"
|
||||
? truncatedApplicationCoverage(limits, semantic.ir.coverage.omittedCount)
|
||||
: partialApplicationCoverage(limits, semantic.ir.coverage.omittedCount);
|
||||
};
|
||||
|
||||
const moduleFormat = (
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
partialApplicationCoverage,
|
||||
truncatedApplicationCoverage,
|
||||
} from "../domain/javascriptApplicationEvidenceSchemas.js";
|
||||
import type {
|
||||
JavaScriptSemanticIr,
|
||||
JavaScriptSemanticCallable,
|
||||
@@ -7,7 +11,6 @@ import type {
|
||||
import { flattenSemanticReturnValue } from "../domain/javascriptSemanticReturns.js";
|
||||
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js";
|
||||
import { partialReconstructionCoverage } from "./JavaScriptArtifactGraphEvidence.js";
|
||||
|
||||
const MAX_PROJECTED_RETURN_SHAPES = 32;
|
||||
const MAX_PROJECTED_RETURN_FIELDS = 64;
|
||||
@@ -43,30 +46,31 @@ export const projectJavaScriptExportReturnShapes = (input: {
|
||||
input.baseCoverage.status === "complete" &&
|
||||
callable.returnCoverage.status === "complete" &&
|
||||
projectionOmitted === 0;
|
||||
const limits = [
|
||||
...input.baseCoverage.limits,
|
||||
{
|
||||
name: "return-shape-sites",
|
||||
value: MAX_PROJECTED_RETURN_SHAPES,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "return-shape-fields",
|
||||
value: MAX_PROJECTED_RETURN_FIELDS,
|
||||
unit: "items" as const,
|
||||
},
|
||||
{
|
||||
name: "return-shape-property-coverage",
|
||||
value: MAX_PROJECTED_PROPERTY_COVERAGE,
|
||||
unit: "items" as const,
|
||||
},
|
||||
];
|
||||
const omitted =
|
||||
semanticOmitted === null ? null : semanticOmitted + projectionOmitted;
|
||||
const coverage = complete
|
||||
? input.baseCoverage
|
||||
: partialReconstructionCoverage(
|
||||
[
|
||||
...input.baseCoverage.limits,
|
||||
{
|
||||
name: "return-shape-sites",
|
||||
value: MAX_PROJECTED_RETURN_SHAPES,
|
||||
unit: "items",
|
||||
},
|
||||
{
|
||||
name: "return-shape-fields",
|
||||
value: MAX_PROJECTED_RETURN_FIELDS,
|
||||
unit: "items",
|
||||
},
|
||||
{
|
||||
name: "return-shape-property-coverage",
|
||||
value: MAX_PROJECTED_PROPERTY_COVERAGE,
|
||||
unit: "items",
|
||||
},
|
||||
],
|
||||
semanticOmitted === null ? null : semanticOmitted + projectionOmitted,
|
||||
callable.returnCoverage.status === "truncated" || projectionOmitted > 0,
|
||||
);
|
||||
: callable.returnCoverage.status === "truncated" || projectionOmitted > 0
|
||||
? truncatedApplicationCoverage(limits, omitted)
|
||||
: partialApplicationCoverage(limits, omitted);
|
||||
const limitations = [
|
||||
...input.ir.limitations,
|
||||
"Return shapes are inferred from inert syntax and do not prove runtime behavior.",
|
||||
|
||||
+6
-6
@@ -1,14 +1,14 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js";
|
||||
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
|
||||
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../domain/javascriptSemanticQuery.js";
|
||||
import { analyzeJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
|
||||
type JavaScriptSemanticLimits,
|
||||
} from "../../../src/domain/javascriptSemanticIr.js";
|
||||
} from "../domain/javascriptSemanticIr.js";
|
||||
|
||||
const SHA256 = "a".repeat(64);
|
||||
const GRAPH_ID = `jag_${"b".repeat(64)}`;
|
||||
+6
-6
@@ -1,14 +1,14 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js";
|
||||
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js";
|
||||
import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
|
||||
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
|
||||
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
|
||||
import { queryJavaScriptSemanticGraph } from "../domain/javascriptSemanticQuery.js";
|
||||
import { analyzeJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
|
||||
import {
|
||||
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
|
||||
type JavaScriptSemanticLimits,
|
||||
} from "../../../src/domain/javascriptSemanticIr.js";
|
||||
} from "../domain/javascriptSemanticIr.js";
|
||||
|
||||
const SHA256 = "a".repeat(64);
|
||||
const GRAPH_ID = `jag_${"b".repeat(64)}`;
|
||||
@@ -64,14 +64,24 @@ export const linuxHopperInstallDisclosure = (
|
||||
};
|
||||
};
|
||||
|
||||
/** Parsed Linux distribution information used for support and package selection. */
|
||||
export interface LinuxDistribution {
|
||||
interface LinuxDistributionIdentity {
|
||||
readonly id: string;
|
||||
readonly versionId?: string;
|
||||
readonly packageFamily: LinuxPackageFamily | undefined;
|
||||
readonly supported: boolean;
|
||||
}
|
||||
|
||||
/** Parsed Linux distribution information used for support and package selection. */
|
||||
export type LinuxDistribution = LinuxDistributionIdentity &
|
||||
(
|
||||
| {
|
||||
readonly packageFamily: LinuxPackageFamily;
|
||||
readonly supported: true;
|
||||
}
|
||||
| {
|
||||
readonly packageFamily: LinuxPackageFamily | undefined;
|
||||
readonly supported: false;
|
||||
}
|
||||
);
|
||||
|
||||
/** Download response kept independent of Node's global fetch implementation. */
|
||||
export interface LinuxHopperDownload {
|
||||
readonly ok: boolean;
|
||||
@@ -134,15 +144,17 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
|
||||
const versionId = fields.get("VERSION_ID");
|
||||
const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE"));
|
||||
const supported =
|
||||
id === "arch" ||
|
||||
(id === "ubuntu" && versionAtLeast(versionId, 24)) ||
|
||||
(id === "fedora" && versionAtLeast(versionId, 41));
|
||||
return {
|
||||
packageFamily !== undefined &&
|
||||
(id === "arch" ||
|
||||
(id === "ubuntu" && versionAtLeast(versionId, 24)) ||
|
||||
(id === "fedora" && versionAtLeast(versionId, 41)));
|
||||
const identity = {
|
||||
id,
|
||||
...(versionId === undefined ? {} : { versionId }),
|
||||
packageFamily,
|
||||
supported,
|
||||
};
|
||||
return supported
|
||||
? { ...identity, packageFamily, supported: true }
|
||||
: { ...identity, packageFamily, supported: false };
|
||||
};
|
||||
|
||||
/** Read and classify the current Linux distribution. */
|
||||
@@ -169,10 +181,7 @@ export const installLinuxHopper = async (
|
||||
if (options.signal?.aborted === true)
|
||||
return { status: "failed", reason: "cancelled" };
|
||||
const distribution = await host.distribution();
|
||||
if (
|
||||
distribution?.supported !== true ||
|
||||
distribution.packageFamily === undefined
|
||||
)
|
||||
if (distribution?.supported !== true)
|
||||
return { status: "failed", reason: "unsupported_host" };
|
||||
let temporary: string | undefined;
|
||||
try {
|
||||
|
||||
@@ -97,7 +97,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
|
||||
operation_identity: operationIdentity(input, staticEvidence),
|
||||
},
|
||||
"read",
|
||||
{ restartRequired: true },
|
||||
{ remediation: "restart" },
|
||||
);
|
||||
if (!authorized.ok)
|
||||
return err(
|
||||
|
||||
@@ -18,7 +18,10 @@ import {
|
||||
reloadPermissionCeilings,
|
||||
revokePermission,
|
||||
} from "../domain/permissionPolicy.js";
|
||||
import { PermissionRequiredError } from "../domain/errors.js";
|
||||
import {
|
||||
PermissionRequiredError,
|
||||
type PermissionRemediation,
|
||||
} from "../domain/errors.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Failure to establish a filesystem object's canonical authorization identity. */
|
||||
@@ -108,8 +111,7 @@ const errorReason = (error: unknown): PermissionPathError["reason"] =>
|
||||
isNotFound(error) ? "not_found" : "io";
|
||||
|
||||
interface PermissionEvaluationOptions {
|
||||
readonly elicitationSupported?: boolean;
|
||||
readonly restartRequired?: boolean;
|
||||
readonly remediation?: PermissionRemediation;
|
||||
}
|
||||
|
||||
interface CanonicalPermissionDecision {
|
||||
@@ -131,16 +133,22 @@ type PermissionAuthorizationResult = Promise<
|
||||
export class PermissionAuthority {
|
||||
private policy: PermissionPolicy;
|
||||
private readonly configuredAuthority: PermissionAuthority | undefined;
|
||||
private readonly outsideCeilingRestartRequired: boolean;
|
||||
private readonly outsideCeilingRemediation: Exclude<
|
||||
PermissionRemediation,
|
||||
"elicit"
|
||||
>;
|
||||
|
||||
constructor(
|
||||
policy: PermissionPolicy,
|
||||
configuredAuthority?: PermissionAuthority,
|
||||
outsideCeilingRestartRequired = false,
|
||||
outsideCeilingRemediation: Exclude<
|
||||
PermissionRemediation,
|
||||
"elicit"
|
||||
> = "configure",
|
||||
) {
|
||||
this.policy = policy;
|
||||
this.configuredAuthority = configuredAuthority;
|
||||
this.outsideCeilingRestartRequired = outsideCeilingRestartRequired;
|
||||
this.outsideCeilingRemediation = outsideCeilingRemediation;
|
||||
}
|
||||
|
||||
/** Create a connection-owned overlay for once and session grants. */
|
||||
@@ -148,7 +156,7 @@ export class PermissionAuthority {
|
||||
return new PermissionAuthority(
|
||||
createPermissionPolicy([]),
|
||||
this.configuredAuthority ?? this,
|
||||
true,
|
||||
"restart",
|
||||
);
|
||||
}
|
||||
|
||||
@@ -273,15 +281,18 @@ export class PermissionAuthority {
|
||||
if (denied.allowed) return ok({ decision: denied, owner: this });
|
||||
const outsideAdministratorCeiling =
|
||||
denied.reason === "outside_administrator_ceiling";
|
||||
const requestedRemediation = options.remediation ?? "configure";
|
||||
const remediation =
|
||||
outsideAdministratorCeiling && requestedRemediation !== "restart"
|
||||
? this.outsideCeilingRemediation
|
||||
: requestedRemediation;
|
||||
return err(
|
||||
new PermissionRequiredError(
|
||||
request,
|
||||
denied.missing,
|
||||
ceilingFor(effective, request.capability),
|
||||
!outsideAdministratorCeiling && (options.elicitationSupported ?? false),
|
||||
options.restartRequired ??
|
||||
(outsideAdministratorCeiling && this.outsideCeilingRestartRequired),
|
||||
),
|
||||
new PermissionRequiredError({
|
||||
requested: request,
|
||||
missing: denied.missing,
|
||||
ceiling: ceilingFor(effective, request.capability),
|
||||
remediation,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,9 +9,11 @@ import type {
|
||||
FilesystemCheckpoint,
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessPolicyDecision,
|
||||
ProcessSample,
|
||||
ProcessSettlement,
|
||||
ProcessScenario,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
RecordProcessCaptureEvent,
|
||||
@@ -71,25 +73,43 @@ interface CaptureResultOptions {
|
||||
};
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly replay: LoopbackReplay;
|
||||
readonly reactiveRun: ProcessCapture["reactive_run"];
|
||||
readonly before: SnapshotResult;
|
||||
readonly after: SnapshotResult;
|
||||
readonly truncated: boolean;
|
||||
readonly scenario: ProcessScenario;
|
||||
readonly rootPid: number;
|
||||
readonly samplingPartial: boolean;
|
||||
readonly renderedFrames: ProcessCapture["rendered_frames"];
|
||||
readonly renderedFrames: UnverifiedProcessCapture["rendered_frames"];
|
||||
readonly interactions: readonly InteractionEvent[];
|
||||
readonly checkpoints: readonly FilesystemCheckpoint[];
|
||||
readonly shimEvents: ProcessCapture["shim_events"];
|
||||
readonly settlement: ProcessCapture["settlement"];
|
||||
readonly manifest: ProcessCapture["manifest"];
|
||||
readonly shimEvents: UnverifiedProcessCapture["shim_events"];
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
readonly manifest: UnverifiedProcessCapture["manifest"];
|
||||
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
|
||||
}
|
||||
|
||||
/** Settlement observation before process-resource cleanup has completed. */
|
||||
export type ObservedProcessSettlement =
|
||||
| Pick<
|
||||
Extract<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>
|
||||
| Pick<
|
||||
Exclude<ProcessSettlement, { readonly state: "quiesced" }>,
|
||||
"state" | "elapsed_ms"
|
||||
>;
|
||||
|
||||
/** Capture observations that cannot yet claim final cleanup or reactive state. */
|
||||
export type PendingProcessCapture = Omit<
|
||||
UnverifiedProcessCapture,
|
||||
"cleanup" | "reactive_run" | "settlement"
|
||||
> & {
|
||||
readonly settlement: ObservedProcessSettlement;
|
||||
};
|
||||
|
||||
export const buildCaptureResult = (
|
||||
options: CaptureResultOptions,
|
||||
): ProcessCapture => ({
|
||||
): PendingProcessCapture => ({
|
||||
schema_version: 4,
|
||||
manifest: options.manifest,
|
||||
normalization: options.scenario.normalization,
|
||||
@@ -117,7 +137,6 @@ export const buildCaptureResult = (
|
||||
options.scenario,
|
||||
),
|
||||
replay_transitions: options.replay.transitions,
|
||||
reactive_run: options.reactiveRun,
|
||||
event_journal: options.eventJournal,
|
||||
files_before: options.before.files,
|
||||
files_after: options.after.files,
|
||||
@@ -144,10 +163,6 @@ export const buildCaptureResult = (
|
||||
reason: "External network isolation is not enforced by this adapter.",
|
||||
},
|
||||
],
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
});
|
||||
|
||||
const hashFile = async (path: string): Promise<string> => {
|
||||
@@ -160,7 +175,7 @@ export const createRunManifest = async (
|
||||
scenario: ProcessScenario,
|
||||
startedAt: Date,
|
||||
completedAt: Date,
|
||||
): Promise<ProcessCapture["manifest"]> => {
|
||||
): Promise<UnverifiedProcessCapture["manifest"]> => {
|
||||
const executableSha256 = await hashFile(scenario.executable);
|
||||
const scenarioCommitment = processScenarioCommitment(
|
||||
scenario,
|
||||
@@ -193,7 +208,7 @@ export const observeSettlement = async (
|
||||
processGroupIds: readonly number[],
|
||||
settleMs: number,
|
||||
recordEvent: RecordProcessCaptureEvent = () => undefined,
|
||||
): Promise<Omit<ProcessCapture["settlement"], "cleanup_outcome">> => {
|
||||
): Promise<ObservedProcessSettlement> => {
|
||||
if (process.platform === "win32") {
|
||||
recordEvent("lifecycle", 1);
|
||||
return { state: "unverifiable", elapsed_ms: 0 };
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { processCapturePermissionRequest } from "../../../src/application/ProcessCapturePermission.js";
|
||||
import { parseProcessScenario } from "../../../src/domain/processCapture.js";
|
||||
import { processCapturePermissionRequest } from "./ProcessCapturePermission.js";
|
||||
import { parseProcessScenario } from "../domain/processCapture.js";
|
||||
|
||||
describe("process capture permission request", () => {
|
||||
it("projects the complete adapter-neutral authority scope", () => {
|
||||
@@ -18,15 +18,32 @@ export const classifyFilesystemEffects = (
|
||||
.map((path) => {
|
||||
const beforeFile = beforeByPath.get(path) ?? null;
|
||||
const afterFile = afterByPath.get(path) ?? null;
|
||||
const status =
|
||||
beforeFile === null
|
||||
? "created"
|
||||
: afterFile === null
|
||||
? "deleted"
|
||||
: JSON.stringify(beforeFile) === JSON.stringify(afterFile)
|
||||
? "unchanged"
|
||||
: "modified";
|
||||
return { path, status, before: beforeFile, after: afterFile } as const;
|
||||
if (beforeFile === null) {
|
||||
if (afterFile === null)
|
||||
throw new TypeError(`Filesystem effect ${path} has no file state`);
|
||||
return {
|
||||
path,
|
||||
status: "created",
|
||||
before: null,
|
||||
after: afterFile,
|
||||
} as const;
|
||||
}
|
||||
if (afterFile === null)
|
||||
return {
|
||||
path,
|
||||
status: "deleted",
|
||||
before: beforeFile,
|
||||
after: null,
|
||||
} as const;
|
||||
return {
|
||||
path,
|
||||
status:
|
||||
JSON.stringify(beforeFile) === JSON.stringify(afterFile)
|
||||
? "unchanged"
|
||||
: "modified",
|
||||
before: beforeFile,
|
||||
after: afterFile,
|
||||
} as const;
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -5,7 +5,6 @@ import type {
|
||||
ProcessCapture,
|
||||
ProcessScenario,
|
||||
} from "../domain/processCapture.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
|
||||
/** Provider identity for controlled Process Capture v4 evidence. */
|
||||
export const PROCESS_PROVIDER = {
|
||||
@@ -32,12 +31,11 @@ export const createProcessCaptureEvidence = (
|
||||
scenario: ProcessScenario,
|
||||
capture: ProcessCapture,
|
||||
) => {
|
||||
const validatedCapture = parseProcessCapture(capture);
|
||||
return createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
operation: "capture_process_scenario",
|
||||
parameters: processEvidenceParameters(scenario),
|
||||
result: jsonValueSchema.parse(validatedCapture),
|
||||
result: jsonValueSchema.parse(capture),
|
||||
confidence: "observed",
|
||||
authority: "controlled-replay",
|
||||
environment: {
|
||||
@@ -46,6 +44,6 @@ export const createProcessCaptureEvidence = (
|
||||
architecture: process.arch,
|
||||
isolation: "process",
|
||||
},
|
||||
limitations: validatedCapture.limitations,
|
||||
limitations: capture.limitations,
|
||||
});
|
||||
};
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { IPty } from "@lydell/node-pty";
|
||||
import type {
|
||||
InteractionEvent,
|
||||
ProcessCapture,
|
||||
UnverifiedProcessCapture,
|
||||
ProcessCaptureEventJournalEntry,
|
||||
ProcessExecutionPolicy,
|
||||
ProcessSample,
|
||||
@@ -9,7 +10,7 @@ import type {
|
||||
RecordProcessCaptureEvent,
|
||||
TerminalFrame,
|
||||
} from "../domain/processCapture.js";
|
||||
import { validateProcessCapture } from "../domain/processCapture.js";
|
||||
import { parseProcessCapture } from "../domain/processCapture.js";
|
||||
import { err, ok, type Result } from "../domain/result.js";
|
||||
import {
|
||||
ProcessCaptureError,
|
||||
@@ -39,6 +40,7 @@ import {
|
||||
prepareProcessCapture,
|
||||
releaseProcessResources,
|
||||
resolveProcessResult,
|
||||
type PendingProcessCapture,
|
||||
} from "./ProcessCaptureLifecycle.js";
|
||||
import { assertNotCancelled } from "./ProcessCaptureAuthority.js";
|
||||
import {
|
||||
@@ -240,7 +242,7 @@ const normalizedShimEvents = (
|
||||
runtime: StartedCaptureRuntime,
|
||||
scenario: ProcessScenario,
|
||||
temporaryRoot: string,
|
||||
): ProcessCapture["shim_events"] =>
|
||||
): UnverifiedProcessCapture["shim_events"] =>
|
||||
runtime.shimReplay.events.map((event) =>
|
||||
normalizeProcessShimEvent(
|
||||
event,
|
||||
@@ -257,7 +259,7 @@ const finishProcessRun = async (options: {
|
||||
readonly temporaryRoot: string;
|
||||
readonly samples: readonly ProcessSample[];
|
||||
readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
|
||||
readonly capture: ProcessCapture | undefined;
|
||||
readonly capture: PendingProcessCapture | undefined;
|
||||
readonly executionFailure: unknown;
|
||||
}): Promise<ProcessCapture> => {
|
||||
options.runtime?.reactive?.unsubscribe();
|
||||
@@ -285,27 +287,35 @@ const finishProcessRun = async (options: {
|
||||
});
|
||||
await options.runtime?.reactive?.coordinator.close();
|
||||
let { capture, executionFailure } = options;
|
||||
if (capture !== undefined) {
|
||||
capture = {
|
||||
let verifiedCapture: ProcessCapture | undefined;
|
||||
if (capture !== undefined && cleanupFailure === undefined) {
|
||||
const settlement: UnverifiedProcessCapture["settlement"] =
|
||||
capture.settlement.state === "quiesced"
|
||||
? { ...capture.settlement, cleanup_outcome: "not_required" }
|
||||
: { ...capture.settlement, cleanup_outcome: "cleaned" };
|
||||
const completedCapture: UnverifiedProcessCapture = {
|
||||
...capture,
|
||||
reactive_run: projectProcessReactiveRun(options.runtime?.reactive),
|
||||
settlement: {
|
||||
...capture.settlement,
|
||||
cleanup_outcome:
|
||||
capture.settlement.state === "quiesced"
|
||||
? "not_required"
|
||||
: cleanupFailure === undefined
|
||||
? "cleaned"
|
||||
: "failed",
|
||||
settlement,
|
||||
cleanup: {
|
||||
owned_process_group: "verified",
|
||||
temporary_root: "removed",
|
||||
},
|
||||
};
|
||||
const issue = validateProcessCapture(capture)[0];
|
||||
if (issue !== undefined)
|
||||
try {
|
||||
verifiedCapture = parseProcessCapture(completedCapture);
|
||||
} catch (cause: unknown) {
|
||||
executionFailure = new ProcessCaptureError(
|
||||
`process capture validation failed: ${issue.path}: ${issue.message}`,
|
||||
`process capture validation failed${cause instanceof Error ? `: ${cause.message}` : ""}`,
|
||||
{ cause },
|
||||
);
|
||||
}
|
||||
}
|
||||
return resolveProcessResult(capture, executionFailure, cleanupFailure);
|
||||
return resolveProcessResult(
|
||||
verifiedCapture,
|
||||
executionFailure,
|
||||
cleanupFailure,
|
||||
);
|
||||
};
|
||||
|
||||
const completeCapture = async (options: {
|
||||
@@ -322,7 +332,7 @@ const completeCapture = async (options: {
|
||||
readonly initiallyTruncated: boolean;
|
||||
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
|
||||
readonly recordEvent: RecordProcessCaptureEvent;
|
||||
}): Promise<ProcessCapture> => {
|
||||
}): Promise<PendingProcessCapture> => {
|
||||
const { runtime, scenario } = options;
|
||||
runtime.checkpoints.trigger("root_exit");
|
||||
const { reason } = options.exit;
|
||||
@@ -374,7 +384,6 @@ const completeCapture = async (options: {
|
||||
exit: { ...options.exit, reason },
|
||||
samples: options.samples,
|
||||
replay: runtime.replay,
|
||||
reactiveRun: projectProcessReactiveRun(runtime.reactive),
|
||||
before: options.before,
|
||||
after,
|
||||
truncated,
|
||||
@@ -385,7 +394,7 @@ const completeCapture = async (options: {
|
||||
interactions: options.interactions,
|
||||
checkpoints,
|
||||
shimEvents: normalizedShimEvents(runtime, scenario, options.temporaryRoot),
|
||||
settlement: { ...settlement, cleanup_outcome: "not_required" },
|
||||
settlement,
|
||||
manifest,
|
||||
eventJournal: options.eventJournal,
|
||||
});
|
||||
@@ -409,7 +418,7 @@ const runProcessScenario = async (
|
||||
const { entries: eventJournal, recordEvent } = journal;
|
||||
let runtime: StartedCaptureRuntime | undefined;
|
||||
const timers = new Set<NodeJS.Timeout>();
|
||||
let capture: ProcessCapture | undefined;
|
||||
let capture: PendingProcessCapture | undefined;
|
||||
let executionFailure: unknown;
|
||||
let stopSampler = async () => ({ partial: false });
|
||||
const interactions: InteractionEvent[] = [];
|
||||
|
||||
+32
-24
@@ -3,18 +3,18 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
runPairedProcessExperiment,
|
||||
type ProcessCapturePort,
|
||||
} from "../../../src/application/ProcessPairedExperiment.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
} from "./ProcessPairedExperiment.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import {
|
||||
parseProcessCapture,
|
||||
type EnabledProcessExecutionPolicy,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
analyzeProcessRepeatability,
|
||||
bindProcessScenario,
|
||||
processPairedExperimentSchema,
|
||||
} from "../../../src/domain/processPairedExperiment.js";
|
||||
import { ok } from "../../../src/domain/result.js";
|
||||
} from "../domain/processPairedExperiment.js";
|
||||
import { ok } from "../domain/result.js";
|
||||
|
||||
const experiment = () =>
|
||||
processPairedExperimentSchema.parse({
|
||||
@@ -58,6 +58,11 @@ const policy: EnabledProcessExecutionPolicy = {
|
||||
networkAccess: "none",
|
||||
};
|
||||
|
||||
const cloneCapture = (
|
||||
capture: ReturnType<typeof parseProcessCapture>,
|
||||
): ReturnType<typeof parseProcessCapture> =>
|
||||
parseProcessCapture(structuredClone(capture));
|
||||
|
||||
describe("paired process experiments", () => {
|
||||
it("binds only declared side inputs onto the shared observation contract", () => {
|
||||
const parsed = experiment();
|
||||
@@ -87,7 +92,7 @@ describe("paired process experiments", () => {
|
||||
const capturePort: ProcessCapturePort = {
|
||||
capture: (scenario) => {
|
||||
observedExecutables.push(scenario.executable);
|
||||
return Promise.resolve(ok(structuredClone(capture)));
|
||||
return Promise.resolve(ok(cloneCapture(capture)));
|
||||
},
|
||||
};
|
||||
const result = await runPairedProcessExperiment(experiment(), policy, {
|
||||
@@ -107,6 +112,7 @@ describe("paired process experiments", () => {
|
||||
expect(result.value.authority_repeatability.stable).toBe(true);
|
||||
expect(result.value.candidate_repeatability.stable).toBe(true);
|
||||
expect(result.value.cross_side?.status).toBe("unchanged");
|
||||
expect(result.value.cross_side_blocked_reason).toBeNull();
|
||||
});
|
||||
|
||||
it("blocks cross-side claims when a candidate has a flaky exit", async () => {
|
||||
@@ -114,14 +120,14 @@ describe("paired process experiments", () => {
|
||||
let candidateRun = 0;
|
||||
const capturePort: ProcessCapturePort = {
|
||||
capture: (scenario) => {
|
||||
let capture = structuredClone(base);
|
||||
let capture = cloneCapture(base);
|
||||
if (scenario.executable === "/bin/candidate") {
|
||||
candidateRun += 1;
|
||||
if (candidateRun === 2)
|
||||
capture = {
|
||||
capture = parseProcessCapture({
|
||||
...capture,
|
||||
exit: { code: 1, signal: null, reason: "exited" },
|
||||
};
|
||||
});
|
||||
}
|
||||
return Promise.resolve(ok(capture));
|
||||
},
|
||||
@@ -145,14 +151,14 @@ describe("paired process experiments", () => {
|
||||
describe("paired process experiment comparisons", () => {
|
||||
it("distinguishes normalized timing variance from semantic output drift", () => {
|
||||
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const early = {
|
||||
const early = parseProcessCapture({
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 10, data: "ready" }],
|
||||
};
|
||||
const late = {
|
||||
});
|
||||
const late = parseProcessCapture({
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 20, data: "ready" }],
|
||||
};
|
||||
});
|
||||
expect(
|
||||
analyzeProcessRepeatability([early, late], ["terminal"]),
|
||||
).toMatchObject({
|
||||
@@ -160,10 +166,10 @@ describe("paired process experiment comparisons", () => {
|
||||
classification: "timing_variance",
|
||||
unstable_dimensions: ["terminal"],
|
||||
});
|
||||
const changed = {
|
||||
const changed = parseProcessCapture({
|
||||
...base,
|
||||
frames: [{ sequence: 0, at_ms: 20, data: "failed" }],
|
||||
};
|
||||
});
|
||||
expect(
|
||||
analyzeProcessRepeatability([early, changed], ["terminal"]),
|
||||
).toMatchObject({ classification: "nondeterministic_output" });
|
||||
@@ -192,7 +198,7 @@ describe("paired process experiment comparisons", () => {
|
||||
it("blocks full cross-side output when only a subset was repeatable", async () => {
|
||||
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const capturePort: ProcessCapturePort = {
|
||||
capture: () => Promise.resolve(ok(structuredClone(capture))),
|
||||
capture: () => Promise.resolve(ok(cloneCapture(capture))),
|
||||
};
|
||||
const subset = processPairedExperimentSchema.parse({
|
||||
...experiment(),
|
||||
@@ -225,14 +231,16 @@ describe("paired process experiment freshness", () => {
|
||||
: "2026-01-01T00:00:09.500Z";
|
||||
captureIndex += 1;
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
...structuredClone(base),
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
started_at: completedAt,
|
||||
completed_at: completedAt,
|
||||
},
|
||||
}),
|
||||
ok(
|
||||
parseProcessCapture({
|
||||
...structuredClone(base),
|
||||
manifest: {
|
||||
...base.manifest,
|
||||
started_at: completedAt,
|
||||
completed_at: completedAt,
|
||||
},
|
||||
}),
|
||||
),
|
||||
);
|
||||
},
|
||||
};
|
||||
@@ -26,8 +26,7 @@ export interface ProcessCapturePort {
|
||||
): Promise<Result<ProcessCapture, ProcessCaptureError>>;
|
||||
}
|
||||
|
||||
/** Repeatability evidence and an optional stable cross-side comparison. */
|
||||
export interface PairedProcessExperimentResult {
|
||||
interface PairedProcessExperimentEvidence {
|
||||
readonly authority_runs: readonly ProcessCapture[];
|
||||
readonly candidate_runs: readonly ProcessCapture[];
|
||||
readonly authority_repeatability: ReturnType<
|
||||
@@ -36,10 +35,21 @@ export interface PairedProcessExperimentResult {
|
||||
readonly candidate_repeatability: ReturnType<
|
||||
typeof analyzeProcessRepeatability
|
||||
>;
|
||||
readonly cross_side: ReturnType<typeof compareProcessCaptures> | null;
|
||||
readonly cross_side_blocked_reason: string | null;
|
||||
}
|
||||
|
||||
/** Repeatability evidence and either a stable comparison or its blocking reason. */
|
||||
export type PairedProcessExperimentResult = PairedProcessExperimentEvidence &
|
||||
(
|
||||
| {
|
||||
readonly cross_side: ReturnType<typeof compareProcessCaptures>;
|
||||
readonly cross_side_blocked_reason: null;
|
||||
}
|
||||
| {
|
||||
readonly cross_side: null;
|
||||
readonly cross_side_blocked_reason: string;
|
||||
}
|
||||
);
|
||||
|
||||
const productionCapturePort: ProcessCapturePort = {
|
||||
capture: captureProcessScenario,
|
||||
};
|
||||
@@ -114,27 +124,29 @@ export const runPairedProcessExperiment = async (
|
||||
);
|
||||
const authorityLatest = authorityRuns.value.at(-1);
|
||||
const candidateLatest = candidateRuns.value.at(-1);
|
||||
const crossSide =
|
||||
const crossSideOutcome =
|
||||
stable &&
|
||||
allDimensionsRequired &&
|
||||
authorityLatest !== undefined &&
|
||||
candidateLatest !== undefined
|
||||
? compareProcessCaptures(authorityLatest, candidateLatest, {
|
||||
maxCaptureAgeMs: experiment.freshness_policy.max_capture_age_ms,
|
||||
...(options.now === undefined ? {} : { now: options.now }),
|
||||
})
|
||||
: null;
|
||||
? {
|
||||
cross_side: compareProcessCaptures(authorityLatest, candidateLatest, {
|
||||
maxCaptureAgeMs: experiment.freshness_policy.max_capture_age_ms,
|
||||
...(options.now === undefined ? {} : { now: options.now }),
|
||||
}),
|
||||
cross_side_blocked_reason: null,
|
||||
}
|
||||
: {
|
||||
cross_side: null,
|
||||
cross_side_blocked_reason: !allDimensionsRequired
|
||||
? "Cross-side comparison is blocked until every returned dimension is required and repeatable."
|
||||
: "Cross-side comparison is blocked because a required same-side dimension is unstable.",
|
||||
};
|
||||
return ok({
|
||||
authority_runs: authorityRuns.value,
|
||||
candidate_runs: candidateRuns.value,
|
||||
authority_repeatability: authorityRepeatability,
|
||||
candidate_repeatability: candidateRepeatability,
|
||||
cross_side: crossSide,
|
||||
cross_side_blocked_reason:
|
||||
crossSide !== null
|
||||
? null
|
||||
: !allDimensionsRequired
|
||||
? "Cross-side comparison is blocked until every returned dimension is required and repeatable."
|
||||
: "Cross-side comparison is blocked because a required same-side dimension is unstable.",
|
||||
...crossSideOutcome,
|
||||
});
|
||||
};
|
||||
|
||||
+6
-6
@@ -2,19 +2,19 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ProcessReactiveCoordinator,
|
||||
type ProcessReactiveTimerHost,
|
||||
} from "../../../src/application/ProcessReactiveCoordinator.js";
|
||||
import { executeProcessReactiveEffects } from "../../../src/application/ProcessReactiveEffects.js";
|
||||
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js";
|
||||
import { subscribeProcessReactiveObservations } from "../../../src/application/ProcessReactiveObservations.js";
|
||||
} from "./ProcessReactiveCoordinator.js";
|
||||
import { executeProcessReactiveEffects } from "./ProcessReactiveEffects.js";
|
||||
import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
|
||||
import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservations.js";
|
||||
import type {
|
||||
FilesystemCheckpoint,
|
||||
InteractionEvent,
|
||||
TerminalFrame,
|
||||
} from "../../../src/domain/processCapture.js";
|
||||
} from "../domain/processCapture.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveScenario,
|
||||
} from "../../../src/domain/processReactiveScenario.js";
|
||||
} from "../domain/processReactiveScenario.js";
|
||||
const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
+5
-5
@@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ProcessReactiveCoordinator,
|
||||
type ProcessReactiveTimerHost,
|
||||
} from "../../../src/application/ProcessReactiveCoordinator.js";
|
||||
import { unsupportedProcessReactiveFeatures } from "../../../src/application/ProcessReactiveEffects.js";
|
||||
import { createProcessObservation } from "../../../src/domain/processObservation.js";
|
||||
import type { ProcessReactiveEffectResult } from "../../../src/domain/processReactiveRuntime.js";
|
||||
} from "./ProcessReactiveCoordinator.js";
|
||||
import { unsupportedProcessReactiveFeatures } from "./ProcessReactiveEffects.js";
|
||||
import { createProcessObservation } from "../domain/processObservation.js";
|
||||
import type { ProcessReactiveEffectResult } from "../domain/processReactiveRuntime.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveScenario,
|
||||
} from "../../../src/domain/processReactiveScenario.js";
|
||||
} from "../domain/processReactiveScenario.js";
|
||||
const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
+3
-3
@@ -2,12 +2,12 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
ProcessReactiveCoordinator,
|
||||
type ProcessReactiveTimerHost,
|
||||
} from "../../../src/application/ProcessReactiveCoordinator.js";
|
||||
import { createProcessObservation } from "../../../src/domain/processObservation.js";
|
||||
} from "./ProcessReactiveCoordinator.js";
|
||||
import { createProcessObservation } from "../domain/processObservation.js";
|
||||
import {
|
||||
processReactiveScenarioSchema,
|
||||
type ProcessReactiveScenario,
|
||||
} from "../../../src/domain/processReactiveScenario.js";
|
||||
} from "../domain/processReactiveScenario.js";
|
||||
const terminalTrigger = () => ({
|
||||
kind: "terminal_text" as const,
|
||||
view: "decoded" as const,
|
||||
@@ -167,13 +167,17 @@ export const startProcessReactiveHarness = (options: {
|
||||
/** Project internal reducer state into the stable Process Capture shape. */
|
||||
export const projectProcessReactiveRun = (
|
||||
harness: ProcessReactiveHarness | undefined,
|
||||
): ProcessCapture["reactive_run"] =>
|
||||
harness === undefined
|
||||
? null
|
||||
: {
|
||||
status: harness.coordinator.snapshot.status,
|
||||
outcome: harness.coordinator.snapshot.outcome,
|
||||
active_state: harness.coordinator.snapshot.active_state,
|
||||
transitions: harness.coordinator.snapshot.transitions,
|
||||
controls: harness.controls,
|
||||
};
|
||||
): ProcessCapture["reactive_run"] => {
|
||||
if (harness === undefined) return null;
|
||||
const snapshot = harness.coordinator.snapshot;
|
||||
const completion =
|
||||
snapshot.status === "running"
|
||||
? { status: snapshot.status, outcome: null }
|
||||
: { status: snapshot.status, outcome: snapshot.outcome };
|
||||
return {
|
||||
...completion,
|
||||
active_state: snapshot.active_state,
|
||||
transitions: snapshot.transitions,
|
||||
controls: harness.controls,
|
||||
};
|
||||
};
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createProgressReporter } from "../../../src/application/ProgressReporter.js";
|
||||
import { createProgressReporter } from "./ProgressReporter.js";
|
||||
|
||||
describe("progress reporter", () => {
|
||||
it("preserves monotonic order, rate bounds intermediate updates, and always emits terminal state", async () => {
|
||||
+8
-8
@@ -1,21 +1,21 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "../../../src/application/ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../domain/processCapture.js";
|
||||
import {
|
||||
reconstructionObligationLedgerPageSchema,
|
||||
type ReconstructionObligationLedgerInput,
|
||||
type ReconstructionObligationLedgerPage,
|
||||
type ReviewedReconstructionObligation,
|
||||
} from "../../../src/domain/reconstructionObligationLedgerSchemas.js";
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
const proofEvidence = (id: string) =>
|
||||
createEvidence(
|
||||
+8
-8
@@ -1,22 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js";
|
||||
import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
|
||||
import {
|
||||
buildReconstructionObligationLedgerEvidenceValidated,
|
||||
resolveReconstructionObligationLedgerRequest,
|
||||
} from "../../../src/application/ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js";
|
||||
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../../../src/domain/processCapture.js";
|
||||
} from "./ReconstructionObligationLedgerService.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import { processCaptureSchema } from "../domain/processCapture.js";
|
||||
import {
|
||||
reconstructionObligationLedgerPageSchema,
|
||||
serializeReconstructionObligationLedger,
|
||||
type ReconstructionObligationLedgerInput,
|
||||
type ReconstructionObligationLedgerPage,
|
||||
type ReviewedReconstructionObligation,
|
||||
} from "../../../src/domain/reconstructionObligationLedgerSchemas.js";
|
||||
} from "../domain/reconstructionObligationLedgerSchemas.js";
|
||||
|
||||
const proofEvidence = (id: string) =>
|
||||
createEvidence(
|
||||
@@ -27,18 +27,29 @@ interface RuntimeProbeFailure {
|
||||
readonly stderr: string;
|
||||
}
|
||||
|
||||
/** One lexical PATH candidate and its canonical executable probe result. */
|
||||
interface RuntimeExecutableDiagnostic {
|
||||
interface RuntimeExecutableIdentity {
|
||||
readonly tool: RuntimeToolName;
|
||||
readonly lexical_path: string;
|
||||
readonly canonical_path: string;
|
||||
readonly path_index: number | null;
|
||||
readonly selection: "rea-launcher" | "path-primary" | "path-shadowed";
|
||||
readonly version: string | null;
|
||||
readonly healthy: boolean;
|
||||
readonly failure: RuntimeProbeFailure | null;
|
||||
}
|
||||
|
||||
/** One lexical PATH candidate and its canonical executable probe result. */
|
||||
type RuntimeExecutableDiagnostic = RuntimeExecutableIdentity &
|
||||
(
|
||||
| {
|
||||
readonly version: string;
|
||||
readonly healthy: true;
|
||||
readonly failure: null;
|
||||
}
|
||||
| {
|
||||
readonly version: null;
|
||||
readonly healthy: false;
|
||||
readonly failure: RuntimeProbeFailure;
|
||||
}
|
||||
);
|
||||
|
||||
/** Runtime identities observed under one exact effective environment. */
|
||||
export interface RuntimeExecutableInventory {
|
||||
readonly launcher_node: string;
|
||||
@@ -148,16 +159,21 @@ const probeCandidate = async (
|
||||
): Promise<RuntimeExecutableDiagnostic> => {
|
||||
const canonical = await canonicalPath(candidate.path);
|
||||
const result = await executeVersion(candidate.path, timeoutMs, effectivePath);
|
||||
return {
|
||||
const identity = {
|
||||
tool: candidate.tool,
|
||||
lexical_path: candidate.path,
|
||||
canonical_path: canonical,
|
||||
path_index: candidate.pathIndex,
|
||||
selection: candidate.selection,
|
||||
version: result.ok ? result.version : null,
|
||||
healthy: result.ok,
|
||||
failure: result.ok ? null : result.failure,
|
||||
};
|
||||
return result.ok
|
||||
? { ...identity, version: result.version, healthy: true, failure: null }
|
||||
: {
|
||||
...identity,
|
||||
version: null,
|
||||
healthy: false,
|
||||
failure: result.failure,
|
||||
};
|
||||
};
|
||||
|
||||
type VersionResult =
|
||||
|
||||
@@ -74,8 +74,8 @@ export class SessionProviderRouter {
|
||||
private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime,
|
||||
) {}
|
||||
|
||||
/** Preserve the existing provider/factory seam used by focused embedders. */
|
||||
static legacy(
|
||||
/** Create routing for an embedding backed by one fixed provider or factory. */
|
||||
static single(
|
||||
provider: AnalysisProvider | AnalysisClientFactory,
|
||||
options: {
|
||||
readonly resolveAnalysisProfile?: (
|
||||
|
||||
+5
-8
@@ -1,13 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
runCapabilityStatus,
|
||||
runProviderStatus,
|
||||
} from "../../../src/application/DirectAnalysis.js";
|
||||
import { projectDoctorReport } from "../../../src/application/DoctorProjection.js";
|
||||
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
import { runCapabilityStatus, runProviderStatus } from "./DirectAnalysis.js";
|
||||
import { projectDoctorReport } from "./DoctorProjection.js";
|
||||
import { runDoctor, type DoctorHost } from "./Doctor.js";
|
||||
import { CATALOG_IDENTITY } from "../catalogIdentity.js";
|
||||
import { PRODUCT_IDENTITY } from "../identity.js";
|
||||
|
||||
const doctorHost = (): DoctorHost => ({
|
||||
platform: "darwin",
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { BrowserScenarioSecrets } from "../../../src/browser/BrowserScenarioSecrets.js";
|
||||
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js";
|
||||
import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
|
||||
const secret = (secret_id: string) => ({ source: "secret", secret_id });
|
||||
const literal = (value: string) => ({
|
||||
@@ -5,6 +5,7 @@ import type {
|
||||
BrowserScenarioUrl,
|
||||
BrowserScenarioValue,
|
||||
} from "../domain/browserScenario.js";
|
||||
import type { BrowserStorageValueFingerprint } from "../domain/browserScenarioCaptureValues.js";
|
||||
|
||||
const REDACTION_PREFIX = "[REDACTED:";
|
||||
|
||||
@@ -53,10 +54,7 @@ export class BrowserScenarioSecrets {
|
||||
return output;
|
||||
}
|
||||
|
||||
fingerprint(value: string): {
|
||||
readonly value_state: "hashed" | "redacted-secret";
|
||||
readonly value_sha256: string | null;
|
||||
} {
|
||||
fingerprint(value: string): BrowserStorageValueFingerprint {
|
||||
for (const secret of this.values.values())
|
||||
if (secret !== "" && value.includes(secret))
|
||||
return { value_state: "redacted-secret", value_sha256: null };
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { inspectWebPageInputSchema } from "../domain/browserObservation.js";
|
||||
import { CdpCaptureCompleteness } from "./CdpCaptureCompleteness.js";
|
||||
import { CdpCaptureEvents } from "./CdpCaptureEvents.js";
|
||||
import { ingestElectronScriptEvent } from "./CdpElectronScriptEvents.js";
|
||||
|
||||
describe("CDP execution-context retention", () => {
|
||||
it("removes stale frame attribution when execution contexts are destroyed", () => {
|
||||
const request = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const browser = new CdpCaptureEvents(
|
||||
request,
|
||||
new Set(["https://app.example.test"]),
|
||||
);
|
||||
browser.beginAuthorizedFrame("frame-old");
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextDestroyed",
|
||||
params: { executionContextId: 7 },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Debugger.scriptParsed",
|
||||
params: {
|
||||
scriptId: "script-1",
|
||||
url: "https://app.example.test/app.js",
|
||||
executionContextId: 7,
|
||||
},
|
||||
});
|
||||
const script = browser.scripts.get("script-1");
|
||||
if (script === undefined) throw new TypeError("Expected captured script");
|
||||
expect(browser.frameForScript(script, new Set(["frame-old"]))).toBeNull();
|
||||
|
||||
const electronFrames = new Map<string, string>();
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
ingestElectronScriptEvent({
|
||||
event: {
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
},
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
ingestElectronScriptEvent({
|
||||
event: { method: "Runtime.executionContextsCleared", params: {} },
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
expect(electronFrames.size).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -10,12 +10,14 @@ import type {
|
||||
} from "../domain/browserScenario.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
browserScenarioCompletenessSchema,
|
||||
classifyBrowserScenarioCompleteness,
|
||||
browserScenarioStepSchema,
|
||||
browserStepArtifactsSchema,
|
||||
type BrowserScenarioCapture,
|
||||
type BrowserScenarioCompleteness,
|
||||
type BrowserScenarioCompletenessSection,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserScenarioStepOutcome,
|
||||
type BrowserStepArtifacts,
|
||||
} from "../domain/browserScenarioCapture.js";
|
||||
import {
|
||||
@@ -51,6 +53,14 @@ export const PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY: ProviderIdentity =
|
||||
});
|
||||
|
||||
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
|
||||
const SNAPSHOT_KINDS = [
|
||||
"screenshot",
|
||||
"dom",
|
||||
"accessibility",
|
||||
"url",
|
||||
"history",
|
||||
"storage",
|
||||
] as const satisfies readonly SnapshotKind[];
|
||||
|
||||
const requestedForStep = (
|
||||
scenario: BrowserScenario,
|
||||
@@ -83,40 +93,29 @@ const stepCompleteness = (
|
||||
artifacts: BrowserStepArtifacts,
|
||||
status: BrowserScenarioStep["status"],
|
||||
): BrowserScenarioCompleteness => {
|
||||
const missing = Object.entries(artifacts)
|
||||
.filter(([, state]) => state.state === "missing")
|
||||
.map(([section]) => section);
|
||||
const truncated = Object.entries(artifacts)
|
||||
.filter(([, state]) => state.state === "truncated")
|
||||
.map(([section]) => section);
|
||||
const missing: BrowserScenarioCompletenessSection[] = SNAPSHOT_KINDS.filter(
|
||||
(section) => artifacts[section].state === "missing",
|
||||
);
|
||||
const truncated = SNAPSHOT_KINDS.filter(
|
||||
(section) => artifacts[section].state === "truncated",
|
||||
);
|
||||
if (status !== "completed") missing.push("action");
|
||||
const condition =
|
||||
truncated.length > 0
|
||||
? "truncated"
|
||||
: missing.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: condition,
|
||||
equality_eligible: condition === "complete",
|
||||
missing_sections: [...new Set(missing)].sort(),
|
||||
truncated_sections: [...new Set(truncated)].sort(),
|
||||
});
|
||||
return classifyBrowserScenarioCompleteness(missing, truncated);
|
||||
};
|
||||
|
||||
const createStep = (input: {
|
||||
readonly stepIndex: number;
|
||||
readonly stepId: string;
|
||||
readonly action: string;
|
||||
readonly status: BrowserScenarioStep["status"];
|
||||
readonly elapsedMs: number;
|
||||
readonly beforeUrl: string;
|
||||
readonly afterUrl: string;
|
||||
readonly error: string | null;
|
||||
readonly eventStart: number;
|
||||
readonly eventEnd: number;
|
||||
readonly artifacts: BrowserStepArtifacts;
|
||||
}): BrowserScenarioStep =>
|
||||
const createStep = (
|
||||
input: {
|
||||
readonly stepIndex: number;
|
||||
readonly stepId: string;
|
||||
readonly action: string;
|
||||
readonly elapsedMs: number;
|
||||
readonly beforeUrl: string;
|
||||
readonly afterUrl: string;
|
||||
readonly eventStart: number;
|
||||
readonly eventEnd: number;
|
||||
readonly artifacts: BrowserStepArtifacts;
|
||||
} & BrowserScenarioStepOutcome,
|
||||
): BrowserScenarioStep =>
|
||||
browserScenarioStepSchema.parse({
|
||||
step_index: input.stepIndex,
|
||||
step_id: input.stepId,
|
||||
@@ -207,11 +206,12 @@ const executeStep = async (input: {
|
||||
const actionStartedAt = Date.now();
|
||||
session.setStep(stepIndex);
|
||||
const requestCancelled = (): boolean => signal?.aborted === true;
|
||||
let status: BrowserScenarioStep["status"] = "completed";
|
||||
let error: string | null = null;
|
||||
let outcome: BrowserScenarioStepOutcome = {
|
||||
status: "completed",
|
||||
error: null,
|
||||
};
|
||||
if (requestCancelled()) {
|
||||
status = "cancelled";
|
||||
error = "scenario request cancelled";
|
||||
outcome = { status: "cancelled", error: "scenario request cancelled" };
|
||||
} else {
|
||||
try {
|
||||
const elapsed = Date.now() - startedAt;
|
||||
@@ -219,16 +219,18 @@ const executeStep = async (input: {
|
||||
if (remaining <= 0) throw new Error("Scenario duration limit reached");
|
||||
await session.perform(action, remaining, signal);
|
||||
} catch (cause: unknown) {
|
||||
status = requestCancelled() ? "cancelled" : "failed";
|
||||
error = session.redactError(cause);
|
||||
outcome = {
|
||||
status: requestCancelled() ? "cancelled" : "failed",
|
||||
error: session.redactError(cause),
|
||||
};
|
||||
}
|
||||
}
|
||||
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
|
||||
const artifacts =
|
||||
status === "cancelled" || remaining <= 0
|
||||
outcome.status === "cancelled" || remaining <= 0
|
||||
? unavailableArtifacts(
|
||||
requested,
|
||||
status === "cancelled"
|
||||
outcome.status === "cancelled"
|
||||
? "scenario request cancelled"
|
||||
: "scenario duration limit reached",
|
||||
)
|
||||
@@ -237,11 +239,10 @@ const executeStep = async (input: {
|
||||
stepIndex,
|
||||
stepId: action.step_id,
|
||||
action: action.action,
|
||||
status,
|
||||
...outcome,
|
||||
elapsedMs: Date.now() - actionStartedAt,
|
||||
beforeUrl,
|
||||
afterUrl: session.currentUrl(),
|
||||
error,
|
||||
eventStart,
|
||||
eventEnd: session.lastEventSequence(),
|
||||
artifacts,
|
||||
@@ -261,18 +262,7 @@ const globalCompleteness = (
|
||||
);
|
||||
truncated.push(...session.eventTruncationSections());
|
||||
if (session.mode === "connect") missing.push("events");
|
||||
const status =
|
||||
truncated.length > 0
|
||||
? "truncated"
|
||||
: missing.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status,
|
||||
equality_eligible: status === "complete",
|
||||
missing_sections: [...new Set(missing)].sort(),
|
||||
truncated_sections: [...new Set(truncated)].sort(),
|
||||
});
|
||||
return classifyBrowserScenarioCompleteness(missing, truncated);
|
||||
};
|
||||
|
||||
const runScenario = async (
|
||||
|
||||
@@ -241,22 +241,31 @@ export class PlaywrightScenarioEvents {
|
||||
}
|
||||
|
||||
private request(kind: "request" | "request-failed", request: Request): void {
|
||||
this.push({
|
||||
kind,
|
||||
const observation = {
|
||||
method: this.secrets.redact(request.method()).slice(0, 32),
|
||||
url: this.safeUrl(request.url()),
|
||||
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
|
||||
status: null,
|
||||
header_names: Object.keys(request.headers())
|
||||
.map((name) => this.secrets.redact(name).slice(0, 256))
|
||||
.sort()
|
||||
.slice(0, 256),
|
||||
failure:
|
||||
kind === "request-failed"
|
||||
? this.secrets
|
||||
.redact(request.failure()?.errorText ?? "unknown")
|
||||
.slice(0, 1_024)
|
||||
: null,
|
||||
};
|
||||
if (kind === "request-failed") {
|
||||
this.push({
|
||||
...observation,
|
||||
kind,
|
||||
status: null,
|
||||
failure: this.secrets
|
||||
.redact(request.failure()?.errorText ?? "unknown")
|
||||
.slice(0, 1_024),
|
||||
});
|
||||
return;
|
||||
}
|
||||
this.push({
|
||||
...observation,
|
||||
kind,
|
||||
status: null,
|
||||
failure: null,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -300,14 +309,25 @@ export class PlaywrightScenarioEvents {
|
||||
): void {
|
||||
const bytes = Buffer.byteLength(payload);
|
||||
const isText = typeof payload === "string";
|
||||
const text = isText ? this.secrets.redact(payload).slice(0, 65_536) : null;
|
||||
if (!isText) {
|
||||
this.push({
|
||||
kind,
|
||||
url,
|
||||
payload_type: "binary",
|
||||
payload_bytes: bytes,
|
||||
payload_text: null,
|
||||
truncated: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const text = this.secrets.redact(payload).slice(0, 65_536);
|
||||
this.push({
|
||||
kind,
|
||||
url,
|
||||
payload_type: isText ? "text" : "binary",
|
||||
payload_type: "text",
|
||||
payload_bytes: bytes,
|
||||
payload_text: text,
|
||||
truncated: isText && text !== null && text.length < payload.length,
|
||||
truncated: text.length < payload.length,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+23
-2
@@ -2,11 +2,12 @@ import { deflateSync } from "node:zlib";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { comparePngScreenshots } from "../../../src/browser/PngVisualDiff.js";
|
||||
import { comparePngScreenshots } from "./PngVisualDiff.js";
|
||||
import {
|
||||
compareWebScreenshotsInputSchema,
|
||||
createWebScreenshotArtifact,
|
||||
} from "../../../src/domain/webScreenshot.js";
|
||||
webScreenshotDiffSchema,
|
||||
} from "../domain/webScreenshot.js";
|
||||
|
||||
describe("PNG visual diff", () => {
|
||||
it("reports exact changed-pixel and channel metrics", () => {
|
||||
@@ -60,6 +61,26 @@ describe("PNG visual diff", () => {
|
||||
),
|
||||
).toThrow("oversized PNG");
|
||||
});
|
||||
|
||||
it("rejects metrics that cannot represent their comparison status", () => {
|
||||
const image = artifact(1, 1, [0, 0, 0, 255]);
|
||||
const result = comparePngScreenshots(
|
||||
compareWebScreenshotsInputSchema.parse({ before: image, after: image }),
|
||||
);
|
||||
|
||||
expect(
|
||||
webScreenshotDiffSchema.safeParse({
|
||||
...result,
|
||||
status: "dimension_mismatch",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
webScreenshotDiffSchema.safeParse({
|
||||
...result,
|
||||
compared_pixels: 2,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const artifact = (width: number, height: number, pixels: readonly number[]) =>
|
||||
@@ -50,19 +50,29 @@ export const comparePngScreenshots = (
|
||||
if (changed) changedPixels += 1;
|
||||
}
|
||||
const pixels = before.width * before.height;
|
||||
return {
|
||||
schema_version: 1,
|
||||
status: changedPixels === 0 ? "identical" : "different",
|
||||
const context = {
|
||||
schema_version: 1 as const,
|
||||
before: dimensions(before),
|
||||
after: dimensions(after),
|
||||
channel_threshold: input.channel_threshold,
|
||||
compared_pixels: pixels,
|
||||
changed_pixels: changedPixels,
|
||||
changed_ratio: changedPixels / pixels,
|
||||
maximum_channel_delta: maximumDelta,
|
||||
mean_absolute_channel_delta: totalDelta / (pixels * 4),
|
||||
limitations: limitations(),
|
||||
};
|
||||
if (changedPixels === 0)
|
||||
return {
|
||||
...context,
|
||||
status: "identical",
|
||||
changed_pixels: 0,
|
||||
changed_ratio: 0,
|
||||
};
|
||||
return {
|
||||
...context,
|
||||
status: "different",
|
||||
changed_pixels: changedPixels,
|
||||
changed_ratio: changedPixels / pixels,
|
||||
};
|
||||
};
|
||||
|
||||
const decodePng = (
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
boundedSensitiveText,
|
||||
redactSensitiveText,
|
||||
} from "../../../src/browser/SensitiveTextCapture.js";
|
||||
} from "./SensitiveTextCapture.js";
|
||||
|
||||
describe("sensitive console text", () => {
|
||||
it("redacts assignments, bearer credentials, and JWT-shaped values", () => {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("browser runtime configuration", () => {
|
||||
it("builds an exact-origin browser observation ceiling only when enabled", () => {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("capability flags", () => {
|
||||
it("rejects values outside the exact true/false boundary", () => {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("passive browser observation policy", () => {
|
||||
it("requires both endpoint and origin scopes when enabled", () => {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("process capture configuration", () => {
|
||||
it("parses all authority required by enabled capture", () => {
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseConfig } from "../../../src/config.js";
|
||||
import { parseConfig } from "./config.js";
|
||||
|
||||
describe("runtime configuration", () => {
|
||||
it("allows target-free startup and defaults to Hopper's documented launcher", () => {
|
||||
+12
-15
@@ -6,27 +6,24 @@ import {
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
TOOL_CONTRACTS,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "../../../src/contracts/artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../../../src/contracts/managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
|
||||
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "../../../src/contracts/browserScenarioToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "../../../src/contracts/electronToolContracts.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../../../src/contracts/javascriptRuntimeObservationToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js";
|
||||
} from "./toolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
import {
|
||||
enhancedOutputSchemas,
|
||||
managedOutputSchemas,
|
||||
managedWorkflowOutputSchemas,
|
||||
officialOutputSchemas,
|
||||
sessionOutputSchemas,
|
||||
} from "../../../src/contracts/toolOutputSchemas.js";
|
||||
import {
|
||||
annotationsFromEffects,
|
||||
TOOL_EFFECTS,
|
||||
} from "../../../src/contracts/toolEffects.js";
|
||||
} from "./toolOutputSchemas.js";
|
||||
import { annotationsFromEffects, TOOL_EFFECTS } from "./toolEffects.js";
|
||||
|
||||
const convertContractJsonSchema = (schema: z.ZodType) =>
|
||||
z.toJSONSchema(schema, {
|
||||
@@ -3,7 +3,7 @@ import { createEvidence } from "../domain/evidence.js";
|
||||
import { jsonValueSchema } from "../domain/jsonValue.js";
|
||||
import {
|
||||
compareProcessCaptures,
|
||||
processCaptureSchema,
|
||||
parseProcessCapture,
|
||||
} from "../domain/processCapture.js";
|
||||
import { FUNCTION_COMPARISON_EXAMPLE } from "./functionComparisonExample.js";
|
||||
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
|
||||
@@ -46,7 +46,7 @@ const PROCESS_PROVIDER = {
|
||||
name: "REA deterministic process harness",
|
||||
version: "3",
|
||||
} as const;
|
||||
const capture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
|
||||
const captureEvidence = (scenario: string) =>
|
||||
createEvidence(undefined, PROCESS_PROVIDER, {
|
||||
predicateType: "rea.process-capture/v4",
|
||||
|
||||
+2
-5
@@ -1,10 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
PROMPT_CONTRACTS,
|
||||
renderGuidedPrompt,
|
||||
} from "../../../src/contracts/promptContracts.js";
|
||||
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
|
||||
import { PROMPT_CONTRACTS, renderGuidedPrompt } from "./promptContracts.js";
|
||||
import { TOOL_CONTRACTS } from "./toolContracts.js";
|
||||
|
||||
const promptNames = [
|
||||
"investigate_feature",
|
||||
+8
-8
@@ -5,14 +5,14 @@ import {
|
||||
OFFICIAL_TOOL_CONTRACTS,
|
||||
SESSION_TOOL_CONTRACTS,
|
||||
TOOL_CONTRACTS,
|
||||
} from "../../../src/contracts/toolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "../../../src/contracts/artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "../../../src/contracts/managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/nativeToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "../../../src/contracts/electronToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js";
|
||||
} from "./toolContracts.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
|
||||
import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
|
||||
import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
|
||||
|
||||
describe("tool contract inventory", () => {
|
||||
it("publishes the canonical analysis and session tool inventory", () => {
|
||||
+16
-77
@@ -1,30 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { traceJavaScriptSemanticsRequestSchema } from "../../../src/contracts/applicationWorkflowInputContracts.js";
|
||||
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
|
||||
import { traceJavaScriptSemanticsRequestSchema } from "./applicationWorkflowInputContracts.js";
|
||||
import {
|
||||
artifactInspectionInputSchema,
|
||||
artifactInventoryInputSchema,
|
||||
} from "../../../src/contracts/artifactToolContracts.js";
|
||||
} from "./artifactToolContracts.js";
|
||||
import { JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE } from "./javascriptApplicationWorkflowExamples.js";
|
||||
import {
|
||||
MANAGED_WORKFLOW_TOOL_CONTRACTS,
|
||||
compareManagedMembersReferenceInputSchema,
|
||||
managedApplicationGraphReferenceInputSchema,
|
||||
managedNativeVerificationReferenceInputSchema,
|
||||
compareManagedMembersReferenceInputSchema,
|
||||
} from "../../../src/contracts/managedWorkflowToolContracts.js";
|
||||
import {
|
||||
PROMPT_CONTRACTS,
|
||||
renderGuidedPrompt,
|
||||
} from "../../../src/contracts/promptContracts.js";
|
||||
import {
|
||||
annotationsFromEffects,
|
||||
toolContractMetadata,
|
||||
} from "../../../src/contracts/toolEffects.js";
|
||||
import {
|
||||
requireOutputSchema,
|
||||
toolAvailability,
|
||||
} from "../../../src/contracts/toolOutputSchemaPrimitives.js";
|
||||
import { JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE } from "../../../src/contracts/javascriptApplicationWorkflowExamples.js";
|
||||
} from "./managedWorkflowToolContracts.js";
|
||||
|
||||
const EVIDENCE_ID = `ev_${"a".repeat(64)}`;
|
||||
|
||||
@@ -36,22 +23,24 @@ const workflowInput = (name: string) => {
|
||||
return contract.examples[0].input;
|
||||
};
|
||||
|
||||
describe("contract validation boundaries", () => {
|
||||
describe("workflow input contracts", () => {
|
||||
it("rejects missing and duplicated application Evidence references", () => {
|
||||
const query = {
|
||||
seed: { kind: "literal" as const, value: "renderer" },
|
||||
direction: "callers" as const,
|
||||
};
|
||||
const missing = traceJavaScriptSemanticsRequestSchema.safeParse({ query });
|
||||
expect(missing.success).toBe(false);
|
||||
expect(
|
||||
traceJavaScriptSemanticsRequestSchema.safeParse({ query }).success,
|
||||
).toBe(false);
|
||||
|
||||
const evidence = JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application;
|
||||
const duplicated = traceJavaScriptSemanticsRequestSchema.safeParse({
|
||||
application: evidence,
|
||||
application_evidence_id: evidence.evidence_id,
|
||||
query,
|
||||
});
|
||||
expect(duplicated.success).toBe(false);
|
||||
expect(
|
||||
traceJavaScriptSemanticsRequestSchema.safeParse({
|
||||
application: evidence,
|
||||
application_evidence_id: evidence.evidence_id,
|
||||
query,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects managed Evidence identity collisions", () => {
|
||||
@@ -103,54 +92,4 @@ describe("contract validation boundaries", () => {
|
||||
expect(artifactInventoryInputSchema.safeParse(input).success).toBe(false);
|
||||
expect(artifactInspectionInputSchema.safeParse(input).success).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects contradictory tool availability states", () => {
|
||||
const inventory = buildCapabilityInventory(
|
||||
{ open: false, capabilities: [] },
|
||||
{
|
||||
processCaptureEnabled: false,
|
||||
evidenceFileRoots: 0,
|
||||
investigationInputRoots: 0,
|
||||
},
|
||||
);
|
||||
const unavailable = inventory.find(({ available }) => !available);
|
||||
expect(unavailable).toBeDefined();
|
||||
expect(toolAvailability.safeParse(unavailable).success).toBe(true);
|
||||
expect(
|
||||
toolAvailability.safeParse({ ...unavailable, available: true }).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
toolAvailability.safeParse({
|
||||
...unavailable,
|
||||
available: false,
|
||||
reason: "available",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("covers deterministic contract rendering and defensive helper errors", () => {
|
||||
const rendered = renderGuidedPrompt(PROMPT_CONTRACTS[0], {
|
||||
zulu: "last",
|
||||
alpha: "first",
|
||||
});
|
||||
expect(rendered).toContain('"alpha":"first"');
|
||||
expect(
|
||||
annotationsFromEffects({
|
||||
mutatesTarget: false,
|
||||
mutatesSession: false,
|
||||
writesFilesystem: false,
|
||||
launchesProcess: false,
|
||||
accessesNetwork: true,
|
||||
changesUiState: false,
|
||||
mayDiscardData: false,
|
||||
idempotent: true,
|
||||
}).openWorldHint,
|
||||
).toBe(true);
|
||||
expect(() => toolContractMetadata("missing_tool")).toThrow(
|
||||
/Missing effect audit/u,
|
||||
);
|
||||
expect(() => requireOutputSchema({}, "missing_output")).toThrow(
|
||||
/Missing output schema/u,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -28,12 +28,16 @@ export const analysisErrorRemediationAction = (
|
||||
return "Check that the unknown_id belongs to this session, then retry.";
|
||||
if (error instanceof ReplayPlanStaleError)
|
||||
return "Review the rebuilt replay plan and explicitly approve its new digest.";
|
||||
if (error instanceof PermissionRequiredError)
|
||||
return error.restartRequired
|
||||
? "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client."
|
||||
: error.elicitationSupported
|
||||
? "Approve the exact missing scope, then retry the operation."
|
||||
: "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
if (error instanceof PermissionRequiredError) {
|
||||
switch (error.remediation) {
|
||||
case "configure":
|
||||
return "Add the exact missing scope beneath the administrator ceiling, then retry.";
|
||||
case "elicit":
|
||||
return "Approve the exact missing scope, then retry the operation.";
|
||||
case "restart":
|
||||
return "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client.";
|
||||
}
|
||||
}
|
||||
return analysisErrorUserMessage(error);
|
||||
};
|
||||
|
||||
|
||||
@@ -50,9 +50,10 @@ export const projectAnalysisError = (
|
||||
remediation: {
|
||||
action: analysisErrorRemediationAction(error),
|
||||
restart_required:
|
||||
error instanceof PermissionRequiredError && error.restartRequired,
|
||||
error instanceof PermissionRequiredError &&
|
||||
error.remediation === "restart",
|
||||
...(error instanceof PermissionRequiredError
|
||||
? { elicitation_supported: error.elicitationSupported }
|
||||
? { elicitation_supported: error.remediation === "elicit" }
|
||||
: {}),
|
||||
},
|
||||
...(details === undefined ? {} : { details }),
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ import {
|
||||
analysisProfileSchema,
|
||||
analysisProfilesEqual,
|
||||
createAnalysisProfile,
|
||||
} from "../../../src/domain/analysisProfile.js";
|
||||
} from "./analysisProfile.js";
|
||||
|
||||
const PROVIDER = {
|
||||
id: "fixture",
|
||||
@@ -0,0 +1,26 @@
|
||||
import { createAnalysisProfile } from "./analysisProfile.js";
|
||||
import type { BinaryTarget } from "./binaryTarget.js";
|
||||
|
||||
/** Immutable target shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_TARGET: BinaryTarget = {
|
||||
path: "/tmp/app",
|
||||
sha256: "a".repeat(64),
|
||||
kind: "executable",
|
||||
format: "mach-o",
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["arm64"],
|
||||
};
|
||||
|
||||
/** Provider identity shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_PROVIDER = {
|
||||
id: "fixture",
|
||||
name: "Fixture",
|
||||
version: "1",
|
||||
} as const;
|
||||
|
||||
/** Exact analysis profile shared by analysis-snapshot contract tests. */
|
||||
export const ANALYSIS_SNAPSHOT_PROFILE = createAnalysisProfile(
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
1,
|
||||
{ loader: "mach-o-arm64" },
|
||||
);
|
||||
@@ -0,0 +1,73 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
type AnalysisSnapshot,
|
||||
parseAnalysisSnapshot,
|
||||
snapshotBinding,
|
||||
snapshotEvidenceForQuery,
|
||||
snapshotTarget,
|
||||
} from "./analysisSnapshot.js";
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_PROFILE,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
} from "./analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
|
||||
describe("analysis snapshot contract", () => {
|
||||
it("finds only Evidence committed to the exact binding and profile", () => {
|
||||
const evidence = createEvidence(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{
|
||||
operation: "analyze_function",
|
||||
parameters: { procedure: "main" },
|
||||
result: { summary: "cached" },
|
||||
analysisProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
},
|
||||
);
|
||||
const legacy = createEvidence(
|
||||
ANALYSIS_SNAPSHOT_TARGET,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
{
|
||||
operation: "legacy_query",
|
||||
parameters: {},
|
||||
result: { summary: "legacy" },
|
||||
},
|
||||
);
|
||||
const snapshot: AnalysisSnapshot = {
|
||||
snapshot_version: 2,
|
||||
target: snapshotTarget(ANALYSIS_SNAPSHOT_TARGET),
|
||||
binding: snapshotBinding(ANALYSIS_SNAPSHOT_PROFILE),
|
||||
entries: [],
|
||||
evidence_bundle: createEvidenceBundle([evidence, legacy]),
|
||||
};
|
||||
expect(
|
||||
snapshotEvidenceForQuery(snapshot, {
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
bindingProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
operation: "analyze_function",
|
||||
parameters: { procedure: "main" },
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
}),
|
||||
).toEqual(evidence);
|
||||
expect(
|
||||
snapshotEvidenceForQuery(snapshot, {
|
||||
target: ANALYSIS_SNAPSHOT_TARGET,
|
||||
bindingProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
operation: "legacy_query",
|
||||
parameters: {},
|
||||
provider: ANALYSIS_SNAPSHOT_PROVIDER,
|
||||
evidenceProfile: ANALYSIS_SNAPSHOT_PROFILE,
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("rejects snapshot v1 with explicit recapture guidance", () => {
|
||||
expect(() => parseAnalysisSnapshot({ snapshot_version: 1 })).toThrow(
|
||||
/v1.*recapture.*v2/iu,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/** Build a minimal ELF header for binary-target parser tests. */
|
||||
export const elf = (
|
||||
class_: number,
|
||||
endian: number,
|
||||
machine: number,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(20);
|
||||
bytes.set([0x7f, 0x45, 0x4c, 0x46, class_, endian]);
|
||||
if (endian === 1) bytes.writeUInt16LE(machine, 18);
|
||||
else bytes.writeUInt16BE(machine, 18);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a minimal thin Mach-O header for binary-target parser tests. */
|
||||
export const thinMach = (magic: number, cpu: number): Buffer => {
|
||||
const bytes = Buffer.alloc(8);
|
||||
bytes.writeUInt32BE(magic, 0);
|
||||
if (magic === 0xcefaedfe || magic === 0xcffaedfe) bytes.writeUInt32LE(cpu, 4);
|
||||
else bytes.writeUInt32BE(cpu, 4);
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a minimal FAT Mach-O table for binary-target parser tests. */
|
||||
export const fat = (
|
||||
cpus: readonly number[],
|
||||
declared = cpus.length,
|
||||
): Buffer => {
|
||||
const bytes = Buffer.alloc(8 + cpus.length * 20);
|
||||
bytes.writeUInt32BE(0xcafebabe, 0);
|
||||
bytes.writeUInt32BE(declared, 4);
|
||||
cpus.forEach((cpu, index) => bytes.writeUInt32BE(cpu, 8 + index * 20));
|
||||
return bytes;
|
||||
};
|
||||
|
||||
/** Build a bounded PE image with optional managed metadata. */
|
||||
export const pe = (
|
||||
machine: number,
|
||||
offset = 64,
|
||||
characteristics = 0x0002,
|
||||
managed = false,
|
||||
): Buffer => {
|
||||
const optionalHeaderSize =
|
||||
machine === 0x014c || machine === 0x01c0 ? 224 : 240;
|
||||
const bytes = Buffer.alloc(Math.max(512, offset + 24 + optionalHeaderSize));
|
||||
bytes.write("MZ", 0, "ascii");
|
||||
bytes.writeUInt32LE(offset, 0x3c);
|
||||
bytes.write("PE\0\0", offset, "binary");
|
||||
bytes.writeUInt16LE(machine, offset + 4);
|
||||
bytes.writeUInt16LE(optionalHeaderSize, offset + 20);
|
||||
bytes.writeUInt16LE(characteristics, offset + 22);
|
||||
const optionalHeader = offset + 24;
|
||||
const pe32 = machine === 0x014c || machine === 0x01c0;
|
||||
bytes.writeUInt16LE(pe32 ? 0x10b : 0x20b, optionalHeader);
|
||||
const directoryOffset = pe32 ? 96 : 112;
|
||||
bytes.writeUInt32LE(16, optionalHeader + directoryOffset - 4);
|
||||
if (managed) {
|
||||
bytes.writeUInt32LE(0x2000, optionalHeader + directoryOffset + 14 * 8);
|
||||
bytes.writeUInt32LE(72, optionalHeader + directoryOffset + 14 * 8 + 4);
|
||||
}
|
||||
return bytes;
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseExecutableHeader } from "./binaryTarget.js";
|
||||
import { elf, fat, pe, thinMach } from "./binaryTarget.fixture.js";
|
||||
|
||||
describe("executable header parsing", () => {
|
||||
it.each([
|
||||
[elf(1, 1, 62), "elf", "x86_64"],
|
||||
[elf(2, 2, 183), "elf", "arm64"],
|
||||
[thinMach(0xfeedfacf, 0x0100000c), "mach-o", "arm64"],
|
||||
[thinMach(0xcefaedfe, 0x01000007), "mach-o", "x86_64"],
|
||||
[pe(0x8664), "pe", "x86_64"],
|
||||
[pe(0xaa64), "pe", "arm64"],
|
||||
] as const)("parses metadata for %s", (bytes, format, architecture) => {
|
||||
const result = parseExecutableHeader(bytes, "arm64");
|
||||
expect(result.ok && result.value).toMatchObject({ format, architecture });
|
||||
});
|
||||
|
||||
it("distinguishes native PE applications, DLLs, and managed assemblies", () => {
|
||||
const application = parseExecutableHeader(pe(0x8664), "x64");
|
||||
const library = parseExecutableHeader(pe(0x8664, 64, 0x2002), "x64");
|
||||
const managed = parseExecutableHeader(pe(0x8664, 64, 0x0002, true), "x64");
|
||||
const nonExecutable = parseExecutableHeader(pe(0x8664, 64, 0), "x64");
|
||||
|
||||
expect(application.ok && application.value).toMatchObject({
|
||||
executableRole: "application",
|
||||
managed: false,
|
||||
});
|
||||
expect(library.ok && library.value).toMatchObject({
|
||||
executableRole: "shared-library",
|
||||
managed: false,
|
||||
});
|
||||
expect(managed.ok && managed.value).toMatchObject({
|
||||
executableRole: "application",
|
||||
managed: true,
|
||||
});
|
||||
expect(nonExecutable.ok && nonExecutable.value).toMatchObject({
|
||||
executableRole: "non-executable",
|
||||
managed: false,
|
||||
});
|
||||
});
|
||||
|
||||
it("selects the host architecture from a FAT table", () => {
|
||||
const bytes = fat([0x01000007, 0x0100000c]);
|
||||
const arm = parseExecutableHeader(bytes, "arm64");
|
||||
const intel = parseExecutableHeader(bytes, "x64");
|
||||
expect(arm.ok && arm.value).toMatchObject({
|
||||
architecture: "arm64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
});
|
||||
expect(intel.ok && intel.value).toMatchObject({
|
||||
architecture: "x86_64",
|
||||
availableArchitectures: ["x86_64", "arm64"],
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects FAT files without a host-compatible slice", () => {
|
||||
expect(parseExecutableHeader(fat([0x01000007]), "arm64")).toMatchObject({
|
||||
ok: false,
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
Buffer.alloc(0),
|
||||
Buffer.from([0x7f, 0x45, 0x4c, 0x46]),
|
||||
fat([], 2),
|
||||
pe(0xffff),
|
||||
])("rejects malformed, truncated, or unsupported metadata", (bytes) => {
|
||||
expect(parseExecutableHeader(bytes, "arm64").ok).toBe(false);
|
||||
});
|
||||
|
||||
it("rejects malformed PE optional-header commitments", () => {
|
||||
const wrongMagic = pe(0x8664);
|
||||
wrongMagic.writeUInt16LE(0x10b, 64 + 24);
|
||||
const truncatedDirectories = pe(0x8664);
|
||||
truncatedDirectories.writeUInt16LE(112, 64 + 20);
|
||||
truncatedDirectories.writeUInt32LE(16, 64 + 24 + 108);
|
||||
|
||||
expect(parseExecutableHeader(wrongMagic, "x64").ok).toBe(false);
|
||||
expect(parseExecutableHeader(truncatedDirectories, "x64").ok).toBe(false);
|
||||
});
|
||||
});
|
||||
+2
-99
@@ -1,10 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { listBrowserTargets } from "../../../src/application/BrowserObservationService.js";
|
||||
import { createPermissionAuthority } from "../../../src/application/PermissionAuthority.js";
|
||||
import { CdpCaptureCompleteness } from "../../../src/browser/CdpCaptureCompleteness.js";
|
||||
import { CdpCaptureEvents } from "../../../src/browser/CdpCaptureEvents.js";
|
||||
import { ingestElectronScriptEvent } from "../../../src/browser/CdpElectronScriptEvents.js";
|
||||
import {
|
||||
browserEndpointSchema,
|
||||
browserOriginSchema,
|
||||
@@ -12,8 +7,8 @@ import {
|
||||
isLiteralLoopbackHostname,
|
||||
listBrowserTargetsInputSchema,
|
||||
sanitizeBrowserUrl,
|
||||
} from "../../../src/domain/browserObservation.js";
|
||||
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js";
|
||||
} from "./browserObservation.js";
|
||||
import { captureWebScreenshotInputSchema } from "./webScreenshot.js";
|
||||
|
||||
describe("browser observation contracts", () => {
|
||||
it("normalizes exact HTTP origins without accepting broader URL scopes", () => {
|
||||
@@ -57,46 +52,6 @@ describe("browser observation contracts", () => {
|
||||
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false);
|
||||
});
|
||||
|
||||
it("requests loopback authority for an IPv6-only browser origin", async () => {
|
||||
const endpoint = "http://127.0.0.1:9222";
|
||||
const origin = "http://[::1]:3000";
|
||||
const ceiling = {
|
||||
capability: "browser_observe" as const,
|
||||
roots: [],
|
||||
executables: [],
|
||||
environment_names: [],
|
||||
origins: [endpoint, origin],
|
||||
network: "loopback" as const,
|
||||
mount: false,
|
||||
};
|
||||
const authority = await createPermissionAuthority(
|
||||
[ceiling],
|
||||
[
|
||||
{
|
||||
...ceiling,
|
||||
grant_id: "administrator:browser_observe",
|
||||
lifetime: "administrator",
|
||||
operation_identity: null,
|
||||
expires_at: null,
|
||||
},
|
||||
],
|
||||
);
|
||||
if (!authority.ok) throw authority.error;
|
||||
const result = await listBrowserTargets(
|
||||
undefined,
|
||||
authority.value,
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
cdp_endpoint: endpoint,
|
||||
allowed_origins: [origin],
|
||||
approved: true,
|
||||
}),
|
||||
);
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("applies conservative bounded defaults to public tool input", () => {
|
||||
expect(
|
||||
listBrowserTargetsInputSchema.parse({
|
||||
@@ -194,58 +149,6 @@ describe("browser observation sensitive surfaces and retention", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("removes stale frame attribution when CDP destroys execution contexts", () => {
|
||||
const request = inspectWebPageInputSchema.parse({
|
||||
cdp_endpoint: "http://127.0.0.1:9222",
|
||||
allowed_origins: ["https://app.example.test"],
|
||||
target_id: "page-1",
|
||||
approved: true,
|
||||
});
|
||||
const browser = new CdpCaptureEvents(
|
||||
request,
|
||||
new Set(["https://app.example.test"]),
|
||||
);
|
||||
browser.beginAuthorizedFrame("frame-old");
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Runtime.executionContextDestroyed",
|
||||
params: { executionContextId: 7 },
|
||||
});
|
||||
browser.ingest({
|
||||
method: "Debugger.scriptParsed",
|
||||
params: {
|
||||
scriptId: "script-1",
|
||||
url: "https://app.example.test/app.js",
|
||||
executionContextId: 7,
|
||||
},
|
||||
});
|
||||
const script = browser.scripts.get("script-1");
|
||||
if (script === undefined) throw new TypeError("Expected captured script");
|
||||
expect(browser.frameForScript(script, new Set(["frame-old"]))).toBeNull();
|
||||
|
||||
const electronFrames = new Map<string, string>();
|
||||
const completeness = new CdpCaptureCompleteness();
|
||||
ingestElectronScriptEvent({
|
||||
event: {
|
||||
method: "Runtime.executionContextCreated",
|
||||
params: { context: { id: 7, auxData: { frameId: "frame-old" } } },
|
||||
},
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
ingestElectronScriptEvent({
|
||||
event: { method: "Runtime.executionContextsCleared", params: {} },
|
||||
scripts: [],
|
||||
executionContextFrames: electronFrames,
|
||||
completeness,
|
||||
});
|
||||
expect(electronFrames.size).toBe(0);
|
||||
});
|
||||
|
||||
it("removes credentials, query values, and fragments from observed URLs", () => {
|
||||
expect(
|
||||
sanitizeBrowserUrl(
|
||||
@@ -0,0 +1,106 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { sanitizeBrowserUrl } from "./browserObservation.js";
|
||||
import {
|
||||
browserScenarioCompletenessSchema,
|
||||
browserScenarioEventSchema,
|
||||
browserStepArtifactsSchema,
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
const networkEvent = {
|
||||
sequence: 1,
|
||||
step_index: 0,
|
||||
method: "GET",
|
||||
url: sanitizeBrowserUrl("https://example.test/resource"),
|
||||
resource_type: "document",
|
||||
header_names: [],
|
||||
} as const;
|
||||
|
||||
it("parses each network outcome without contradictory status or failure data", () => {
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...networkEvent,
|
||||
kind: "response",
|
||||
status: null,
|
||||
failure: null,
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...networkEvent,
|
||||
kind: "request-failed",
|
||||
status: 500,
|
||||
failure: "connection reset",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps WebSocket payload representation tied to its payload type", () => {
|
||||
const frame = {
|
||||
sequence: 1,
|
||||
step_index: 0,
|
||||
kind: "websocket-frame-received",
|
||||
url: sanitizeBrowserUrl("https://example.test/socket"),
|
||||
payload_bytes: 3,
|
||||
truncated: false,
|
||||
} as const;
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...frame,
|
||||
payload_type: "binary",
|
||||
payload_text: "abc",
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioEventSchema.safeParse({
|
||||
...frame,
|
||||
payload_type: "text",
|
||||
payload_text: "abc",
|
||||
}).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("does not attach a content digest to redacted storage secrets", () => {
|
||||
expect(
|
||||
browserStepArtifactsSchema.safeParse({
|
||||
screenshot: { state: "not_requested" },
|
||||
dom: { state: "not_requested" },
|
||||
accessibility: { state: "not_requested" },
|
||||
url: { state: "not_requested" },
|
||||
history: { state: "not_requested" },
|
||||
storage: {
|
||||
state: "captured",
|
||||
value: {
|
||||
cookies: [],
|
||||
local_storage: [
|
||||
{
|
||||
name: "session",
|
||||
value_state: "redacted-secret",
|
||||
value_sha256: "a".repeat(64),
|
||||
},
|
||||
],
|
||||
session_storage: [],
|
||||
},
|
||||
},
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it("derives equality eligibility from exact completeness state", () => {
|
||||
expect(
|
||||
browserScenarioCompletenessSchema.safeParse({
|
||||
status: "complete",
|
||||
equality_eligible: false,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
browserScenarioCompletenessSchema.safeParse({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: ["dom"],
|
||||
truncated_sections: ["events"],
|
||||
}).success,
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -7,14 +7,17 @@ import {
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
export {
|
||||
classifyBrowserScenarioCompleteness,
|
||||
browserScenarioCompletenessSchema,
|
||||
browserScenarioEventSchema,
|
||||
browserScenarioStepSchema,
|
||||
browserStepArtifactsSchema,
|
||||
captureStateSchema,
|
||||
type BrowserScenarioCompleteness,
|
||||
type BrowserScenarioCompletenessSection,
|
||||
type BrowserScenarioEvent,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserScenarioStepOutcome,
|
||||
type BrowserStepArtifacts,
|
||||
} from "./browserScenarioCaptureValues.js";
|
||||
|
||||
|
||||
@@ -65,25 +65,49 @@ const historySchema = z.strictObject({
|
||||
.max(256),
|
||||
});
|
||||
|
||||
const storageValueSchema = z.strictObject({
|
||||
const hashedStorageValueShape = {
|
||||
value_state: z.literal("hashed"),
|
||||
value_sha256: digestSchema,
|
||||
};
|
||||
const redactedStorageValueShape = {
|
||||
value_state: z.literal("redacted-secret"),
|
||||
value_sha256: z.null(),
|
||||
};
|
||||
const storageValueFingerprintSchema = z.discriminatedUnion("value_state", [
|
||||
z.strictObject(hashedStorageValueShape),
|
||||
z.strictObject(redactedStorageValueShape),
|
||||
]);
|
||||
export type BrowserStorageValueFingerprint = z.infer<
|
||||
typeof storageValueFingerprintSchema
|
||||
>;
|
||||
|
||||
const storageValueSchema = z.discriminatedUnion("value_state", [
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
...hashedStorageValueShape,
|
||||
}),
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
...redactedStorageValueShape,
|
||||
}),
|
||||
]);
|
||||
|
||||
const cookieShape = {
|
||||
name: z.string().max(1_024),
|
||||
value_state: z.enum(["hashed", "redacted-secret"]),
|
||||
value_sha256: digestSchema.nullable(),
|
||||
});
|
||||
domain: z.string().max(2_048),
|
||||
path: z.string().max(4_096),
|
||||
secure: z.boolean(),
|
||||
http_only: z.boolean(),
|
||||
same_site: z.enum(["Strict", "Lax", "None"]),
|
||||
};
|
||||
|
||||
const storageSnapshotSchema = z.strictObject({
|
||||
cookies: z
|
||||
.array(
|
||||
z.strictObject({
|
||||
name: z.string().max(1_024),
|
||||
domain: z.string().max(2_048),
|
||||
path: z.string().max(4_096),
|
||||
secure: z.boolean(),
|
||||
http_only: z.boolean(),
|
||||
same_site: z.enum(["Strict", "Lax", "None"]),
|
||||
value_state: z.enum(["hashed", "redacted-secret"]),
|
||||
value_sha256: digestSchema.nullable(),
|
||||
}),
|
||||
z.discriminatedUnion("value_state", [
|
||||
z.strictObject({ ...cookieShape, ...hashedStorageValueShape }),
|
||||
z.strictObject({ ...cookieShape, ...redactedStorageValueShape }),
|
||||
]),
|
||||
)
|
||||
.max(512),
|
||||
local_storage: z.array(storageValueSchema).max(512),
|
||||
@@ -106,8 +130,22 @@ const eventBase = {
|
||||
};
|
||||
|
||||
const eventUrl = sanitizedBrowserUrlSchema.nullable();
|
||||
const networkEventShape = {
|
||||
...eventBase,
|
||||
method: z.string().min(1).max(32),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
resource_type: z.string().min(1).max(64),
|
||||
header_names: z.array(z.string().max(256)).max(256),
|
||||
};
|
||||
const webSocketFrameShape = {
|
||||
...eventBase,
|
||||
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
payload_bytes: z.number().int().min(0),
|
||||
truncated: z.boolean(),
|
||||
};
|
||||
|
||||
export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
export const browserScenarioEventSchema = z.union([
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.literal("console"),
|
||||
@@ -122,14 +160,22 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
stack: z.string().max(262_144).nullable(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.enum(["request", "response", "request-failed"]),
|
||||
method: z.string().min(1).max(32),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
resource_type: z.string().min(1).max(64),
|
||||
status: z.number().int().min(100).max(599).nullable(),
|
||||
header_names: z.array(z.string().max(256)).max(256),
|
||||
failure: z.string().max(1_024).nullable(),
|
||||
...networkEventShape,
|
||||
kind: z.literal("request"),
|
||||
status: z.null(),
|
||||
failure: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...networkEventShape,
|
||||
kind: z.literal("response"),
|
||||
status: z.number().int().min(100).max(599),
|
||||
failure: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...networkEventShape,
|
||||
kind: z.literal("request-failed"),
|
||||
status: z.null(),
|
||||
failure: z.string().min(1).max(1_024),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
@@ -137,13 +183,14 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]),
|
||||
url: sanitizedBrowserUrlSchema,
|
||||
payload_type: z.enum(["text", "binary"]),
|
||||
payload_bytes: z.number().int().min(0),
|
||||
payload_text: z.string().max(65_536).nullable(),
|
||||
truncated: z.boolean(),
|
||||
...webSocketFrameShape,
|
||||
payload_type: z.literal("text"),
|
||||
payload_text: z.string().max(65_536),
|
||||
}),
|
||||
z.strictObject({
|
||||
...webSocketFrameShape,
|
||||
payload_type: z.literal("binary"),
|
||||
payload_text: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...eventBase,
|
||||
@@ -182,50 +229,92 @@ const completenessSectionSchema = z.enum([
|
||||
"popups",
|
||||
"websockets",
|
||||
]);
|
||||
export type BrowserScenarioCompletenessSection = z.infer<
|
||||
typeof completenessSectionSchema
|
||||
>;
|
||||
|
||||
export const browserScenarioCompletenessSchema = z
|
||||
.strictObject({
|
||||
status: z.enum(["complete", "incomplete", "truncated"]),
|
||||
equality_eligible: z.boolean(),
|
||||
missing_sections: z.array(completenessSectionSchema),
|
||||
truncated_sections: z.array(completenessSectionSchema),
|
||||
})
|
||||
.superRefine((value, context) => {
|
||||
const expectedStatus =
|
||||
value.truncated_sections.length > 0
|
||||
? "truncated"
|
||||
: value.missing_sections.length > 0
|
||||
? "incomplete"
|
||||
: "complete";
|
||||
if (value.status !== expectedStatus)
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["status"],
|
||||
message: "Completeness status does not match section accounting",
|
||||
});
|
||||
if (value.equality_eligible !== (expectedStatus === "complete"))
|
||||
context.addIssue({
|
||||
code: "custom",
|
||||
path: ["equality_eligible"],
|
||||
message: "Missing or truncated evidence is never equality-eligible",
|
||||
});
|
||||
});
|
||||
export const browserScenarioCompletenessSchema = z.discriminatedUnion(
|
||||
"status",
|
||||
[
|
||||
z.strictObject({
|
||||
status: z.literal("complete"),
|
||||
equality_eligible: z.literal(true),
|
||||
missing_sections: z.tuple([]),
|
||||
truncated_sections: z.tuple([]),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("incomplete"),
|
||||
equality_eligible: z.literal(false),
|
||||
missing_sections: z.array(completenessSectionSchema).min(1),
|
||||
truncated_sections: z.tuple([]),
|
||||
}),
|
||||
z.strictObject({
|
||||
status: z.literal("truncated"),
|
||||
equality_eligible: z.literal(false),
|
||||
missing_sections: z.array(completenessSectionSchema),
|
||||
truncated_sections: z.array(completenessSectionSchema).min(1),
|
||||
}),
|
||||
],
|
||||
);
|
||||
export type BrowserScenarioCompleteness = z.infer<
|
||||
typeof browserScenarioCompletenessSchema
|
||||
>;
|
||||
|
||||
export const browserScenarioStepSchema = z.strictObject({
|
||||
/** Classify canonical browser-scenario completeness from section accounting. */
|
||||
export const classifyBrowserScenarioCompleteness = (
|
||||
missing: Iterable<BrowserScenarioCompletenessSection>,
|
||||
truncated: Iterable<BrowserScenarioCompletenessSection>,
|
||||
): BrowserScenarioCompleteness => {
|
||||
const missingSections = [...new Set(missing)].sort();
|
||||
const truncatedSections = [...new Set(truncated)].sort();
|
||||
if (truncatedSections.length > 0)
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: "truncated",
|
||||
equality_eligible: false,
|
||||
missing_sections: missingSections,
|
||||
truncated_sections: truncatedSections,
|
||||
});
|
||||
if (missingSections.length > 0)
|
||||
return browserScenarioCompletenessSchema.parse({
|
||||
status: "incomplete",
|
||||
equality_eligible: false,
|
||||
missing_sections: missingSections,
|
||||
truncated_sections: [],
|
||||
});
|
||||
return {
|
||||
status: "complete",
|
||||
equality_eligible: true,
|
||||
missing_sections: [],
|
||||
truncated_sections: [],
|
||||
};
|
||||
};
|
||||
|
||||
const browserScenarioStepShape = {
|
||||
step_index: z.number().int().min(0),
|
||||
step_id: z.string().min(1).max(64),
|
||||
action: z.string().min(1).max(64),
|
||||
status: z.enum(["completed", "failed", "cancelled"]),
|
||||
elapsed_ms: z.number().int().min(0),
|
||||
before_url: sanitizedBrowserUrlSchema,
|
||||
after_url: sanitizedBrowserUrlSchema,
|
||||
error: z.string().max(4_096).nullable(),
|
||||
event_sequence_start: z.number().int().min(1),
|
||||
event_sequence_end: z.number().int().min(0),
|
||||
artifacts: browserStepArtifactsSchema,
|
||||
completeness: browserScenarioCompletenessSchema,
|
||||
});
|
||||
};
|
||||
export const browserScenarioStepSchema = z.union([
|
||||
z.strictObject({
|
||||
...browserScenarioStepShape,
|
||||
status: z.literal("completed"),
|
||||
error: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...browserScenarioStepShape,
|
||||
status: z.enum(["failed", "cancelled"]),
|
||||
error: z.string().max(4_096),
|
||||
}),
|
||||
]);
|
||||
export type BrowserScenarioStep = z.infer<typeof browserScenarioStepSchema>;
|
||||
type StepOutcome<Step> = Step extends BrowserScenarioStep
|
||||
? Pick<Step, "status" | "error">
|
||||
: never;
|
||||
export type BrowserScenarioStepOutcome = StepOutcome<BrowserScenarioStep>;
|
||||
|
||||
+2
-2
@@ -5,11 +5,11 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
compareBrowserScenarios,
|
||||
compareBrowserScenariosInputSchema,
|
||||
} from "../../../src/domain/browserScenarioDiff.js";
|
||||
} from "./browserScenarioDiff.js";
|
||||
import {
|
||||
browserScenarioCaptureSchema,
|
||||
type BrowserScenarioCapture,
|
||||
} from "../../../src/domain/browserScenarioCapture.js";
|
||||
} from "./browserScenarioCapture.js";
|
||||
|
||||
describe("browser scenario comparison", () => {
|
||||
it("records canonical literal normalization and ignores declared volatile fields", () => {
|
||||
@@ -1,8 +1,16 @@
|
||||
import {
|
||||
type BrowserScenarioCapture,
|
||||
type BrowserScenarioStep,
|
||||
type BrowserStepArtifacts,
|
||||
} from "./browserScenarioCapture.js";
|
||||
import {
|
||||
actionState,
|
||||
artifactEvidenceState,
|
||||
captured,
|
||||
eventEvidenceState,
|
||||
eventsFor,
|
||||
screenshotProjection,
|
||||
type CaptureState,
|
||||
} from "./browserScenarioDiffEvidence.js";
|
||||
import {
|
||||
browserScenarioDiffSchema,
|
||||
type BrowserScenarioAlignmentFailure,
|
||||
@@ -26,22 +34,18 @@ export {
|
||||
type CompareBrowserScenariosInput,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
type CaptureState<T> =
|
||||
| { readonly state: "captured"; readonly value: T }
|
||||
| { readonly state: "not_requested" }
|
||||
| { readonly state: "missing"; readonly reason: string }
|
||||
| {
|
||||
readonly state: "truncated";
|
||||
readonly observed: number;
|
||||
readonly retained: number;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
interface ComparableArtifact {
|
||||
type ComparableArtifact = {
|
||||
readonly artifact: BrowserScenarioArtifactKind;
|
||||
readonly status: "changed" | "unchanged" | "unknown" | "not_compared";
|
||||
readonly diff: BrowserScenarioArtifactDiff | null;
|
||||
}
|
||||
} & (
|
||||
| {
|
||||
readonly status: "unchanged" | "not_compared";
|
||||
readonly diff: null;
|
||||
}
|
||||
| {
|
||||
readonly status: "changed" | "unknown";
|
||||
readonly diff: BrowserScenarioArtifactDiff;
|
||||
}
|
||||
);
|
||||
|
||||
interface ScenarioAlignment {
|
||||
readonly before: ReadonlyMap<string, BrowserScenarioStep>;
|
||||
@@ -434,80 +438,3 @@ const compareCapturedValues = <Value>(
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const artifactEvidenceState = <Value>(
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
state: CaptureState<Value>,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
if (state.state !== "captured") return state.state;
|
||||
const section = artifact === "action_state" ? "action" : artifact;
|
||||
if (step.completeness.truncated_sections.includes(section))
|
||||
return "truncated";
|
||||
if (step.completeness.missing_sections.includes(section)) return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const eventEvidenceState = (
|
||||
capture: BrowserScenarioCapture,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
const sections = [
|
||||
"events",
|
||||
"frames",
|
||||
"workers",
|
||||
"popups",
|
||||
"websockets",
|
||||
] as const;
|
||||
if (
|
||||
capture.events.dropped > 0 ||
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.truncated_sections.includes(section) ||
|
||||
step.completeness.truncated_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "truncated";
|
||||
if (
|
||||
sections.some(
|
||||
(section) =>
|
||||
capture.completeness.missing_sections.includes(section) ||
|
||||
step.completeness.missing_sections.includes(section),
|
||||
)
|
||||
)
|
||||
return "missing";
|
||||
return "captured";
|
||||
};
|
||||
|
||||
const actionState = (step: BrowserScenarioStep) => ({
|
||||
action: step.action,
|
||||
status: step.status,
|
||||
before_url: step.before_url,
|
||||
after_url: step.after_url,
|
||||
error: step.error,
|
||||
});
|
||||
|
||||
const eventsFor = (
|
||||
capture: BrowserScenarioCapture,
|
||||
stepIndex: number,
|
||||
): readonly unknown[] =>
|
||||
capture.events.items.flatMap(
|
||||
({ sequence: _sequence, step_index: eventStepIndex, ...event }) =>
|
||||
eventStepIndex === stepIndex ? [event] : [],
|
||||
);
|
||||
|
||||
const captured = <Value>(value: Value): CaptureState<Value> => ({
|
||||
state: "captured",
|
||||
value,
|
||||
});
|
||||
|
||||
const screenshotProjection = (
|
||||
screenshot: Extract<
|
||||
BrowserStepArtifacts["screenshot"],
|
||||
{ state: "captured" }
|
||||
>["value"],
|
||||
) => ({
|
||||
sha256: screenshot.sha256,
|
||||
bytes: screenshot.bytes,
|
||||
media_type: screenshot.media_type,
|
||||
});
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import type {
|
||||
BrowserScenarioCapture,
|
||||
BrowserScenarioCompleteness,
|
||||
BrowserScenarioCompletenessSection,
|
||||
BrowserScenarioStep,
|
||||
BrowserStepArtifacts,
|
||||
} from "./browserScenarioCapture.js";
|
||||
import type {
|
||||
BrowserScenarioArtifactKind,
|
||||
BrowserScenarioEvidenceState,
|
||||
} from "./browserScenarioDiffValues.js";
|
||||
|
||||
/** Capture-state input consumed by browser scenario artifact comparison. */
|
||||
export type CaptureState<Value> =
|
||||
| { readonly state: "captured"; readonly value: Value }
|
||||
| { readonly state: "not_requested" }
|
||||
| { readonly state: "missing"; readonly reason: string }
|
||||
| {
|
||||
readonly state: "truncated";
|
||||
readonly observed: number;
|
||||
readonly retained: number;
|
||||
readonly reason: string;
|
||||
};
|
||||
|
||||
const includesCompletenessSection = (
|
||||
completeness: BrowserScenarioCompleteness,
|
||||
collection: "missing_sections" | "truncated_sections",
|
||||
section: BrowserScenarioCompletenessSection,
|
||||
): boolean => {
|
||||
const sections: readonly BrowserScenarioCompletenessSection[] =
|
||||
completeness[collection];
|
||||
return sections.includes(section);
|
||||
};
|
||||
|
||||
/** Project one captured artifact through its step-level completeness ledger. */
|
||||
export const artifactEvidenceState = <Value>(
|
||||
artifact: BrowserScenarioArtifactKind,
|
||||
state: CaptureState<Value>,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
if (state.state !== "captured") return state.state;
|
||||
const section = artifact === "action_state" ? "action" : artifact;
|
||||
if (
|
||||
includesCompletenessSection(
|
||||
step.completeness,
|
||||
"truncated_sections",
|
||||
section,
|
||||
)
|
||||
)
|
||||
return "truncated";
|
||||
return includesCompletenessSection(
|
||||
step.completeness,
|
||||
"missing_sections",
|
||||
section,
|
||||
)
|
||||
? "missing"
|
||||
: "captured";
|
||||
};
|
||||
|
||||
const EVENT_SECTIONS = [
|
||||
"events",
|
||||
"frames",
|
||||
"workers",
|
||||
"popups",
|
||||
"websockets",
|
||||
] as const;
|
||||
|
||||
/** Project event evidence through capture- and step-level completeness. */
|
||||
export const eventEvidenceState = (
|
||||
capture: BrowserScenarioCapture,
|
||||
step: BrowserScenarioStep,
|
||||
): BrowserScenarioEvidenceState => {
|
||||
const listed = (collection: "missing_sections" | "truncated_sections") =>
|
||||
EVENT_SECTIONS.some(
|
||||
(section) =>
|
||||
includesCompletenessSection(
|
||||
capture.completeness,
|
||||
collection,
|
||||
section,
|
||||
) ||
|
||||
includesCompletenessSection(step.completeness, collection, section),
|
||||
);
|
||||
if (capture.events.dropped > 0 || listed("truncated_sections"))
|
||||
return "truncated";
|
||||
return listed("missing_sections") ? "missing" : "captured";
|
||||
};
|
||||
|
||||
/** Select stable action fields for normalized comparison. */
|
||||
export const actionState = (step: BrowserScenarioStep) => ({
|
||||
action: step.action,
|
||||
status: step.status,
|
||||
before_url: step.before_url,
|
||||
after_url: step.after_url,
|
||||
error: step.error,
|
||||
});
|
||||
|
||||
/** Select events attributed to one scenario step without sequence metadata. */
|
||||
export const eventsFor = (
|
||||
capture: BrowserScenarioCapture,
|
||||
stepIndex: number,
|
||||
): readonly unknown[] =>
|
||||
capture.events.items.flatMap(
|
||||
({ sequence: _sequence, step_index: eventStepIndex, ...event }) =>
|
||||
eventStepIndex === stepIndex ? [event] : [],
|
||||
);
|
||||
|
||||
/** Wrap one value as captured comparison evidence. */
|
||||
export const captured = <Value>(value: Value): CaptureState<Value> => ({
|
||||
state: "captured",
|
||||
value,
|
||||
});
|
||||
|
||||
/** Retain stable screenshot identity without embedding image bytes. */
|
||||
export const screenshotProjection = (
|
||||
screenshot: Extract<
|
||||
BrowserStepArtifacts["screenshot"],
|
||||
{ state: "captured" }
|
||||
>["value"],
|
||||
) => ({
|
||||
sha256: screenshot.sha256,
|
||||
bytes: screenshot.bytes,
|
||||
media_type: screenshot.media_type,
|
||||
});
|
||||
+4
-4
@@ -3,15 +3,15 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
bundleComparisonResultSchema,
|
||||
compareBundles,
|
||||
} from "../../../src/domain/bundleComparison.js";
|
||||
import { createEvidence } from "../../../src/domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js";
|
||||
} from "./bundleComparison.js";
|
||||
import { createEvidence } from "./evidence.js";
|
||||
import { createEvidenceBundle } from "./evidenceBundle.js";
|
||||
import {
|
||||
createResidualUnknown,
|
||||
recordUnknownInputSchema,
|
||||
updateResidualUnknown,
|
||||
updateUnknownInputSchema,
|
||||
} from "../../../src/domain/residualUnknown.js";
|
||||
} from "./residualUnknown.js";
|
||||
|
||||
const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const;
|
||||
const evidence = (label: string) =>
|
||||
@@ -1,14 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { enhancedInputSchemas } from "../../../src/contracts/enhancedInputs.js";
|
||||
import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
|
||||
import {
|
||||
buildCallPath,
|
||||
callPathInputSchema,
|
||||
callPathResultSchema,
|
||||
} from "../../../src/domain/callPath.js";
|
||||
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js";
|
||||
import { functionDossierSchema } from "../../../src/domain/hopperValues.js";
|
||||
import { jsonValueSchema } from "../../../src/domain/jsonValue.js";
|
||||
} from "./callPath.js";
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import { functionDossierSchema } from "./hopperValues.js";
|
||||
import { jsonValueSchema } from "./jsonValue.js";
|
||||
|
||||
const bounded = <Item>(items: readonly Item[], complete = true) => ({
|
||||
items,
|
||||
+3
-3
@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
changedBehaviorResultSchema,
|
||||
findChangedBehavior,
|
||||
} from "../../../src/domain/changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js";
|
||||
import type { JsonValue } from "../../../src/domain/jsonValue.js";
|
||||
} from "./changedBehavior.js";
|
||||
import { createEvidence, type Evidence } from "./evidence.js";
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
const source = (digit: string): Evidence =>
|
||||
createEvidence(
|
||||
+2
-2
@@ -5,8 +5,8 @@ import {
|
||||
createCompletionLedgerArtifacts,
|
||||
parseCompletionManifest,
|
||||
type CompletionVerifierReport,
|
||||
} from "../../../src/domain/completionLedgerGeneration.js";
|
||||
import { parseEvidenceCompletionLedger } from "../../../src/domain/evidenceCompletionLedger.js";
|
||||
} from "./completionLedgerGeneration.js";
|
||||
import { parseEvidenceCompletionLedger } from "./evidenceCompletionLedger.js";
|
||||
|
||||
const digest = (digit: string): string => digit.repeat(64);
|
||||
const evidenceId = (digit: string): string => `ev_${digest(digit)}`;
|
||||
+226
-114
@@ -5,22 +5,16 @@ import { z } from "zod";
|
||||
|
||||
import { evidenceEnvelopeSchema } from "./evidence.js";
|
||||
import { evidenceBundleSchema } from "./evidenceBundle.js";
|
||||
import { err, ok, type Result } from "./result.js";
|
||||
|
||||
/** Schema version for the conformance package format. */
|
||||
export const CONFORMANCE_PACKAGE_VERSION = 1;
|
||||
|
||||
/** A stable, path-independent identifier for a conformance package. */
|
||||
export const conformancePackageIdSchema = z
|
||||
.string()
|
||||
.regex(/^cp_[a-f0-9]{64}$/u);
|
||||
const conformancePackageIdSchema = z.string().regex(/^cp_[a-f0-9]{64}$/u);
|
||||
|
||||
/** Identifier for a single scenario within a package. */
|
||||
export const scenarioIdSchema = z
|
||||
.string()
|
||||
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
|
||||
const scenarioIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
|
||||
|
||||
/** Deterministic manifest for a scenario fixture. */
|
||||
export const scenarioManifestSchema = z.strictObject({
|
||||
const scenarioManifestSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
@@ -32,8 +26,7 @@ export const scenarioManifestSchema = z.strictObject({
|
||||
expected_patterns: z.array(z.string()).default([]),
|
||||
});
|
||||
|
||||
/** Replay plan describing how a scenario is replayed deterministically. */
|
||||
export const replayPlanSchema = z.strictObject({
|
||||
const replayPlanSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Ordered steps to execute during replay. */
|
||||
steps: z
|
||||
@@ -51,8 +44,7 @@ export const replayPlanSchema = z.strictObject({
|
||||
environment: z.record(z.string(), z.string()).default({}),
|
||||
});
|
||||
|
||||
/** Shim plan for intercepting observable effects. */
|
||||
export const shimPlanSchema = z.strictObject({
|
||||
const shimPlanSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Shims to install, each intercepting a named effect. */
|
||||
shims: z
|
||||
@@ -64,23 +56,20 @@ export const shimPlanSchema = z.strictObject({
|
||||
policy: z.enum(["observe", "allow", "block", "emulate"]),
|
||||
}),
|
||||
)
|
||||
.min(0)
|
||||
.max(50),
|
||||
});
|
||||
|
||||
/** Expected evidence for a scenario, checked against the captured run. */
|
||||
export const expectedEvidenceSchema = z.strictObject({
|
||||
const expectedEvidenceSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Expected evidence envelopes. */
|
||||
envelopes: z.array(evidenceEnvelopeSchema).min(0).max(100),
|
||||
envelopes: z.array(evidenceEnvelopeSchema).max(100),
|
||||
/** Expected evidence bundle. */
|
||||
bundle: evidenceBundleSchema.nullable(),
|
||||
/** Required dimensions that must be present in the evidence. */
|
||||
required_dimensions: z.array(z.string().min(1)).default([]),
|
||||
});
|
||||
|
||||
/** Verifier contract describing how to validate conformance. */
|
||||
export const verifierContractSchema = z.strictObject({
|
||||
const verifierContractSchema = z.strictObject({
|
||||
scenario_id: scenarioIdSchema,
|
||||
/** Dimensions to verify. */
|
||||
dimensions: z
|
||||
@@ -97,122 +86,245 @@ export const verifierContractSchema = z.strictObject({
|
||||
timing_tolerance_ms: z.number().int().nonnegative().default(0),
|
||||
});
|
||||
|
||||
/** Top-level conformance package manifest. */
|
||||
export const conformancePackageSchema = z.strictObject({
|
||||
const conformancePackageContentsSchema = z.strictObject({
|
||||
schema_version: z.literal(CONFORMANCE_PACKAGE_VERSION),
|
||||
package_id: conformancePackageIdSchema,
|
||||
name: z.string().min(1),
|
||||
description: z.string().min(1),
|
||||
created_at: z.string().datetime(),
|
||||
/** Scenario manifests. */
|
||||
scenarios: z.array(scenarioManifestSchema).min(1).max(100),
|
||||
/** Replay plans keyed by scenario_id. */
|
||||
/** Exactly one replay plan for each scenario. */
|
||||
replay_plans: z.array(replayPlanSchema).min(1).max(100),
|
||||
/** Shim plans keyed by scenario_id. */
|
||||
/** At most one optional shim plan for each scenario. */
|
||||
shim_plans: z.array(shimPlanSchema).default([]),
|
||||
/** Expected evidence for each scenario. */
|
||||
/** Exactly one expected-evidence record for each scenario. */
|
||||
expected_evidence: z.array(expectedEvidenceSchema).min(1).max(100),
|
||||
/** Verifier contracts for each scenario. */
|
||||
/** Exactly one verifier contract for each scenario. */
|
||||
verifier_contracts: z.array(verifierContractSchema).min(1).max(100),
|
||||
});
|
||||
|
||||
export type ConformancePackage = z.infer<typeof conformancePackageSchema>;
|
||||
export type ScenarioManifest = z.infer<typeof scenarioManifestSchema>;
|
||||
export type ReplayPlan = z.infer<typeof replayPlanSchema>;
|
||||
export type ShimPlan = z.infer<typeof shimPlanSchema>;
|
||||
export type ExpectedEvidence = z.infer<typeof expectedEvidenceSchema>;
|
||||
export type VerifierContract = z.infer<typeof verifierContractSchema>;
|
||||
const conformancePackageRecordSchema = conformancePackageContentsSchema.extend({
|
||||
package_id: conformancePackageIdSchema,
|
||||
});
|
||||
|
||||
/** Error from validation or package operations. */
|
||||
const conformancePackageSchema =
|
||||
conformancePackageRecordSchema.brand<"ConformancePackage">();
|
||||
|
||||
type ConformancePackageContents = z.output<
|
||||
typeof conformancePackageContentsSchema
|
||||
>;
|
||||
type ConformancePackageRecord = z.output<typeof conformancePackageRecordSchema>;
|
||||
type DeepReadonly<T> = T extends readonly (infer Item)[]
|
||||
? readonly DeepReadonly<Item>[]
|
||||
: T extends object
|
||||
? { readonly [Key in keyof T]: DeepReadonly<T[Key]> }
|
||||
: T;
|
||||
|
||||
/** Source fields accepted by the conformance-package smart constructor. */
|
||||
export type ConformancePackageInput = DeepReadonly<
|
||||
z.input<typeof conformancePackageContentsSchema>
|
||||
>;
|
||||
|
||||
/** A shape- and relation-checked, content-addressed conformance package. */
|
||||
export type ConformancePackage = DeepReadonly<
|
||||
z.output<typeof conformancePackageSchema>
|
||||
>;
|
||||
|
||||
/** Verification policy for one conformance scenario. */
|
||||
export type VerifierContract = DeepReadonly<
|
||||
z.output<typeof verifierContractSchema>
|
||||
>;
|
||||
|
||||
/** Per-scenario package section participating in relation checks. */
|
||||
export type ConformancePackageSection =
|
||||
| "replay_plans"
|
||||
| "shim_plans"
|
||||
| "expected_evidence"
|
||||
| "verifier_contracts";
|
||||
|
||||
/** Precise reason an unknown package could not become a domain value. */
|
||||
export type ConformancePackageError =
|
||||
| { kind: "invalid_package"; message: string }
|
||||
| { kind: "scenario_not_found"; scenario_id: string }
|
||||
| { kind: "duplicate_scenario"; scenario_id: string };
|
||||
|
||||
/** Result type for package operations. */
|
||||
export type ConformancePackageResult<T> =
|
||||
| { ok: true; value: T }
|
||||
| { ok: false; error: ConformancePackageError };
|
||||
|
||||
/** Validate a conformance package and cross-check internal references. */
|
||||
export function validateConformancePackage(
|
||||
input: unknown,
|
||||
): ConformancePackageResult<ConformancePackage> {
|
||||
const parsed = conformancePackageSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "invalid_package",
|
||||
message: parsed.error.issues[0]?.message ?? "invalid package",
|
||||
},
|
||||
| {
|
||||
readonly kind: "invalid_package";
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "duplicate_scenario";
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "unknown_scenario_reference";
|
||||
readonly section: ConformancePackageSection;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "duplicate_scenario_reference";
|
||||
readonly section: ConformancePackageSection;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "missing_scenario_reference";
|
||||
readonly section: Exclude<ConformancePackageSection, "shim_plans">;
|
||||
readonly scenario_id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
| {
|
||||
readonly kind: "package_id_mismatch";
|
||||
readonly actual: string;
|
||||
readonly expected: string;
|
||||
readonly message: string;
|
||||
};
|
||||
|
||||
const pkg = parsed.data;
|
||||
type ScenarioReferenceSection =
|
||||
| {
|
||||
readonly name: Exclude<ConformancePackageSection, "shim_plans">;
|
||||
readonly entries: readonly { readonly scenario_id: string }[];
|
||||
readonly required: true;
|
||||
}
|
||||
| {
|
||||
readonly name: "shim_plans";
|
||||
readonly entries: readonly { readonly scenario_id: string }[];
|
||||
readonly required: false;
|
||||
};
|
||||
|
||||
// Check for duplicate scenario IDs
|
||||
const seen = new Set<string>();
|
||||
for (const s of pkg.scenarios) {
|
||||
if (seen.has(s.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: { kind: "duplicate_scenario", scenario_id: s.scenario_id },
|
||||
};
|
||||
seen.add(s.scenario_id);
|
||||
}
|
||||
/** Parse unknown input once into a package whose aggregate invariants hold. */
|
||||
export function parseConformancePackage(
|
||||
input: unknown,
|
||||
): Result<ConformancePackage, ConformancePackageError> {
|
||||
const parsed = conformancePackageSchema.safeParse(input);
|
||||
if (!parsed.success)
|
||||
return err({
|
||||
kind: "invalid_package",
|
||||
message: parsed.error.issues[0]?.message ?? "Invalid package",
|
||||
});
|
||||
|
||||
// Check that replay plans reference existing scenarios
|
||||
for (const rp of pkg.replay_plans) {
|
||||
if (!seen.has(rp.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: rp.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
const relationError = parseScenarioRelations(parsed.data);
|
||||
if (relationError !== undefined) return err(relationError);
|
||||
|
||||
// Check that expected evidence references existing scenarios
|
||||
for (const ee of pkg.expected_evidence) {
|
||||
if (!seen.has(ee.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: ee.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
const expectedPackageId = computePackageId(packageContents(parsed.data));
|
||||
if (parsed.data.package_id !== expectedPackageId)
|
||||
return err({
|
||||
kind: "package_id_mismatch",
|
||||
actual: parsed.data.package_id,
|
||||
expected: expectedPackageId,
|
||||
message: "Package identifier does not match its canonical contents",
|
||||
});
|
||||
|
||||
// Check that verifier contracts reference existing scenarios
|
||||
for (const vc of pkg.verifier_contracts) {
|
||||
if (!seen.has(vc.scenario_id))
|
||||
return {
|
||||
ok: false,
|
||||
error: {
|
||||
kind: "scenario_not_found",
|
||||
scenario_id: vc.scenario_id,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return { ok: true, value: pkg };
|
||||
return ok(parsed.data);
|
||||
}
|
||||
|
||||
/** Compute a deterministic package ID from the canonical JSON. */
|
||||
export function computePackageId(
|
||||
pkg: Omit<ConformancePackage, "package_id">,
|
||||
): string {
|
||||
const json = canonicalize(pkg);
|
||||
if (!json) throw new Error("failed to canonicalize package");
|
||||
return `cp_${createHash("sha256").update(json).digest("hex")}`;
|
||||
}
|
||||
|
||||
/** Create a conformance package with an auto-computed package_id. */
|
||||
/** Create a content-addressed package from source-owned typed fields. */
|
||||
export function createConformancePackage(
|
||||
pkg: Omit<ConformancePackage, "package_id">,
|
||||
input: ConformancePackageInput,
|
||||
): ConformancePackage {
|
||||
const package_id = computePackageId(pkg);
|
||||
return { package_id, ...pkg };
|
||||
const contents = conformancePackageContentsSchema.safeParse(input);
|
||||
if (!contents.success)
|
||||
throw new TypeError(
|
||||
`Invalid conformance package source: ${contents.error.issues[0]?.message ?? "unknown parse failure"}`,
|
||||
);
|
||||
|
||||
const parsed = parseConformancePackage({
|
||||
...contents.data,
|
||||
package_id: computePackageId(contents.data),
|
||||
});
|
||||
if (!parsed.ok)
|
||||
throw new TypeError(
|
||||
`Invalid conformance package source: ${parsed.error.message}`,
|
||||
);
|
||||
return parsed.value;
|
||||
}
|
||||
|
||||
const parseScenarioRelations = (
|
||||
pkg: ConformancePackageRecord,
|
||||
): ConformancePackageError | undefined => {
|
||||
const scenarioIds = new Set<string>();
|
||||
for (const scenario of pkg.scenarios) {
|
||||
if (scenarioIds.has(scenario.scenario_id))
|
||||
return {
|
||||
kind: "duplicate_scenario",
|
||||
scenario_id: scenario.scenario_id,
|
||||
message: `Duplicate scenario ${scenario.scenario_id}`,
|
||||
};
|
||||
scenarioIds.add(scenario.scenario_id);
|
||||
}
|
||||
|
||||
const sections: readonly ScenarioReferenceSection[] = [
|
||||
{ name: "replay_plans", entries: pkg.replay_plans, required: true },
|
||||
{ name: "shim_plans", entries: pkg.shim_plans, required: false },
|
||||
{
|
||||
name: "expected_evidence",
|
||||
entries: pkg.expected_evidence,
|
||||
required: true,
|
||||
},
|
||||
{
|
||||
name: "verifier_contracts",
|
||||
entries: pkg.verifier_contracts,
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
for (const section of sections) {
|
||||
const error = parseScenarioSection(scenarioIds, section);
|
||||
if (error !== undefined) return error;
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const parseScenarioSection = (
|
||||
scenarioIds: ReadonlySet<string>,
|
||||
section: ScenarioReferenceSection,
|
||||
): ConformancePackageError | undefined => {
|
||||
const referenced = new Set<string>();
|
||||
for (const entry of section.entries) {
|
||||
if (!scenarioIds.has(entry.scenario_id))
|
||||
return {
|
||||
kind: "unknown_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: entry.scenario_id,
|
||||
message: `${section.name} references unknown scenario ${entry.scenario_id}`,
|
||||
};
|
||||
if (referenced.has(entry.scenario_id))
|
||||
return {
|
||||
kind: "duplicate_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: entry.scenario_id,
|
||||
message: `${section.name} contains duplicate scenario ${entry.scenario_id}`,
|
||||
};
|
||||
referenced.add(entry.scenario_id);
|
||||
}
|
||||
|
||||
if (!section.required) return undefined;
|
||||
for (const scenarioId of scenarioIds) {
|
||||
if (!referenced.has(scenarioId))
|
||||
return {
|
||||
kind: "missing_scenario_reference",
|
||||
section: section.name,
|
||||
scenario_id: scenarioId,
|
||||
message: `${section.name} is missing scenario ${scenarioId}`,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
};
|
||||
|
||||
const packageContents = (
|
||||
pkg: ConformancePackageRecord,
|
||||
): ConformancePackageContents => ({
|
||||
schema_version: pkg.schema_version,
|
||||
name: pkg.name,
|
||||
description: pkg.description,
|
||||
created_at: pkg.created_at,
|
||||
scenarios: pkg.scenarios,
|
||||
replay_plans: pkg.replay_plans,
|
||||
shim_plans: pkg.shim_plans,
|
||||
expected_evidence: pkg.expected_evidence,
|
||||
verifier_contracts: pkg.verifier_contracts,
|
||||
});
|
||||
|
||||
const computePackageId = (contents: ConformancePackageContents): string => {
|
||||
const json = canonicalize(contents);
|
||||
if (json === undefined)
|
||||
throw new TypeError("Could not canonicalize parsed conformance package");
|
||||
return `cp_${createHash("sha256").update(json).digest("hex")}`;
|
||||
};
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import {
|
||||
conformancePackageSchema,
|
||||
type ConformancePackage,
|
||||
} from "./conformancePackage.js";
|
||||
import { parseConformancePackage } from "./conformancePackage.js";
|
||||
import {
|
||||
evaluatePackageTrustGates,
|
||||
trustGateResultSchema,
|
||||
@@ -74,12 +71,10 @@ export async function replayConformancePackage(
|
||||
runner: ScenarioRunner = defaultRunner,
|
||||
options: { truncated?: boolean } = {},
|
||||
): Promise<PackageReplayResult> {
|
||||
const parsed = conformancePackageSchema.safeParse(packageInput);
|
||||
if (!parsed.success)
|
||||
throw new TypeError(
|
||||
`invalid conformance package: ${parsed.error.issues[0]?.message ?? "unknown"}`,
|
||||
);
|
||||
const pkg: ConformancePackage = parsed.data;
|
||||
const parsed = parseConformancePackage(packageInput);
|
||||
if (!parsed.ok)
|
||||
throw new TypeError(`invalid conformance package: ${parsed.error.message}`);
|
||||
const pkg = parsed.value;
|
||||
|
||||
const scenarioResults: ScenarioReplayResult[] = [];
|
||||
let passed = 0;
|
||||
|
||||
@@ -389,7 +389,10 @@ export function evaluatePackageTrustGates(
|
||||
const expected = pkg.expected_evidence.find(
|
||||
(e) => e.scenario_id === contract.scenario_id,
|
||||
);
|
||||
if (!expected) continue;
|
||||
if (expected === undefined)
|
||||
throw new TypeError(
|
||||
`Parsed conformance package is missing expected evidence for ${contract.scenario_id}`,
|
||||
);
|
||||
const expectedEvidence = expected.envelopes[0] ?? {};
|
||||
const actual = actualEvidence[contract.scenario_id] ?? {};
|
||||
const result = evaluateTrustGate(
|
||||
|
||||
@@ -235,7 +235,7 @@ const coverageSchema = z.strictObject({
|
||||
pre_capture_activity: z.literal("unavailable"),
|
||||
});
|
||||
|
||||
const actionResultSchema = z.strictObject({
|
||||
const actionResultContextShape = {
|
||||
step_id: z.string().min(1).max(128),
|
||||
kind: z.enum([
|
||||
"click",
|
||||
@@ -246,10 +246,21 @@ const actionResultSchema = z.strictObject({
|
||||
]),
|
||||
window_index: windowIndexSchema.nullable(),
|
||||
target: z.string().max(256).nullable(),
|
||||
status: z.enum(["completed", "failed", "cancelled"]),
|
||||
elapsed_ms: z.number().int().min(0),
|
||||
error: z.string().nullable(),
|
||||
});
|
||||
};
|
||||
|
||||
const actionResultSchema = z.discriminatedUnion("status", [
|
||||
z.strictObject({
|
||||
...actionResultContextShape,
|
||||
status: z.literal("completed"),
|
||||
error: z.null(),
|
||||
}),
|
||||
z.strictObject({
|
||||
...actionResultContextShape,
|
||||
status: z.enum(["failed", "cancelled"]),
|
||||
error: z.string(),
|
||||
}),
|
||||
]);
|
||||
|
||||
/** Bounded result of a provider-owned Electron runtime experiment. */
|
||||
export const electronActiveObservationResultSchema = z.strictObject({
|
||||
|
||||
@@ -2,6 +2,8 @@ import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronBrowserWindowFinding,
|
||||
ElectronBrowserWindowPreload,
|
||||
ElectronContextBridgeApiKey,
|
||||
ElectronContextBridgeFinding,
|
||||
ElectronStaticValue,
|
||||
ElectronUtilityProcessFinding,
|
||||
@@ -57,8 +59,7 @@ const inspectBrowserWindow = (
|
||||
web_preferences_status: collected.status,
|
||||
web_preferences: collected.preferences,
|
||||
omitted_web_preferences: collected.omitted,
|
||||
preload_path: collected.preloadPath,
|
||||
preload_resolution_context: collected.preloadResolutionContext,
|
||||
...collected.preload,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
@@ -76,8 +77,7 @@ const collectWindowOptions = (
|
||||
): {
|
||||
readonly status: ElectronBrowserWindowFinding["web_preferences_status"];
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
|
||||
readonly preload: ElectronBrowserWindowPreload;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
@@ -85,8 +85,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: options === undefined ? "missing" : "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: options === undefined ? 0 : 1,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -95,8 +94,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: "missing",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: 0,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -104,8 +102,7 @@ const collectWindowOptions = (
|
||||
return {
|
||||
status: "dynamic",
|
||||
preferences: [],
|
||||
preloadPath: null,
|
||||
preloadResolutionContext: null,
|
||||
preload: { preload_path: null, preload_resolution_context: null },
|
||||
unknown: 1,
|
||||
omitted: 0,
|
||||
};
|
||||
@@ -118,16 +115,16 @@ const collectWebPreferences = (
|
||||
): {
|
||||
readonly status: "object-literal";
|
||||
readonly preferences: readonly ElectronWebPreference[];
|
||||
readonly preloadPath: string | null;
|
||||
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
|
||||
readonly preload: ElectronBrowserWindowPreload;
|
||||
readonly unknown: number;
|
||||
readonly omitted: number;
|
||||
} => {
|
||||
const preferences: ElectronWebPreference[] = [];
|
||||
let unknown = 0;
|
||||
let preloadPath: string | null = null;
|
||||
let preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"] =
|
||||
null;
|
||||
let preload: ElectronBrowserWindowPreload = {
|
||||
preload_path: null,
|
||||
preload_resolution_context: null,
|
||||
};
|
||||
for (const property of object.properties) {
|
||||
if (t.isSpreadElement(property)) {
|
||||
unknown += 1;
|
||||
@@ -155,10 +152,11 @@ const collectWebPreferences = (
|
||||
continue;
|
||||
}
|
||||
const path = name === "preload" ? staticPath(property.value) : undefined;
|
||||
if (path !== undefined) {
|
||||
preloadPath = path;
|
||||
preloadResolutionContext = staticPathResolutionContext(property.value);
|
||||
}
|
||||
if (path !== undefined)
|
||||
preload = {
|
||||
preload_path: path,
|
||||
preload_resolution_context: staticPathResolutionContext(property.value),
|
||||
};
|
||||
const value: ElectronStaticValue =
|
||||
path === undefined
|
||||
? electronStaticValue(source, property.value)
|
||||
@@ -170,8 +168,7 @@ const collectWebPreferences = (
|
||||
return {
|
||||
status: "object-literal",
|
||||
preferences: preferences.slice(0, MAX_WEB_PREFERENCES),
|
||||
preloadPath,
|
||||
preloadResolutionContext,
|
||||
preload,
|
||||
unknown,
|
||||
omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES),
|
||||
};
|
||||
@@ -201,14 +198,16 @@ const inspectContextBridge = (
|
||||
(worldId?.status === "dynamic" ? 1 : 0) +
|
||||
api.unknown;
|
||||
accountForStructure(context, unknown, api.omitted);
|
||||
const apiKey: ElectronContextBridgeApiKey =
|
||||
key.status === "dynamic"
|
||||
? { api_key: null, api_key_expression: key.expression }
|
||||
: typeof key.value === "string"
|
||||
? { api_key: key.value, api_key_expression: null }
|
||||
: { api_key: null, api_key_expression: null };
|
||||
const finding: ElectronContextBridgeFinding = {
|
||||
...apiKey,
|
||||
world: isolated ? "isolated" : "main",
|
||||
world_id: worldId,
|
||||
api_key:
|
||||
key.status === "literal" && typeof key.value === "string"
|
||||
? key.value
|
||||
: null,
|
||||
api_key_expression: key.status === "dynamic" ? key.expression : null,
|
||||
api_status: api.status,
|
||||
members: api.members,
|
||||
unknown_members: api.unknown,
|
||||
@@ -234,10 +233,6 @@ const inspectUtilityProcess = (
|
||||
const moduleNode = argumentNode(node.arguments[0]);
|
||||
const modulePath =
|
||||
moduleNode === undefined ? undefined : staticPath(moduleNode);
|
||||
const moduleResolutionContext =
|
||||
modulePath === undefined || moduleNode === undefined
|
||||
? null
|
||||
: staticPathResolutionContext(moduleNode);
|
||||
const options = argumentNode(node.arguments[2]);
|
||||
const serviceName =
|
||||
t.isObjectExpression(options) &&
|
||||
@@ -245,20 +240,27 @@ const inspectUtilityProcess = (
|
||||
? staticPath(objectProperty(options, "serviceName")?.value ?? options)
|
||||
: undefined;
|
||||
if (modulePath === undefined) context.accumulator.unknownFindings += 1;
|
||||
const moduleReference =
|
||||
modulePath === undefined || moduleNode === undefined
|
||||
? {
|
||||
module_path: null,
|
||||
module_resolution_context: null,
|
||||
module_expression: boundedExpression(context.source, moduleNode),
|
||||
}
|
||||
: {
|
||||
module_path: modulePath,
|
||||
module_resolution_context: staticPathResolutionContext(moduleNode),
|
||||
module_expression: null,
|
||||
};
|
||||
const finding: ElectronUtilityProcessFinding = {
|
||||
module_path: modulePath ?? null,
|
||||
module_resolution_context: moduleResolutionContext,
|
||||
module_expression:
|
||||
modulePath === undefined
|
||||
? boundedExpression(context.source, moduleNode)
|
||||
: null,
|
||||
...moduleReference,
|
||||
service_name: serviceName ?? null,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.utilityProcesses,
|
||||
key: `electron-utility\0${modulePath ?? finding.module_expression ?? "[missing]"}`,
|
||||
key: `electron-utility\0${finding.module_path ?? finding.module_expression}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as t from "@babel/types";
|
||||
|
||||
import type {
|
||||
ElectronIpcDescriptor,
|
||||
ElectronIpcFinding,
|
||||
ElectronSenderValidationFinding,
|
||||
} from "./electronStaticAnalysisTypes.js";
|
||||
@@ -18,12 +19,6 @@ import {
|
||||
} from "./javascriptStaticAnalysisHelpers.js";
|
||||
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.js";
|
||||
|
||||
interface IpcDescriptor {
|
||||
readonly side: ElectronIpcFinding["side"];
|
||||
readonly operation: ElectronIpcFinding["operation"];
|
||||
readonly mode: ElectronIpcFinding["mode"];
|
||||
}
|
||||
|
||||
/** Inspect Electron IPC operations and validation candidates. */
|
||||
export const inspectElectronIpcNode = (
|
||||
node: t.Node,
|
||||
@@ -49,30 +44,56 @@ const inspectIpcCall = (
|
||||
channelValue.status === "literal" && typeof channelValue.value === "string"
|
||||
? channelValue.value
|
||||
: null;
|
||||
const channelExpression =
|
||||
const channelReference =
|
||||
channel === null
|
||||
? channelValue.status === "dynamic"
|
||||
? channelValue.expression
|
||||
: boundedExpression(context.source, channelNode)
|
||||
: null;
|
||||
const hasHandler =
|
||||
descriptor.mode === "listen" || descriptor.mode === "handle";
|
||||
const handlerNode = hasHandler ? argumentNode(node.arguments[1]) : undefined;
|
||||
? {
|
||||
channel: null,
|
||||
channel_expression:
|
||||
channelValue.status === "dynamic"
|
||||
? channelValue.expression
|
||||
: boundedExpression(context.source, channelNode),
|
||||
}
|
||||
: { channel, channel_expression: null };
|
||||
const handlerNode =
|
||||
descriptor.mode === "listen" || descriptor.mode === "handle"
|
||||
? argumentNode(node.arguments[1])
|
||||
: undefined;
|
||||
const findingState =
|
||||
descriptor.mode === "send"
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: null,
|
||||
handler_location: null,
|
||||
}
|
||||
: descriptor.mode === "invoke"
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: null,
|
||||
handler_location: null,
|
||||
}
|
||||
: handlerNode === undefined
|
||||
? {
|
||||
...descriptor,
|
||||
handler_kind: "missing" as const,
|
||||
handler_location: null,
|
||||
}
|
||||
: {
|
||||
...descriptor,
|
||||
handler_kind: handlerKind(handlerNode),
|
||||
handler_location: range(handlerNode),
|
||||
};
|
||||
if (channel === null) context.accumulator.unknownFindings += 1;
|
||||
if (hasHandler && handlerNode === undefined)
|
||||
if (findingState.handler_kind === "missing")
|
||||
context.accumulator.unknownFindings += 1;
|
||||
const finding: ElectronIpcFinding = {
|
||||
...descriptor,
|
||||
channel,
|
||||
channel_expression: channelExpression,
|
||||
handler_kind: hasHandler ? handlerKind(handlerNode) : null,
|
||||
handler_location: handlerNode === undefined ? null : range(handlerNode),
|
||||
...findingState,
|
||||
...channelReference,
|
||||
module_key: null,
|
||||
location: range(node),
|
||||
};
|
||||
addLocatedFinding(context, {
|
||||
collection: context.accumulator.ipc,
|
||||
key: `electron-ipc\0${descriptor.side}\0${descriptor.operation}\0${channel ?? channelExpression ?? "[missing]"}`,
|
||||
key: `electron-ipc\0${descriptor.side}\0${descriptor.operation}\0${channelReference.channel ?? channelReference.channel_expression}`,
|
||||
node,
|
||||
value: finding,
|
||||
});
|
||||
@@ -143,7 +164,7 @@ const addValidation = (
|
||||
});
|
||||
};
|
||||
|
||||
const ipcDescriptor = (name: string): IpcDescriptor | undefined => {
|
||||
const ipcDescriptor = (name: string): ElectronIpcDescriptor | undefined => {
|
||||
const renderer = suffixOperation(name, "ipcRenderer");
|
||||
if (renderer !== undefined) {
|
||||
switch (renderer) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user