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:
morluto
2026-08-10 14:57:44 +08:00
committed by GitHub
co-authored by Devin <158243242+devin-ai-integration[bot]@users.noreply.github.com>
parent 344b9b6dff
commit e91c8c39c2
302 changed files with 6822 additions and 5781 deletions
+22 -2
View File
@@ -18,7 +18,27 @@
}, },
"overrides": [ "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": { "rules": {
"max-lines": [ "max-lines": [
"error", "error",
@@ -31,7 +51,7 @@
} }
}, },
{ {
"files": ["src/domain/**/*.test.ts"], "files": ["src/domain/**/*.{fixture,test}.ts"],
"rules": { "rules": {
"no-restricted-imports": [ "no-restricted-imports": [
"error", "error",
+1 -1
View File
@@ -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/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. - `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. - `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-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.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. - `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.
+2 -2
View File
@@ -680,10 +680,10 @@
"mcp_resource_templates": 11 "mcp_resource_templates": 11
}, },
"digests": { "digests": {
"tools_sha256": "b0e8b9c894ef347b6680a3a5bfdb4cba5c10e9129eeaa43a5ea22ce4d398d417", "tools_sha256": "1a4533fef9cbe075fdca76b19a138924bd69d93a6413cdb767b2a9240a46fd04",
"prompts_sha256": "3886a3bf55a448def79e3eb429e6a56eb2ba075423c5cb1e5747642b389ef8fe", "prompts_sha256": "3886a3bf55a448def79e3eb429e6a56eb2ba075423c5cb1e5747642b389ef8fe",
"resources_sha256": "e0e872276ebf6f88e916ef24930a99eed27ce4c93e494e60820e9bd8cc8497c3", "resources_sha256": "e0e872276ebf6f88e916ef24930a99eed27ce4c93e494e60820e9bd8cc8497c3",
"combined_sha256": "bab5657d9525ec4f798d0a9ef6001412d9c11f77fb0ddc925c7076fd10921dc9", "combined_sha256": "8bd40516d78875cb75ba1c4a8786286311036742ad660914d7327c2941b2f73a",
"providers_sha256": "7446b51788734ebf6f4f702e3a5a8c9f0b61967490c245f30bd37b2060827e6b" "providers_sha256": "7446b51788734ebf6f4f702e3a5a8c9f0b61967490c245f30bd37b2060827e6b"
} }
} }
-73
View File
@@ -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
View File
@@ -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 Boundary tests cross one production boundary. Only acceptance tests assemble
the complete runtime or invoke the compiled product surface. 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 `tests/process-global/**` is reserved for cases with a demonstrated dependency
on process-global state. Those tests run without file parallelism. Reusable, on process-global state. Those tests run without file parallelism. Reusable,
test-scoped fixtures live under `tests/support/**`; immutable source artifacts 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 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 project at a time. Boundary fixtures own real subprocesses, and this local cap
keeps aggregate memory predictable; CI retains the existing two-worker budget. 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 `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 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 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 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 minutes across three warm-build runs on the benchmark host. Keep Vitest caches
cold unless separately identified. The final cutover also requires three cold unless separately identified. A PR that touches packaging or real-system
consecutive deterministic passes without retries, `npm run verify:package`, and behavior also requires `npm run verify:package` and the applicable
the applicable real-system lanes. `verify:*` lanes.
@@ -1,6 +1,6 @@
{ {
"schema_version": 1, "schema_version": 1,
"manifest_id": "ecm_c44391ed8e365e21871664422aa38fa6c12598006cde731d65a9d9e271b0fa5f", "manifest_id": "ecm_5add7389cf00e86bfec005df9e0e0cf8d7aceb2f3ec3e5f6b74edb5f880bd9a7",
"verifier": { "verifier": {
"id": "rea-managed-conformance", "id": "rea-managed-conformance",
"version": "1" "version": "1"
@@ -14,7 +14,7 @@
"skill_digests": [ "skill_digests": [
{ {
"skill_id": "reverse-engineer-anything", "skill_id": "reverse-engineer-anything",
"sha256": "97a5bc5d29f162fe171ddbb8f4f5ba9fcba34ad336d4cdcae0c564223aa4cfe8" "sha256": "2cca31c9550fe32c24adcb8134edb4b077aa772fb0f0f1057c99964cac6d9a8f"
} }
], ],
"claims": [ "claims": [
+2
View File
@@ -4,6 +4,8 @@ const valuesAt = (node, path) => {
if (typeof node !== "object" || node === null) return []; if (typeof node !== "object" || node === null) return [];
if ("anyOf" in node && Array.isArray(node.anyOf)) if ("anyOf" in node && Array.isArray(node.anyOf))
return node.anyOf.flatMap((alternative) => valuesAt(alternative, path)); 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) if (path.length === 0)
return "const" in node && return "const" in node &&
(typeof node.const === "number" || typeof node.const === "string") (typeof node.const === "number" || typeof node.const === "string")
+1 -1
View File
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, an
metadata: metadata:
version: "23" version: "23"
tool_count: 116 tool_count: 116
catalog_digest: "bab5657d9525ec4f798d0a9ef6001412d9c11f77fb0ddc925c7076fd10921dc9" catalog_digest: "8bd40516d78875cb75ba1c4a8786286311036742ad660914d7327c2941b2f73a"
--- ---
# REA # REA
@@ -3,16 +3,16 @@ import { describe, expect, it } from "vitest";
import { import {
getNavigationContext, getNavigationContext,
inspectAddressContext, inspectAddressContext,
} from "../../../src/application/AnalysisContextQueries.js"; } from "./AnalysisContextQueries.js";
import { import {
createAnalysisExecution, createAnalysisExecution,
type AnalysisOperationPort, type AnalysisOperationPort,
} from "../../../src/application/AnalysisProvider.js"; } from "./AnalysisProvider.js";
import { import {
AnalysisCancelledError, AnalysisCancelledError,
AnalysisProtocolError, AnalysisProtocolError,
} from "../../../src/domain/errors.js"; } from "../domain/errors.js";
import { err, ok } from "../../../src/domain/result.js"; import { err, ok } from "../domain/result.js";
const provider = { id: "fixture", name: "Fixture", version: "1" }; 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();
});
});
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import { import {
resolveArtifactIntegrityPolicy, resolveArtifactIntegrityPolicy,
resolveNativeMountPolicy, resolveNativeMountPolicy,
} from "../../../src/application/ArtifactInventory/policy.js"; } from "./ArtifactInventory/policy.js";
describe("artifact inventory policy resolution", () => { describe("artifact inventory policy resolution", () => {
it("admits native mounting only when caller and operator both allow it", () => { it("admits native mounting only when caller and operator both allow it", () => {
+2 -20
View File
@@ -15,12 +15,8 @@ import type { JsonValue } from "../domain/jsonValue.js";
import type { import type {
AnalysisClient, AnalysisClient,
AnalysisExecution, AnalysisExecution,
AnalysisClientFactory,
ExecutionOptions, ExecutionOptions,
AnalysisProfileResolution,
AnalysisProfileResolutionOptions,
AnalysisOperationPort, AnalysisOperationPort,
AnalysisProvider,
ProviderIdentity, ProviderIdentity,
} from "./AnalysisProvider.js"; } from "./AnalysisProvider.js";
import type { AnalysisOperation } from "./AnalysisProvider.js"; import type { AnalysisOperation } from "./AnalysisProvider.js";
@@ -80,23 +76,9 @@ export class BinarySession
>(); >();
readonly #availabilityListeners = new Set<() => void | Promise<void>>(); readonly #availabilityListeners = new Set<() => void | Promise<void>>();
constructor( constructor(providerRouter: SessionProviderRouter) {
readonly provider:
| AnalysisProvider
| AnalysisClientFactory
| SessionProviderRouter,
options: {
readonly resolveAnalysisProfile?: (
target: BinaryTarget,
options?: AnalysisProfileResolutionOptions,
) => Promise<Result<AnalysisProfileResolution, AnalysisError>>;
} = {},
) {
super(); super();
this.#providerRouter = this.#providerRouter = providerRouter;
provider instanceof SessionProviderRouter
? provider
: SessionProviderRouter.legacy(provider, options);
} }
/** Identify the provider producing evidence for this session. */ /** Identify the provider producing evidence for this session. */
+1 -45
View File
@@ -1,33 +1,7 @@
import type { import type { AnalysisProvider } from "./AnalysisProvider.js";
AnalysisClientFactory,
AnalysisProfileResolution,
AnalysisProfileResolutionOptions,
AnalysisProvider,
} from "./AnalysisProvider.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js"; import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import { BinarySession } from "./BinarySession.js"; import { BinarySession } from "./BinarySession.js";
import { SessionProviderRouter } from "./SessionProviderRouter.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 * Compose one provider-neutral session from deep-provider selection and
@@ -42,21 +16,3 @@ export const composeBinarySession = (
? registry ? registry
: SessionProviderRouter.selectable(registry, auxiliaryProviders), : 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,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js"; import { buildCapabilityInventory } from "./CapabilityInventory.js";
const enabledPolicy: Parameters<typeof buildCapabilityInventory>[1] = { const enabledPolicy: Parameters<typeof buildCapabilityInventory>[1] = {
processCaptureEnabled: true, processCaptureEnabled: true,
+53 -17
View File
@@ -8,14 +8,37 @@ import { PRODUCT_IDENTITY } from "../identity.js";
import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js"; import { MCP_STARTUP_POLICY } from "../mcpStartupPolicy.js";
import { supportedClients } from "./SupportedClients.js"; import { supportedClients } from "./SupportedClients.js";
export interface ClientRegistrationStatus { interface ClientRegistrationStatusBase {
readonly client: string; readonly client: string;
readonly config_path: 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 objectSchema = z.record(z.string(), z.unknown());
const registrationSchema = z const registrationSchema = z
.object({ .object({
@@ -44,13 +67,18 @@ export const readClientRegistrationStatuses = async (
); );
const raw = servers[PRODUCT_IDENTITY.mcpServerKey]; const raw = servers[PRODUCT_IDENTITY.mcpServerKey];
if (raw === undefined) { if (raw === undefined) {
statuses.push(status(client.name, client.configPath, [], "missing")); statuses.push(
unavailableStatus(client.name, client.configPath, "missing"),
);
continue; continue;
} }
const registration = registrationSchema.parse(raw); const registration = registrationSchema.parse(raw);
const command = [registration.command, ...registration.args]; const command: RegistrationCommand = [
registration.command,
...registration.args,
];
statuses.push( statuses.push(
status( configuredStatus(
client.name, client.name,
client.configPath, client.configPath,
command, command,
@@ -61,10 +89,9 @@ export const readClientRegistrationStatuses = async (
); );
} catch (cause: unknown) { } catch (cause: unknown) {
statuses.push( statuses.push(
status( unavailableStatus(
client.name, client.name,
client.configPath, client.configPath,
[],
isMissing(cause) ? "missing" : "invalid", 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, client: string,
configPath: string, configPath: string,
command: readonly string[], command: RegistrationCommand,
state: ClientRegistrationStatus["state"], 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 => ({ ): ClientRegistrationStatus => ({
client, client,
config_path: configPath, config_path: configPath,
command, command: [],
state, state,
remediation: remediation,
state === "aligned"
? null
: "Run rea setup to refresh this registration, then restart the client.",
}); });
const exists = async (path: string | undefined): Promise<boolean> => { const exists = async (path: string | undefined): Promise<boolean> => {
+7 -5
View File
@@ -19,6 +19,7 @@ import { PRODUCT_IDENTITY, SDK_IDENTITY } from "../identity.js";
import { import {
readClientRegistrationStatuses, readClientRegistrationStatuses,
type ClientRegistrationStatus, type ClientRegistrationStatus,
type UnhealthyClientRegistrationStatus,
} from "./ClientRegistrationStatus.js"; } from "./ClientRegistrationStatus.js";
import { import {
inspectRuntimeExecutables, inspectRuntimeExecutables,
@@ -214,7 +215,10 @@ const collectDoctorIdentity = async (
checks: [ checks: [
...(skillAligned ? [] : [skillIdentityCheck(installedSkillIdentity)]), ...(skillAligned ? [] : [skillIdentityCheck(installedSkillIdentity)]),
...registrations ...registrations
.filter(({ state }) => state !== "aligned") .filter(
(registration): registration is UnhealthyClientRegistrationStatus =>
registration.state !== "aligned",
)
.map(registrationCheck), .map(registrationCheck),
], ],
value: { value: {
@@ -283,15 +287,13 @@ const skillIdentityCheck = (
}); });
const registrationCheck = ( const registrationCheck = (
registration: ClientRegistrationStatus, registration: UnhealthyClientRegistrationStatus,
): DoctorCheck => ({ ): DoctorCheck => ({
name: `registration:${registration.client}`, name: `registration:${registration.client}`,
ok: false, ok: false,
classification: "config_drift", classification: "config_drift",
detail: registration.config_path, detail: registration.config_path,
remediation: remediation: registration.remediation,
registration.remediation ??
"Run rea setup, then restart the affected client.",
}); });
const installationState = ( const installationState = (
+8 -4
View File
@@ -1,4 +1,7 @@
import type { ClientRegistrationStatus } from "./ClientRegistrationStatus.js"; import type {
ClientRegistrationStatus,
UnhealthyClientRegistrationStatus,
} from "./ClientRegistrationStatus.js";
import type { import type {
DoctorCheck, DoctorCheck,
DoctorProviderInspection, DoctorProviderInspection,
@@ -174,13 +177,14 @@ const selectedRegistrationCheck = (
} }
: registrationCheck(status); : registrationCheck(status);
const registrationCheck = (status: ClientRegistrationStatus): DoctorCheck => ({ const registrationCheck = (
status: UnhealthyClientRegistrationStatus,
): DoctorCheck => ({
name: `registration:${status.client}`, name: `registration:${status.client}`,
ok: false, ok: false,
classification: "config_drift", classification: "config_drift",
detail: status.config_path, detail: status.config_path,
remediation: remediation: status.remediation,
status.remediation ?? "Run rea setup, then restart the affected client.",
}); });
const selectedSkillCheck = ( const selectedSkillCheck = (
+10 -9
View File
@@ -151,13 +151,15 @@ export const summarizeElectronBoundaries = (
}, },
sender_validation_observations: validations.length, sender_validation_observations: validations.length,
utility_processes: utilities.length, utility_processes: utilities.length,
resolved_utility_entrypoints: utilities.filter(({ file, finding }) => resolved_utility_entrypoints: utilities.filter(
resolvesToFile({ ({ file, finding }) =>
file, finding.module_path !== null &&
specifier: finding.module_path, resolvesToFile({
context: finding.module_resolution_context ?? "module-specifier", file,
files, specifier: finding.module_path,
}), context: finding.module_resolution_context,
files,
}),
).length, ).length,
native_addon_bindings: nativeBindings.length, native_addon_bindings: nativeBindings.length,
resolved_native_addon_bindings: nativeBindings.filter(({ file, finding }) => resolved_native_addon_bindings: nativeBindings.filter(({ file, finding }) =>
@@ -195,14 +197,13 @@ const isMainHandler = ({ finding }: ElectronIpcRecord): boolean =>
interface ResolveToFileInput { interface ResolveToFileInput {
readonly file: JavaScriptArtifactFile; readonly file: JavaScriptArtifactFile;
readonly specifier: string | null; readonly specifier: string;
readonly context: "module-specifier" | "filesystem-expression"; readonly context: "module-specifier" | "filesystem-expression";
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>; readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly kind?: JavaScriptArtifactFile["kind"]; readonly kind?: JavaScriptArtifactFile["kind"];
} }
const resolvesToFile = (input: ResolveToFileInput): boolean => { const resolvesToFile = (input: ResolveToFileInput): boolean => {
if (input.specifier === null) return false;
const resolved = resolveArtifactPathByContext({ const resolved = resolveArtifactPathByContext({
declaredPath: input.specifier, declaredPath: input.specifier,
sourcePath: input.file.path, sourcePath: input.file.path,
+1 -1
View File
@@ -162,7 +162,7 @@ const addHandlerNode = (input: IpcHandlerInput): ApplicationNode => {
identity: artifactLocalIdentity( identity: artifactLocalIdentity(
file.sha256, file.sha256,
"electron-ipc-handler", "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: [ observations: [
{ {
@@ -110,12 +110,15 @@ const addWindowPreload = (
input: FindingInput<ElectronBrowserWindowFinding>, input: FindingInput<ElectronBrowserWindowFinding>,
window: ApplicationNode, window: ApplicationNode,
): void => { ): void => {
const declared = input.value.preload_path; if (input.value.preload_path === null) return;
if (declared === null) return; const {
preload_path: declared,
preload_resolution_context: resolutionContext,
} = input.value;
const resolution = resolveArtifactPathByContext({ const resolution = resolveArtifactPathByContext({
declaredPath: declared, declaredPath: declared,
sourcePath: input.file.path, sourcePath: input.file.path,
context: input.value.preload_resolution_context ?? "module-specifier", context: resolutionContext,
files: input.context.filesByPath, files: input.context.filesByPath,
}); });
const role = createElectronRoleNode(input.context, { const role = createElectronRoleNode(input.context, {
@@ -210,7 +213,7 @@ const addUtilityProcess = (
identity: artifactLocalIdentity( identity: artifactLocalIdentity(
file.sha256, file.sha256,
"electron-utility-process", "electron-utility-process",
`${value.module_path ?? value.module_expression ?? "[missing]"}:${electronRangeKey(value.location)}`, `${value.module_path ?? value.module_expression}:${electronRangeKey(value.location)}`,
), ),
observations: [ observations: [
{ {
@@ -248,7 +251,7 @@ const addUtilityProcess = (
const resolution = resolveArtifactPathByContext({ const resolution = resolveArtifactPathByContext({
declaredPath: value.module_path, declaredPath: value.module_path,
sourcePath: file.path, sourcePath: file.path,
context: value.module_resolution_context ?? "module-specifier", context: value.module_resolution_context,
files: context.filesByPath, files: context.filesByPath,
}); });
const resolved = resolution.resolved_path; const resolved = resolution.resolved_path;
@@ -1,19 +1,19 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { EvidenceLedger } from "../../../src/application/EvidenceLedger.js"; import { EvidenceLedger } from "./EvidenceLedger.js";
import { createEvidence } from "../../../src/domain/evidence.js"; import { createEvidence } from "../domain/evidence.js";
import { import {
createEvidenceBundle, createEvidenceBundle,
parseEvidenceBundle, parseEvidenceBundle,
serializeEvidenceBundle, serializeEvidenceBundle,
} from "../../../src/domain/evidenceBundle.js"; } from "../domain/evidenceBundle.js";
import { import {
createResidualUnknown, createResidualUnknown,
recordUnknownInputSchema, recordUnknownInputSchema,
updateUnknownInputSchema, updateUnknownInputSchema,
type RecordUnknownInput, type RecordUnknownInput,
type ResidualUnknown, type ResidualUnknown,
} from "../../../src/domain/residualUnknown.js"; } from "../domain/residualUnknown.js";
const provider = { id: "fixture", name: "Fixture", version: "1" }; const provider = { id: "fixture", name: "Fixture", version: "1" };
const ledger = (): EvidenceLedger => const ledger = (): EvidenceLedger =>
+194
View File
@@ -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: [] });
});
});
+19 -12
View File
@@ -277,7 +277,7 @@ const invalidPackage = (
const unavailablePackage = ( const unavailablePackage = (
file: JavaScriptArtifactFile, file: JavaScriptArtifactFile,
limitation: string, limitation: string,
): JavaScriptPackageObservation => ({ ): JavaScriptPackageObservation & { readonly status: "unavailable" } => ({
path: file.path, path: file.path,
sha256: file.sha256, sha256: file.sha256,
status: "unavailable", status: "unavailable",
@@ -394,17 +394,24 @@ const collectSourceMapOriginals = (
} }
} }
const omitted = total - sources.length; const omitted = total - sources.length;
return { return omitted === 0
path: file.path, ? {
sha256: file.sha256, path: file.path,
status: omitted === 0 ? "included" : "truncated", sha256: file.sha256,
sources, status: "included",
omitted_sources: omitted, sources,
limitation: omitted_sources: 0,
omitted === 0 limitation: null,
? null }
: "Original-source inventory reached the approved source-map limit.", : {
}; path: file.path,
sha256: file.sha256,
status: "truncated",
sources,
omitted_sources: omitted,
limitation:
"Original-source inventory reached the approved source-map limit.",
};
}; };
const unavailableSourceMap = ( const unavailableSourceMap = (
@@ -8,18 +8,35 @@ import type {
} from "../domain/javascriptSemanticIr.js"; } from "../domain/javascriptSemanticIr.js";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js"; import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
/** Parsed package metadata used only for static entrypoint discovery. */ interface JavaScriptStructuredObservation {
export interface JavaScriptPackageObservation {
readonly path: string; readonly path: string;
readonly sha256: string; readonly sha256: string;
readonly status: "included" | "invalid" | "unavailable"; }
interface JavaScriptPackageValues {
readonly name: string | null; readonly name: string | null;
readonly version: string | null; readonly version: string | null;
readonly main: string | null; readonly main: string | null;
readonly renderer: 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. */ /** One HTML script source observed without building or executing a DOM. */
export interface JavaScriptHtmlScriptObservation { export interface JavaScriptHtmlScriptObservation {
readonly html_path: string; readonly html_path: string;
@@ -36,24 +53,50 @@ export interface JavaScriptSourceMapOriginal {
} }
/** Bounded local source-map parse result. */ /** Bounded local source-map parse result. */
export interface JavaScriptSourceMapObservation { export type JavaScriptSourceMapObservation = JavaScriptStructuredObservation &
readonly path: string; (
readonly sha256: string; | {
readonly status: "included" | "truncated" | "invalid" | "not-approved"; readonly status: "included";
readonly sources: readonly JavaScriptSourceMapOriginal[]; readonly sources: readonly JavaScriptSourceMapOriginal[];
readonly omitted_sources: number | null; readonly omitted_sources: 0;
readonly limitation: string | null; 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. */ /** Bounded parse status for one inventoried JSON module. */
export interface JavaScriptJsonModuleObservation { export type JavaScriptJsonModuleObservation = JavaScriptStructuredObservation &
readonly path: string; (
readonly sha256: string; | {
readonly status: "included" | "invalid" | "unavailable"; readonly status: "included";
readonly top_level_keys: readonly string[]; readonly top_level_keys: readonly string[];
readonly omitted_top_level_keys: number | null; readonly omitted_top_level_keys: number;
readonly limitation: string | null; 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. */ /** One relevant file plus optional AST-only JavaScript facts. */
export interface AnalyzedJavaScriptArtifactFile { export interface AnalyzedJavaScriptArtifactFile {
@@ -20,9 +20,10 @@ import {
addJavaScriptSourceModules, addJavaScriptSourceModules,
} from "./JavaScriptModuleRelationships.js"; } from "./JavaScriptModuleRelationships.js";
import { import {
completeReconstructionCoverage, completeApplicationCoverage,
partialReconstructionCoverage, partialApplicationCoverage,
} from "./JavaScriptArtifactGraphEvidence.js"; truncatedApplicationCoverage,
} from "../domain/javascriptApplicationEvidenceSchemas.js";
import { import {
addJavaScriptArtifactContainers, addJavaScriptArtifactContainers,
addJavaScriptArtifactFiles, addJavaScriptArtifactFiles,
@@ -108,24 +109,21 @@ const graphCoverage = (context: JavaScriptArtifactGraphContext) => {
malformedStructuredData || malformedStructuredData ||
partialJavaScript; partialJavaScript;
if (context.analysis.truncated_scopes > 0) if (context.analysis.truncated_scopes > 0)
return partialReconstructionCoverage( return truncatedApplicationCoverage(
reconstructionLimits(context.input), reconstructionLimits(context.input),
truncationOmittedCount(context), truncationOmittedCount(context),
true,
); );
if (exactLimitOmissions > 0) if (exactLimitOmissions > 0)
return partialReconstructionCoverage( return truncatedApplicationCoverage(
reconstructionLimits(context.input), reconstructionLimits(context.input),
exactLimitOmissions, exactLimitOmissions,
true,
); );
if (unknownGap) if (unknownGap)
return partialReconstructionCoverage( return partialApplicationCoverage(
reconstructionLimits(context.input), reconstructionLimits(context.input),
null, null,
false,
); );
return completeReconstructionCoverage(reconstructionLimits(context.input)); return completeApplicationCoverage(reconstructionLimits(context.input));
}; };
const truncationOmittedCount = ( const truncationOmittedCount = (
@@ -1,5 +1,10 @@
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js"; 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 { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js"; import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
@@ -12,8 +17,6 @@ import { JavaScriptArtifactGraphAccumulator } from "./JavaScriptArtifactGraphAcc
import { import {
artifactObservationEvidence, artifactObservationEvidence,
astObservationEvidence, astObservationEvidence,
completeReconstructionCoverage,
partialReconstructionCoverage,
staticInferenceEvidence, staticInferenceEvidence,
unavailableAstEvidence, unavailableAstEvidence,
} from "./JavaScriptArtifactGraphEvidence.js"; } from "./JavaScriptArtifactGraphEvidence.js";
@@ -117,7 +120,7 @@ export const addArtifactContainsEdge = (
: input.file.sha256, : input.file.sha256,
path: input.file.path, path: input.file.path,
operation: input.operation, operation: input.operation,
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}); });
}; };
@@ -186,7 +189,7 @@ export const addUnavailableStaticParseScope = (
sha256: input.file.sha256, sha256: input.file.sha256,
path: input.file.path, path: input.file.path,
operation: input.operation, operation: input.operation,
coverage: partialReconstructionCoverage([], null, false), coverage: partialApplicationCoverage([], null),
limitation: input.limitation, limitation: input.limitation,
}), }),
}, },
@@ -201,7 +204,7 @@ export const addUnavailableStaticParseScope = (
sha256: input.file.sha256, sha256: input.file.sha256,
path: input.file.path, path: input.file.path,
operation: "associate-unavailable-parse-scope", operation: "associate-unavailable-parse-scope",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}); });
}; };
@@ -214,13 +217,10 @@ export const javascriptAnalysisCoverage = (
input: JavaScriptArtifactReconstructionInput, input: JavaScriptArtifactReconstructionInput,
): JavaScriptArtifactGraphCoverage => ): JavaScriptArtifactGraphCoverage =>
analysis.parse_status === "complete" analysis.parse_status === "complete"
? completeReconstructionCoverage(javaScriptAnalysisLimits(input)) ? completeApplicationCoverage(javaScriptAnalysisLimits(input))
: { : analysis.parse_status === "truncated"
status: "partial", ? truncatedApplicationCoverage(javaScriptAnalysisLimits(input), null)
truncated: analysis.parse_status === "truncated", : partialApplicationCoverage(javaScriptAnalysisLimits(input), null);
omitted_count: null,
limits: javaScriptAnalysisLimits(input),
};
/** Stable identity for a fact scoped to one exact artifact. */ /** Stable identity for a fact scoped to one exact artifact. */
export const artifactLocalIdentity = ( export const artifactLocalIdentity = (
@@ -274,7 +274,7 @@ export const createElectronRoleNode = (
sha256: input.anchor.sha256, sha256: input.anchor.sha256,
path: input.anchor.path, path: input.anchor.path,
operation: "discover-electron-entrypoint", operation: "discover-electron-entrypoint",
coverage: input.coverage ?? completeReconstructionCoverage(), coverage: input.coverage ?? completeApplicationCoverage(),
limitations: input.resolution.limitations, limitations: input.resolution.limitations,
...(input.range === undefined ? {} : { range: input.range }), ...(input.range === undefined ? {} : { range: input.range }),
}), }),
@@ -305,7 +305,7 @@ export const linkElectronRoleToAsset = (
sha256: input.anchor.sha256, sha256: input.anchor.sha256,
path: input.anchor.path, path: input.anchor.path,
operation: "resolve-electron-entrypoint", operation: "resolve-electron-entrypoint",
coverage: input.coverage ?? completeReconstructionCoverage(), coverage: input.coverage ?? completeApplicationCoverage(),
limitations: input.resolution.limitations, limitations: input.resolution.limitations,
...(input.range === undefined ? {} : { range: input.range }), ...(input.range === undefined ? {} : { range: input.range }),
}), }),
@@ -5,11 +5,11 @@ import {
linkElectronRoleToAsset, linkElectronRoleToAsset,
type JavaScriptArtifactGraphContext, type JavaScriptArtifactGraphContext,
} from "./JavaScriptArtifactGraphContext.js"; } from "./JavaScriptArtifactGraphContext.js";
import { artifactObservationEvidence } from "./JavaScriptArtifactGraphEvidence.js";
import { import {
artifactObservationEvidence, completeApplicationCoverage,
completeReconstructionCoverage, truncatedApplicationCoverage,
partialReconstructionCoverage, } from "../domain/javascriptApplicationEvidenceSchemas.js";
} from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js"; import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
/** Project HTML renderer entrypoints and their local script assets. */ /** Project HTML renderer entrypoints and their local script assets. */
@@ -68,7 +68,7 @@ export const addJavaScriptHtmlRoles = (
target: resolved, target: resolved,
file: html, file: html,
range: script.location, range: script.location,
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
relation: "loads", relation: "loads",
properties: { properties: {
script_path: script.script_path, script_path: script.script_path,
@@ -93,7 +93,7 @@ export const addJavaScriptSourceMapOriginals = (
if (mapFile === undefined || mapNode === undefined) continue; if (mapFile === undefined || mapNode === undefined) continue;
const coverage = const coverage =
sourceMap.status === "truncated" sourceMap.status === "truncated"
? partialReconstructionCoverage( ? truncatedApplicationCoverage(
[ [
{ {
name: "max-source-map-sources", name: "max-source-map-sources",
@@ -102,9 +102,8 @@ export const addJavaScriptSourceMapOriginals = (
}, },
], ],
sourceMap.omitted_sources, sourceMap.omitted_sources,
true,
) )
: completeReconstructionCoverage(); : completeApplicationCoverage();
for (const original of sourceMap.sources) { for (const original of sourceMap.sources) {
const node = context.accumulator.addNode({ const node = context.accumulator.addNode({
kind: "source-module", kind: "source-module",
@@ -111,28 +111,6 @@ export const unavailableAstEvidence = (
evidence_ids: [], 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) => ({ const artifactReference = (sha256: string) => ({
available: true as const, available: true as const,
artifact_id: `art_${sha256}`, artifact_id: `art_${sha256}`,
@@ -78,7 +78,7 @@ const addReference = (
identity: artifactLocalIdentity( identity: artifactLocalIdentity(
input.file.sha256, input.file.sha256,
input.value.kind, input.value.kind,
input.value.specifier ?? input.value.expression ?? "[dynamic]", input.value.specifier ?? input.value.expression,
), ),
observations: [ observations: [
{ {
@@ -406,7 +406,7 @@ const unresolvedReferenceNode = (
identity: artifactLocalIdentity( identity: artifactLocalIdentity(
file.sha256, file.sha256,
"unresolved-reference", "unresolved-reference",
`${reference.kind}:${reference.specifier ?? reference.expression ?? "[dynamic]"}`, `${reference.kind}:${reference.specifier ?? reference.expression}`,
), ),
observations: [ observations: [
{ {
@@ -1,5 +1,6 @@
import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js"; import type { ArtifactInventorySnapshot } from "./ArtifactInventory.js";
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js"; import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import { completeApplicationCoverage } from "../domain/javascriptApplicationEvidenceSchemas.js";
import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { import type {
JavaScriptArtifactContainer, JavaScriptArtifactContainer,
@@ -17,7 +18,6 @@ import {
} from "./JavaScriptArtifactGraphContext.js"; } from "./JavaScriptArtifactGraphContext.js";
import { import {
artifactObservationEvidence, artifactObservationEvidence,
completeReconstructionCoverage,
staticInferenceEvidence, staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js"; } from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js"; import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js";
@@ -61,7 +61,7 @@ export const createJavaScriptArtifactRootNode = (
sha256: root.sha256, sha256: root.sha256,
path: "artifact-root", path: "artifact-root",
operation: "inventory-root", operation: "inventory-root",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
limitations: [ limitations: [
"artifact-root is a path-independent alias; the application result retains the canonical local input path.", "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, sha256: container.sha256,
path: container.path, path: container.path,
operation: "inventory-nested-asar", operation: "inventory-nested-asar",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}, },
], ],
@@ -106,7 +106,7 @@ export const addJavaScriptArtifactContainers = (
sha256: context.snapshot.manifest.root_sha256, sha256: context.snapshot.manifest.root_sha256,
path: container.path, path: container.path,
operation: "inventory-nested-asar", operation: "inventory-nested-asar",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}); });
} }
@@ -147,7 +147,7 @@ export const addJavaScriptArtifactFiles = (
sha256: file.container_sha256, sha256: file.container_sha256,
path: file.path, path: file.path,
operation: "map-entry-content", operation: "map-entry-content",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}); });
} }
@@ -167,16 +167,12 @@ export const addJavaScriptArtifactFiles = (
const packageValue = context.analysis.packages.find( const packageValue = context.analysis.packages.find(
({ path }) => path === file.path, ({ path }) => path === file.path,
); );
if ( if (packageValue !== undefined && packageValue.status !== "included")
packageValue?.status !== undefined &&
packageValue.status !== "included"
)
addUnavailableStaticParseScope(context, { addUnavailableStaticParseScope(context, {
file, file,
asset: target, asset: target,
operation: "parse-package-json", operation: "parse-package-json",
limitation: limitation: packageValue.limitation,
packageValue.limitation ?? "Package metadata could not be parsed.",
}); });
const jsonValue = context.analysis.json_modules.find( const jsonValue = context.analysis.json_modules.find(
({ path }) => path === file.path, ({ path }) => path === file.path,
@@ -186,8 +182,7 @@ export const addJavaScriptArtifactFiles = (
file, file,
asset: target, asset: target,
operation: "parse-json-module", operation: "parse-json-module",
limitation: limitation: jsonValue.limitation,
jsonValue.limitation ?? "JSON module content could not be parsed.",
}); });
const sourceMap = context.analysis.source_maps.find( const sourceMap = context.analysis.source_maps.find(
({ path }) => path === file.path, ({ path }) => path === file.path,
@@ -200,8 +195,7 @@ export const addJavaScriptArtifactFiles = (
file, file,
asset: target, asset: target,
operation: "parse-local-source-map", operation: "parse-local-source-map",
limitation: limitation: sourceMap.limitation,
sourceMap.limitation ?? "Source-map content could not be parsed.",
}); });
} }
}; };
@@ -232,7 +226,7 @@ export const addJavaScriptPackageNodes = (
sha256: file.sha256, sha256: file.sha256,
path: file.path, path: file.path,
operation: "parse-package-json", operation: "parse-package-json",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
limitations: limitations:
packageValue.limitation === null ? [] : [packageValue.limitation], packageValue.limitation === null ? [] : [packageValue.limitation],
}), }),
@@ -250,7 +244,7 @@ export const addJavaScriptPackageNodes = (
sha256: file.sha256, sha256: file.sha256,
path: file.path, path: file.path,
operation: "associate-package-artifact", operation: "associate-package-artifact",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}); });
} else } else
@@ -312,7 +306,7 @@ const createFileTarget = (
sha256: file.sha256, sha256: file.sha256,
path: file.path, path: file.path,
operation: "inventory-relevant-file", operation: "inventory-relevant-file",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}, },
], ],
@@ -348,7 +342,7 @@ const createAsarEntry = (
sha256: file.container_sha256, sha256: file.container_sha256,
path: file.path, path: file.path,
operation: "inventory-asar-entry", operation: "inventory-asar-entry",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
}), }),
}, },
], ],
@@ -390,7 +384,7 @@ const addPackageRole = (
sha256: input.packageFile.sha256, sha256: input.packageFile.sha256,
path: input.packageFile.path, path: input.packageFile.path,
operation: "discover-package-entrypoint", operation: "discover-package-entrypoint",
coverage: completeReconstructionCoverage(), coverage: completeApplicationCoverage(),
limitations: resolution.limitations, limitations: resolution.limitations,
}), }),
}); });
@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";
import { import {
resolveArtifactPathByContext, resolveArtifactPathByContext,
type ResolveArtifactPathInput, type ResolveArtifactPathInput,
} from "../../../src/application/JavaScriptArtifactPathResolution.js"; } from "./JavaScriptArtifactPathResolution.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js"; import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { analyzeJavaScriptStaticSource } from "../../../src/domain/javascriptStaticAnalysis.js"; import { analyzeJavaScriptStaticSource } from "../domain/javascriptStaticAnalysis.js";
describe("contextual JavaScript artifact path resolution", () => { describe("contextual JavaScript artifact path resolution", () => {
it.each([ it.each([
@@ -3,33 +3,42 @@ import { posix } from "node:path";
import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js"; import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
/** Explicit outcome of bounded, artifact-confined path resolution. */ type ArtifactPathResolutionContext =
export interface ArtifactPathResolution { | "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
type UnresolvedArtifactPathStatus =
| "not-found"
| "unavailable"
| "external"
| "rejected";
interface ArtifactPathResolutionBase {
readonly declared_path: string; readonly declared_path: string;
readonly resolution_context: readonly resolution_context: ArtifactPathResolutionContext;
| "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
readonly resolved_path: string | null;
readonly resolution_status:
| "resolved"
| "not-found"
| "unavailable"
| "external"
| "rejected";
readonly limitations: readonly string[]; 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. */ /** Values needed to resolve a declaration without filesystem access. */
export interface ResolveArtifactPathInput { export interface ResolveArtifactPathInput {
readonly declaredPath: string; readonly declaredPath: string;
readonly sourcePath: string; readonly sourcePath: string;
readonly context: readonly context: ArtifactPathResolutionContext;
| "package-entrypoint"
| "filesystem-expression"
| "module-specifier"
| "html-reference";
readonly files: ReadonlyMap<string, JavaScriptArtifactFile>; readonly files: ReadonlyMap<string, JavaScriptArtifactFile>;
readonly htmlBaseHref?: string | null; readonly htmlBaseHref?: string | null;
readonly moduleKind?: "import" | "require"; readonly moduleKind?: "import" | "require";
@@ -50,11 +59,17 @@ const NODE_BUILTINS = new Set(
builtinModules.map((name) => name.replace(/^node:/u, "")), builtinModules.map((name) => name.replace(/^node:/u, "")),
); );
interface CandidateResolution { type CandidateResolution =
readonly resolvedPath: string | null; | {
readonly status: ArtifactPathResolution["resolution_status"]; readonly resolvedPath: string;
readonly limitations: readonly 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. */ /** Resolve one declaration under its exact syntax/metadata context. */
export const resolveArtifactPathByContext = ( export const resolveArtifactPathByContext = (
@@ -72,12 +87,7 @@ const resolveAtDepth = (
const confined = confineCandidate(input, candidate); const confined = confineCandidate(input, candidate);
if (typeof confined !== "string") return confined; if (typeof confined !== "string") return confined;
const resolved = resolveCandidate(input, confined, packageDepth); const resolved = resolveCandidate(input, confined, packageDepth);
return outcome( return outcome(input, resolved);
input,
resolved.status,
resolved.resolvedPath,
resolved.limitations,
);
}; };
const rejectDeclaration = ( const rejectDeclaration = (
@@ -85,17 +95,19 @@ const rejectDeclaration = (
): ArtifactPathResolution | null => { ): ArtifactPathResolution | null => {
const declared = input.declaredPath; const declared = input.declaredPath;
if (declared.length === 0) 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) if (declared.length > 4_096)
return outcome(input, "rejected", null, [ return unresolvedOutcome(input, "rejected", [
"The declared path exceeds the 4096-character resolution bound.", "The declared path exceeds the 4096-character resolution bound.",
]); ]);
if (declared.includes("\0") || declared.includes("\\")) 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.", "NUL and backslash path syntax are not admitted for canonical artifact paths.",
]); ]);
if (/%(?:2e|2f|5c)/iu.test(declared)) 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.", "Encoded dot or separator bytes are rejected before artifact path resolution.",
]); ]);
return null; return null;
@@ -114,13 +126,13 @@ const contextualCandidate = (
const fileUrl = fileUrlPath(declared); const fileUrl = fileUrlPath(declared);
if (fileUrl !== undefined) return fileUrl; if (fileUrl !== undefined) return fileUrl;
if (hasScheme(declared)) if (hasScheme(declared))
return outcome(input, "external", null, [ return unresolvedOutcome(input, "external", [
"URL and Node builtin schemes are outside static artifact module resolution.", "URL and Node builtin schemes are outside static artifact module resolution.",
]); ]);
if (!declared.startsWith(".") && !declared.startsWith("/")) if (!declared.startsWith(".") && !declared.startsWith("/"))
return bareModuleCandidate(input, declared); return bareModuleCandidate(input, declared);
} else if (hasScheme(declared)) } else if (hasScheme(declared))
return outcome(input, "external", null, [ return unresolvedOutcome(input, "external", [
"URL schemes are outside this local artifact path context.", "URL schemes are outside this local artifact path context.",
]); ]);
const relative = declared.startsWith("/") ? declared.slice(1) : declared; const relative = declared.startsWith("/") ? declared.slice(1) : declared;
@@ -139,11 +151,11 @@ const bareModuleCandidate = (
NODE_BUILTINS.has(packageName) || NODE_BUILTINS.has(packageName) ||
declared.startsWith("#") 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.", "The bare specifier is a Node builtin, package import map, or invalid package name.",
]); ]);
if (declared !== packageName) 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.", "Bare package subpaths remain unresolved unless an exact package-exports subpath model is available.",
]); ]);
const source = input.files.get(input.sourcePath); const source = input.files.get(input.sourcePath);
@@ -155,7 +167,7 @@ const bareModuleCandidate = (
if (directory === "." || directory === "") break; if (directory === "." || directory === "") break;
directory = posix.dirname(directory); 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.", "No matching bare package was inventoried in an enclosing node_modules directory.",
]); ]);
}; };
@@ -190,7 +202,7 @@ const htmlCandidate = (
): string | ArtifactPathResolution => { ): string | ArtifactPathResolution => {
const declared = stripQueryAndFragment(input.declaredPath); const declared = stripQueryAndFragment(input.declaredPath);
if (hasScheme(declared)) if (hasScheme(declared))
return outcome(input, "external", null, [ return unresolvedOutcome(input, "external", [
"External HTML references are not mapped to local artifact assets.", "External HTML references are not mapped to local artifact assets.",
]); ]);
if (declared.startsWith("/")) return declared.slice(1); if (declared.startsWith("/")) return declared.slice(1);
@@ -198,7 +210,7 @@ const htmlCandidate = (
if (base === undefined || base === null || base === "") if (base === undefined || base === null || base === "")
return posix.join(posix.dirname(input.sourcePath), declared); return posix.join(posix.dirname(input.sourcePath), declared);
if (hasScheme(base)) 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.", "The document base href is external, so its script reference is not a local artifact path.",
]); ]);
const basePath = base.startsWith("/") const basePath = base.startsWith("/")
@@ -218,7 +230,7 @@ const confineCandidate = (
normalized.startsWith("../") || normalized.startsWith("../") ||
normalized.startsWith("/") normalized.startsWith("/")
) )
return outcome(input, "rejected", null, [ return unresolvedOutcome(input, "rejected", [
"The resolved candidate escapes the canonical artifact root.", "The resolved candidate escapes the canonical artifact root.",
]); ]);
return normalized === "." ? "" : normalized; return normalized === "." ? "" : normalized;
@@ -282,11 +294,17 @@ const resolveCandidate = (
}, },
packageDepth + 1, packageDepth + 1,
); );
return { return nested.resolution_status === "resolved"
resolvedPath: nested.resolved_path, ? {
status: nested.resolution_status, resolvedPath: nested.resolved_path,
limitations: nested.limitations, status: nested.resolution_status,
}; limitations: nested.limitations,
}
: {
resolvedPath: null,
status: nested.resolution_status,
limitations: nested.limitations,
};
}; };
const directCandidates = (candidate: string): readonly string[] => [ const directCandidates = (candidate: string): readonly string[] => [
@@ -374,13 +392,27 @@ const stripQueryAndFragment = (value: string): string =>
const outcome = ( const outcome = (
input: ResolveArtifactPathInput, input: ResolveArtifactPathInput,
status: ArtifactPathResolution["resolution_status"], resolution: CandidateResolution,
resolvedPath: string | null, ): 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[], limitations: readonly string[],
): ArtifactPathResolution => ({ ): ArtifactPathResolution =>
declared_path: input.declaredPath, outcome(input, { resolvedPath: null, status, limitations });
resolution_context: input.context,
resolved_path: resolvedPath,
resolution_status: status,
limitations,
});
@@ -1,6 +1,11 @@
import { posix } from "node:path"; import { posix } from "node:path";
import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js"; import type { ApplicationNode } from "../domain/javascriptApplicationGraph.js";
import {
completeApplicationCoverage,
partialApplicationCoverage,
truncatedApplicationCoverage,
} from "../domain/javascriptApplicationEvidenceSchemas.js";
import type { import type {
JavaScriptModuleOrigin, JavaScriptModuleOrigin,
JavaScriptSemanticIr, JavaScriptSemanticIr,
@@ -16,11 +21,12 @@ import {
} from "./JavaScriptArtifactGraphContext.js"; } from "./JavaScriptArtifactGraphContext.js";
import { import {
astObservationEvidence, astObservationEvidence,
completeReconstructionCoverage,
partialReconstructionCoverage,
staticInferenceEvidence, staticInferenceEvidence,
} from "./JavaScriptArtifactGraphEvidence.js"; } from "./JavaScriptArtifactGraphEvidence.js";
import { resolveArtifactPathByContext } from "./JavaScriptArtifactPathResolution.js"; import {
resolveArtifactPathByContext,
type ArtifactPathResolution,
} from "./JavaScriptArtifactPathResolution.js";
import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js"; import { projectJavaScriptExportReturnShapes } from "./JavaScriptReturnShapeProjection.js";
interface SemanticAnalysis { interface SemanticAnalysis {
@@ -36,18 +42,24 @@ interface RelationshipInput {
readonly link: JavaScriptSemanticModuleLink; readonly link: JavaScriptSemanticModuleLink;
} }
interface ResolvedModuleTarget { type ResolvedModuleTarget = {
readonly node: ApplicationNode; readonly node: ApplicationNode;
readonly path: string | null;
readonly file: JavaScriptArtifactFile | null;
readonly status:
| "resolved"
| "not-found"
| "unavailable"
| "external"
| "rejected";
readonly limitations: readonly string[]; 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. */ /** Create one path-scoped source-module identity for every analyzed source file. */
export const addJavaScriptSourceModules = ( export const addJavaScriptSourceModules = (
@@ -239,26 +251,32 @@ const resolveModuleTarget = (
? "require" ? "require"
: "import", : "import",
}); });
const path = resolution.resolved_path; if (resolution.resolution_status !== "resolved")
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)
return { return {
node, node: unresolvedModuleNode(
path, input,
file, specifier,
status: "resolved", resolution.resolution_status,
),
path: null,
file: null,
status: resolution.resolution_status,
limitations: resolution.limitations, 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 { return {
node: unresolvedModuleNode(input, specifier, resolution.resolution_status), node,
path: null, path,
file: null, file,
status: resolution.resolution_status, status: "resolved",
limitations: resolution.limitations, limitations: resolution.limitations,
}; };
}; };
@@ -266,7 +284,7 @@ const resolveModuleTarget = (
const unresolvedModuleNode = ( const unresolvedModuleNode = (
input: RelationshipInput, input: RelationshipInput,
specifier: string, specifier: string,
status: ResolvedModuleTarget["status"], status: Exclude<ResolvedModuleTarget["status"], "resolved">,
): ApplicationNode => ): ApplicationNode =>
input.context.accumulator.addNode({ input.context.accumulator.addNode({
kind: "javascript-module", kind: "javascript-module",
@@ -360,12 +378,10 @@ const semanticCoverage = (
unit: "items" as const, unit: "items" as const,
})); }));
if (semantic.ir.coverage.status === "complete") if (semantic.ir.coverage.status === "complete")
return completeReconstructionCoverage(limits); return completeApplicationCoverage(limits);
return partialReconstructionCoverage( return semantic.ir.coverage.status === "truncated"
limits, ? truncatedApplicationCoverage(limits, semantic.ir.coverage.omittedCount)
semantic.ir.coverage.omittedCount, : partialApplicationCoverage(limits, semantic.ir.coverage.omittedCount);
semantic.ir.coverage.status === "truncated",
);
}; };
const moduleFormat = ( const moduleFormat = (
@@ -1,4 +1,8 @@
import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js"; import { jsonObjectSchema, jsonValueSchema } from "../domain/jsonValue.js";
import {
partialApplicationCoverage,
truncatedApplicationCoverage,
} from "../domain/javascriptApplicationEvidenceSchemas.js";
import type { import type {
JavaScriptSemanticIr, JavaScriptSemanticIr,
JavaScriptSemanticCallable, JavaScriptSemanticCallable,
@@ -7,7 +11,6 @@ import type {
import { flattenSemanticReturnValue } from "../domain/javascriptSemanticReturns.js"; import { flattenSemanticReturnValue } from "../domain/javascriptSemanticReturns.js";
import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js"; import type { JavaScriptSourceRange } from "../domain/javascriptStaticAnalysisTypes.js";
import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js"; import type { JavaScriptArtifactGraphCoverage } from "./JavaScriptArtifactGraphContext.js";
import { partialReconstructionCoverage } from "./JavaScriptArtifactGraphEvidence.js";
const MAX_PROJECTED_RETURN_SHAPES = 32; const MAX_PROJECTED_RETURN_SHAPES = 32;
const MAX_PROJECTED_RETURN_FIELDS = 64; const MAX_PROJECTED_RETURN_FIELDS = 64;
@@ -43,30 +46,31 @@ export const projectJavaScriptExportReturnShapes = (input: {
input.baseCoverage.status === "complete" && input.baseCoverage.status === "complete" &&
callable.returnCoverage.status === "complete" && callable.returnCoverage.status === "complete" &&
projectionOmitted === 0; 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 const coverage = complete
? input.baseCoverage ? input.baseCoverage
: partialReconstructionCoverage( : callable.returnCoverage.status === "truncated" || projectionOmitted > 0
[ ? truncatedApplicationCoverage(limits, omitted)
...input.baseCoverage.limits, : partialApplicationCoverage(limits, omitted);
{
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,
);
const limitations = [ const limitations = [
...input.ir.limitations, ...input.ir.limitations,
"Return shapes are inferred from inert syntax and do not prove runtime behavior.", "Return shapes are inferred from inert syntax and do not prove runtime behavior.",
@@ -1,14 +1,14 @@
import { expect, it } from "vitest"; import { expect, it } from "vitest";
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js"; import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js"; import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js"; import { queryJavaScriptSemanticGraph } from "../domain/javascriptSemanticQuery.js";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js"; import { analyzeJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
import { import {
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS, DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
type JavaScriptSemanticLimits, type JavaScriptSemanticLimits,
} from "../../../src/domain/javascriptSemanticIr.js"; } from "../domain/javascriptSemanticIr.js";
const SHA256 = "a".repeat(64); const SHA256 = "a".repeat(64);
const GRAPH_ID = `jag_${"b".repeat(64)}`; const GRAPH_ID = `jag_${"b".repeat(64)}`;
@@ -1,14 +1,14 @@
import { expect, it } from "vitest"; import { expect, it } from "vitest";
import { buildJavaScriptSemanticGraph } from "../../../src/application/JavaScriptSemanticGraphBuilder.js"; import { buildJavaScriptSemanticGraph } from "./JavaScriptSemanticGraphBuilder.js";
import type { JavaScriptArtifactAnalysis } from "../../../src/application/JavaScriptArtifactAnalysisTypes.js"; import type { JavaScriptArtifactAnalysis } from "./JavaScriptArtifactAnalysisTypes.js";
import type { JavaScriptArtifactFile } from "../../../src/application/JavaScriptArtifactFiles.js"; import type { JavaScriptArtifactFile } from "./JavaScriptArtifactFiles.js";
import { queryJavaScriptSemanticGraph } from "../../../src/domain/javascriptSemanticQuery.js"; import { queryJavaScriptSemanticGraph } from "../domain/javascriptSemanticQuery.js";
import { analyzeJavaScriptSemantics } from "../../../src/domain/javascriptSemanticAnalysis.js"; import { analyzeJavaScriptSemantics } from "../domain/javascriptSemanticAnalysis.js";
import { import {
DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS, DEFAULT_JAVASCRIPT_SEMANTIC_LIMITS,
type JavaScriptSemanticLimits, type JavaScriptSemanticLimits,
} from "../../../src/domain/javascriptSemanticIr.js"; } from "../domain/javascriptSemanticIr.js";
const SHA256 = "a".repeat(64); const SHA256 = "a".repeat(64);
const GRAPH_ID = `jag_${"b".repeat(64)}`; const GRAPH_ID = `jag_${"b".repeat(64)}`;
+23 -14
View File
@@ -64,14 +64,24 @@ export const linuxHopperInstallDisclosure = (
}; };
}; };
/** Parsed Linux distribution information used for support and package selection. */ interface LinuxDistributionIdentity {
export interface LinuxDistribution {
readonly id: string; readonly id: string;
readonly versionId?: 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. */ /** Download response kept independent of Node's global fetch implementation. */
export interface LinuxHopperDownload { export interface LinuxHopperDownload {
readonly ok: boolean; readonly ok: boolean;
@@ -134,15 +144,17 @@ export const parseLinuxDistribution = (text: string): LinuxDistribution => {
const versionId = fields.get("VERSION_ID"); const versionId = fields.get("VERSION_ID");
const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE")); const packageFamily = packageFamilyFor(id, fields.get("ID_LIKE"));
const supported = const supported =
id === "arch" || packageFamily !== undefined &&
(id === "ubuntu" && versionAtLeast(versionId, 24)) || (id === "arch" ||
(id === "fedora" && versionAtLeast(versionId, 41)); (id === "ubuntu" && versionAtLeast(versionId, 24)) ||
return { (id === "fedora" && versionAtLeast(versionId, 41)));
const identity = {
id, id,
...(versionId === undefined ? {} : { versionId }), ...(versionId === undefined ? {} : { versionId }),
packageFamily,
supported,
}; };
return supported
? { ...identity, packageFamily, supported: true }
: { ...identity, packageFamily, supported: false };
}; };
/** Read and classify the current Linux distribution. */ /** Read and classify the current Linux distribution. */
@@ -169,10 +181,7 @@ export const installLinuxHopper = async (
if (options.signal?.aborted === true) if (options.signal?.aborted === true)
return { status: "failed", reason: "cancelled" }; return { status: "failed", reason: "cancelled" };
const distribution = await host.distribution(); const distribution = await host.distribution();
if ( if (distribution?.supported !== true)
distribution?.supported !== true ||
distribution.packageFamily === undefined
)
return { status: "failed", reason: "unsupported_host" }; return { status: "failed", reason: "unsupported_host" };
let temporary: string | undefined; let temporary: string | undefined;
try { try {
@@ -97,7 +97,7 @@ export const planManagedRuntimeCorrelationEvidenceValidated = async (
operation_identity: operationIdentity(input, staticEvidence), operation_identity: operationIdentity(input, staticEvidence),
}, },
"read", "read",
{ restartRequired: true }, { remediation: "restart" },
); );
if (!authorized.ok) if (!authorized.ok)
return err( return err(
+26 -15
View File
@@ -18,7 +18,10 @@ import {
reloadPermissionCeilings, reloadPermissionCeilings,
revokePermission, revokePermission,
} from "../domain/permissionPolicy.js"; } 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"; import { err, ok, type Result } from "../domain/result.js";
/** Failure to establish a filesystem object's canonical authorization identity. */ /** 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"; isNotFound(error) ? "not_found" : "io";
interface PermissionEvaluationOptions { interface PermissionEvaluationOptions {
readonly elicitationSupported?: boolean; readonly remediation?: PermissionRemediation;
readonly restartRequired?: boolean;
} }
interface CanonicalPermissionDecision { interface CanonicalPermissionDecision {
@@ -131,16 +133,22 @@ type PermissionAuthorizationResult = Promise<
export class PermissionAuthority { export class PermissionAuthority {
private policy: PermissionPolicy; private policy: PermissionPolicy;
private readonly configuredAuthority: PermissionAuthority | undefined; private readonly configuredAuthority: PermissionAuthority | undefined;
private readonly outsideCeilingRestartRequired: boolean; private readonly outsideCeilingRemediation: Exclude<
PermissionRemediation,
"elicit"
>;
constructor( constructor(
policy: PermissionPolicy, policy: PermissionPolicy,
configuredAuthority?: PermissionAuthority, configuredAuthority?: PermissionAuthority,
outsideCeilingRestartRequired = false, outsideCeilingRemediation: Exclude<
PermissionRemediation,
"elicit"
> = "configure",
) { ) {
this.policy = policy; this.policy = policy;
this.configuredAuthority = configuredAuthority; this.configuredAuthority = configuredAuthority;
this.outsideCeilingRestartRequired = outsideCeilingRestartRequired; this.outsideCeilingRemediation = outsideCeilingRemediation;
} }
/** Create a connection-owned overlay for once and session grants. */ /** Create a connection-owned overlay for once and session grants. */
@@ -148,7 +156,7 @@ export class PermissionAuthority {
return new PermissionAuthority( return new PermissionAuthority(
createPermissionPolicy([]), createPermissionPolicy([]),
this.configuredAuthority ?? this, this.configuredAuthority ?? this,
true, "restart",
); );
} }
@@ -273,15 +281,18 @@ export class PermissionAuthority {
if (denied.allowed) return ok({ decision: denied, owner: this }); if (denied.allowed) return ok({ decision: denied, owner: this });
const outsideAdministratorCeiling = const outsideAdministratorCeiling =
denied.reason === "outside_administrator_ceiling"; denied.reason === "outside_administrator_ceiling";
const requestedRemediation = options.remediation ?? "configure";
const remediation =
outsideAdministratorCeiling && requestedRemediation !== "restart"
? this.outsideCeilingRemediation
: requestedRemediation;
return err( return err(
new PermissionRequiredError( new PermissionRequiredError({
request, requested: request,
denied.missing, missing: denied.missing,
ceilingFor(effective, request.capability), ceiling: ceilingFor(effective, request.capability),
!outsideAdministratorCeiling && (options.elicitationSupported ?? false), remediation,
options.restartRequired ?? }),
(outsideAdministratorCeiling && this.outsideCeilingRestartRequired),
),
); );
} }
+28 -13
View File
@@ -9,9 +9,11 @@ import type {
FilesystemCheckpoint, FilesystemCheckpoint,
InteractionEvent, InteractionEvent,
ProcessCapture, ProcessCapture,
UnverifiedProcessCapture,
ProcessExecutionPolicy, ProcessExecutionPolicy,
ProcessPolicyDecision, ProcessPolicyDecision,
ProcessSample, ProcessSample,
ProcessSettlement,
ProcessScenario, ProcessScenario,
ProcessCaptureEventJournalEntry, ProcessCaptureEventJournalEntry,
RecordProcessCaptureEvent, RecordProcessCaptureEvent,
@@ -71,25 +73,43 @@ interface CaptureResultOptions {
}; };
readonly samples: readonly ProcessSample[]; readonly samples: readonly ProcessSample[];
readonly replay: LoopbackReplay; readonly replay: LoopbackReplay;
readonly reactiveRun: ProcessCapture["reactive_run"];
readonly before: SnapshotResult; readonly before: SnapshotResult;
readonly after: SnapshotResult; readonly after: SnapshotResult;
readonly truncated: boolean; readonly truncated: boolean;
readonly scenario: ProcessScenario; readonly scenario: ProcessScenario;
readonly rootPid: number; readonly rootPid: number;
readonly samplingPartial: boolean; readonly samplingPartial: boolean;
readonly renderedFrames: ProcessCapture["rendered_frames"]; readonly renderedFrames: UnverifiedProcessCapture["rendered_frames"];
readonly interactions: readonly InteractionEvent[]; readonly interactions: readonly InteractionEvent[];
readonly checkpoints: readonly FilesystemCheckpoint[]; readonly checkpoints: readonly FilesystemCheckpoint[];
readonly shimEvents: ProcessCapture["shim_events"]; readonly shimEvents: UnverifiedProcessCapture["shim_events"];
readonly settlement: ProcessCapture["settlement"]; readonly settlement: ObservedProcessSettlement;
readonly manifest: ProcessCapture["manifest"]; readonly manifest: UnverifiedProcessCapture["manifest"];
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[]; 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 = ( export const buildCaptureResult = (
options: CaptureResultOptions, options: CaptureResultOptions,
): ProcessCapture => ({ ): PendingProcessCapture => ({
schema_version: 4, schema_version: 4,
manifest: options.manifest, manifest: options.manifest,
normalization: options.scenario.normalization, normalization: options.scenario.normalization,
@@ -117,7 +137,6 @@ export const buildCaptureResult = (
options.scenario, options.scenario,
), ),
replay_transitions: options.replay.transitions, replay_transitions: options.replay.transitions,
reactive_run: options.reactiveRun,
event_journal: options.eventJournal, event_journal: options.eventJournal,
files_before: options.before.files, files_before: options.before.files,
files_after: options.after.files, files_after: options.after.files,
@@ -144,10 +163,6 @@ export const buildCaptureResult = (
reason: "External network isolation is not enforced by this adapter.", 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> => { const hashFile = async (path: string): Promise<string> => {
@@ -160,7 +175,7 @@ export const createRunManifest = async (
scenario: ProcessScenario, scenario: ProcessScenario,
startedAt: Date, startedAt: Date,
completedAt: Date, completedAt: Date,
): Promise<ProcessCapture["manifest"]> => { ): Promise<UnverifiedProcessCapture["manifest"]> => {
const executableSha256 = await hashFile(scenario.executable); const executableSha256 = await hashFile(scenario.executable);
const scenarioCommitment = processScenarioCommitment( const scenarioCommitment = processScenarioCommitment(
scenario, scenario,
@@ -193,7 +208,7 @@ export const observeSettlement = async (
processGroupIds: readonly number[], processGroupIds: readonly number[],
settleMs: number, settleMs: number,
recordEvent: RecordProcessCaptureEvent = () => undefined, recordEvent: RecordProcessCaptureEvent = () => undefined,
): Promise<Omit<ProcessCapture["settlement"], "cleanup_outcome">> => { ): Promise<ObservedProcessSettlement> => {
if (process.platform === "win32") { if (process.platform === "win32") {
recordEvent("lifecycle", 1); recordEvent("lifecycle", 1);
return { state: "unverifiable", elapsed_ms: 0 }; return { state: "unverifiable", elapsed_ms: 0 };
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { processCapturePermissionRequest } from "../../../src/application/ProcessCapturePermission.js"; import { processCapturePermissionRequest } from "./ProcessCapturePermission.js";
import { parseProcessScenario } from "../../../src/domain/processCapture.js"; import { parseProcessScenario } from "../domain/processCapture.js";
describe("process capture permission request", () => { describe("process capture permission request", () => {
it("projects the complete adapter-neutral authority scope", () => { it("projects the complete adapter-neutral authority scope", () => {
+26 -9
View File
@@ -18,15 +18,32 @@ export const classifyFilesystemEffects = (
.map((path) => { .map((path) => {
const beforeFile = beforeByPath.get(path) ?? null; const beforeFile = beforeByPath.get(path) ?? null;
const afterFile = afterByPath.get(path) ?? null; const afterFile = afterByPath.get(path) ?? null;
const status = if (beforeFile === null) {
beforeFile === null if (afterFile === null)
? "created" throw new TypeError(`Filesystem effect ${path} has no file state`);
: afterFile === null return {
? "deleted" path,
: JSON.stringify(beforeFile) === JSON.stringify(afterFile) status: "created",
? "unchanged" before: null,
: "modified"; after: afterFile,
return { path, status, before: beforeFile, after: afterFile } as const; } 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;
}); });
}; };
+2 -4
View File
@@ -5,7 +5,6 @@ import type {
ProcessCapture, ProcessCapture,
ProcessScenario, ProcessScenario,
} from "../domain/processCapture.js"; } from "../domain/processCapture.js";
import { parseProcessCapture } from "../domain/processCapture.js";
/** Provider identity for controlled Process Capture v4 evidence. */ /** Provider identity for controlled Process Capture v4 evidence. */
export const PROCESS_PROVIDER = { export const PROCESS_PROVIDER = {
@@ -32,12 +31,11 @@ export const createProcessCaptureEvidence = (
scenario: ProcessScenario, scenario: ProcessScenario,
capture: ProcessCapture, capture: ProcessCapture,
) => { ) => {
const validatedCapture = parseProcessCapture(capture);
return createEvidence(undefined, PROCESS_PROVIDER, { return createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4", predicateType: "rea.process-capture/v4",
operation: "capture_process_scenario", operation: "capture_process_scenario",
parameters: processEvidenceParameters(scenario), parameters: processEvidenceParameters(scenario),
result: jsonValueSchema.parse(validatedCapture), result: jsonValueSchema.parse(capture),
confidence: "observed", confidence: "observed",
authority: "controlled-replay", authority: "controlled-replay",
environment: { environment: {
@@ -46,6 +44,6 @@ export const createProcessCaptureEvidence = (
architecture: process.arch, architecture: process.arch,
isolation: "process", isolation: "process",
}, },
limitations: validatedCapture.limitations, limitations: capture.limitations,
}); });
}; };
+30 -21
View File
@@ -2,6 +2,7 @@ import type { IPty } from "@lydell/node-pty";
import type { import type {
InteractionEvent, InteractionEvent,
ProcessCapture, ProcessCapture,
UnverifiedProcessCapture,
ProcessCaptureEventJournalEntry, ProcessCaptureEventJournalEntry,
ProcessExecutionPolicy, ProcessExecutionPolicy,
ProcessSample, ProcessSample,
@@ -9,7 +10,7 @@ import type {
RecordProcessCaptureEvent, RecordProcessCaptureEvent,
TerminalFrame, TerminalFrame,
} from "../domain/processCapture.js"; } 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 { err, ok, type Result } from "../domain/result.js";
import { import {
ProcessCaptureError, ProcessCaptureError,
@@ -39,6 +40,7 @@ import {
prepareProcessCapture, prepareProcessCapture,
releaseProcessResources, releaseProcessResources,
resolveProcessResult, resolveProcessResult,
type PendingProcessCapture,
} from "./ProcessCaptureLifecycle.js"; } from "./ProcessCaptureLifecycle.js";
import { assertNotCancelled } from "./ProcessCaptureAuthority.js"; import { assertNotCancelled } from "./ProcessCaptureAuthority.js";
import { import {
@@ -240,7 +242,7 @@ const normalizedShimEvents = (
runtime: StartedCaptureRuntime, runtime: StartedCaptureRuntime,
scenario: ProcessScenario, scenario: ProcessScenario,
temporaryRoot: string, temporaryRoot: string,
): ProcessCapture["shim_events"] => ): UnverifiedProcessCapture["shim_events"] =>
runtime.shimReplay.events.map((event) => runtime.shimReplay.events.map((event) =>
normalizeProcessShimEvent( normalizeProcessShimEvent(
event, event,
@@ -257,7 +259,7 @@ const finishProcessRun = async (options: {
readonly temporaryRoot: string; readonly temporaryRoot: string;
readonly samples: readonly ProcessSample[]; readonly samples: readonly ProcessSample[];
readonly stopSampler: () => Promise<{ readonly partial: boolean }>; readonly stopSampler: () => Promise<{ readonly partial: boolean }>;
readonly capture: ProcessCapture | undefined; readonly capture: PendingProcessCapture | undefined;
readonly executionFailure: unknown; readonly executionFailure: unknown;
}): Promise<ProcessCapture> => { }): Promise<ProcessCapture> => {
options.runtime?.reactive?.unsubscribe(); options.runtime?.reactive?.unsubscribe();
@@ -285,27 +287,35 @@ const finishProcessRun = async (options: {
}); });
await options.runtime?.reactive?.coordinator.close(); await options.runtime?.reactive?.coordinator.close();
let { capture, executionFailure } = options; let { capture, executionFailure } = options;
if (capture !== undefined) { let verifiedCapture: ProcessCapture | undefined;
capture = { 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, ...capture,
reactive_run: projectProcessReactiveRun(options.runtime?.reactive), reactive_run: projectProcessReactiveRun(options.runtime?.reactive),
settlement: { settlement,
...capture.settlement, cleanup: {
cleanup_outcome: owned_process_group: "verified",
capture.settlement.state === "quiesced" temporary_root: "removed",
? "not_required"
: cleanupFailure === undefined
? "cleaned"
: "failed",
}, },
}; };
const issue = validateProcessCapture(capture)[0]; try {
if (issue !== undefined) verifiedCapture = parseProcessCapture(completedCapture);
} catch (cause: unknown) {
executionFailure = new ProcessCaptureError( 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: { const completeCapture = async (options: {
@@ -322,7 +332,7 @@ const completeCapture = async (options: {
readonly initiallyTruncated: boolean; readonly initiallyTruncated: boolean;
readonly eventJournal: readonly ProcessCaptureEventJournalEntry[]; readonly eventJournal: readonly ProcessCaptureEventJournalEntry[];
readonly recordEvent: RecordProcessCaptureEvent; readonly recordEvent: RecordProcessCaptureEvent;
}): Promise<ProcessCapture> => { }): Promise<PendingProcessCapture> => {
const { runtime, scenario } = options; const { runtime, scenario } = options;
runtime.checkpoints.trigger("root_exit"); runtime.checkpoints.trigger("root_exit");
const { reason } = options.exit; const { reason } = options.exit;
@@ -374,7 +384,6 @@ const completeCapture = async (options: {
exit: { ...options.exit, reason }, exit: { ...options.exit, reason },
samples: options.samples, samples: options.samples,
replay: runtime.replay, replay: runtime.replay,
reactiveRun: projectProcessReactiveRun(runtime.reactive),
before: options.before, before: options.before,
after, after,
truncated, truncated,
@@ -385,7 +394,7 @@ const completeCapture = async (options: {
interactions: options.interactions, interactions: options.interactions,
checkpoints, checkpoints,
shimEvents: normalizedShimEvents(runtime, scenario, options.temporaryRoot), shimEvents: normalizedShimEvents(runtime, scenario, options.temporaryRoot),
settlement: { ...settlement, cleanup_outcome: "not_required" }, settlement,
manifest, manifest,
eventJournal: options.eventJournal, eventJournal: options.eventJournal,
}); });
@@ -409,7 +418,7 @@ const runProcessScenario = async (
const { entries: eventJournal, recordEvent } = journal; const { entries: eventJournal, recordEvent } = journal;
let runtime: StartedCaptureRuntime | undefined; let runtime: StartedCaptureRuntime | undefined;
const timers = new Set<NodeJS.Timeout>(); const timers = new Set<NodeJS.Timeout>();
let capture: ProcessCapture | undefined; let capture: PendingProcessCapture | undefined;
let executionFailure: unknown; let executionFailure: unknown;
let stopSampler = async () => ({ partial: false }); let stopSampler = async () => ({ partial: false });
const interactions: InteractionEvent[] = []; const interactions: InteractionEvent[] = [];
@@ -3,18 +3,18 @@ import { describe, expect, it } from "vitest";
import { import {
runPairedProcessExperiment, runPairedProcessExperiment,
type ProcessCapturePort, type ProcessCapturePort,
} from "../../../src/application/ProcessPairedExperiment.js"; } from "./ProcessPairedExperiment.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js"; import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { import {
parseProcessCapture, parseProcessCapture,
type EnabledProcessExecutionPolicy, type EnabledProcessExecutionPolicy,
} from "../../../src/domain/processCapture.js"; } from "../domain/processCapture.js";
import { import {
analyzeProcessRepeatability, analyzeProcessRepeatability,
bindProcessScenario, bindProcessScenario,
processPairedExperimentSchema, processPairedExperimentSchema,
} from "../../../src/domain/processPairedExperiment.js"; } from "../domain/processPairedExperiment.js";
import { ok } from "../../../src/domain/result.js"; import { ok } from "../domain/result.js";
const experiment = () => const experiment = () =>
processPairedExperimentSchema.parse({ processPairedExperimentSchema.parse({
@@ -58,6 +58,11 @@ const policy: EnabledProcessExecutionPolicy = {
networkAccess: "none", networkAccess: "none",
}; };
const cloneCapture = (
capture: ReturnType<typeof parseProcessCapture>,
): ReturnType<typeof parseProcessCapture> =>
parseProcessCapture(structuredClone(capture));
describe("paired process experiments", () => { describe("paired process experiments", () => {
it("binds only declared side inputs onto the shared observation contract", () => { it("binds only declared side inputs onto the shared observation contract", () => {
const parsed = experiment(); const parsed = experiment();
@@ -87,7 +92,7 @@ describe("paired process experiments", () => {
const capturePort: ProcessCapturePort = { const capturePort: ProcessCapturePort = {
capture: (scenario) => { capture: (scenario) => {
observedExecutables.push(scenario.executable); observedExecutables.push(scenario.executable);
return Promise.resolve(ok(structuredClone(capture))); return Promise.resolve(ok(cloneCapture(capture)));
}, },
}; };
const result = await runPairedProcessExperiment(experiment(), policy, { 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.authority_repeatability.stable).toBe(true);
expect(result.value.candidate_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?.status).toBe("unchanged");
expect(result.value.cross_side_blocked_reason).toBeNull();
}); });
it("blocks cross-side claims when a candidate has a flaky exit", async () => { it("blocks cross-side claims when a candidate has a flaky exit", async () => {
@@ -114,14 +120,14 @@ describe("paired process experiments", () => {
let candidateRun = 0; let candidateRun = 0;
const capturePort: ProcessCapturePort = { const capturePort: ProcessCapturePort = {
capture: (scenario) => { capture: (scenario) => {
let capture = structuredClone(base); let capture = cloneCapture(base);
if (scenario.executable === "/bin/candidate") { if (scenario.executable === "/bin/candidate") {
candidateRun += 1; candidateRun += 1;
if (candidateRun === 2) if (candidateRun === 2)
capture = { capture = parseProcessCapture({
...capture, ...capture,
exit: { code: 1, signal: null, reason: "exited" }, exit: { code: 1, signal: null, reason: "exited" },
}; });
} }
return Promise.resolve(ok(capture)); return Promise.resolve(ok(capture));
}, },
@@ -145,14 +151,14 @@ describe("paired process experiments", () => {
describe("paired process experiment comparisons", () => { describe("paired process experiment comparisons", () => {
it("distinguishes normalized timing variance from semantic output drift", () => { it("distinguishes normalized timing variance from semantic output drift", () => {
const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE); const base = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const early = { const early = parseProcessCapture({
...base, ...base,
frames: [{ sequence: 0, at_ms: 10, data: "ready" }], frames: [{ sequence: 0, at_ms: 10, data: "ready" }],
}; });
const late = { const late = parseProcessCapture({
...base, ...base,
frames: [{ sequence: 0, at_ms: 20, data: "ready" }], frames: [{ sequence: 0, at_ms: 20, data: "ready" }],
}; });
expect( expect(
analyzeProcessRepeatability([early, late], ["terminal"]), analyzeProcessRepeatability([early, late], ["terminal"]),
).toMatchObject({ ).toMatchObject({
@@ -160,10 +166,10 @@ describe("paired process experiment comparisons", () => {
classification: "timing_variance", classification: "timing_variance",
unstable_dimensions: ["terminal"], unstable_dimensions: ["terminal"],
}); });
const changed = { const changed = parseProcessCapture({
...base, ...base,
frames: [{ sequence: 0, at_ms: 20, data: "failed" }], frames: [{ sequence: 0, at_ms: 20, data: "failed" }],
}; });
expect( expect(
analyzeProcessRepeatability([early, changed], ["terminal"]), analyzeProcessRepeatability([early, changed], ["terminal"]),
).toMatchObject({ classification: "nondeterministic_output" }); ).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 () => { it("blocks full cross-side output when only a subset was repeatable", async () => {
const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE); const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const capturePort: ProcessCapturePort = { const capturePort: ProcessCapturePort = {
capture: () => Promise.resolve(ok(structuredClone(capture))), capture: () => Promise.resolve(ok(cloneCapture(capture))),
}; };
const subset = processPairedExperimentSchema.parse({ const subset = processPairedExperimentSchema.parse({
...experiment(), ...experiment(),
@@ -225,14 +231,16 @@ describe("paired process experiment freshness", () => {
: "2026-01-01T00:00:09.500Z"; : "2026-01-01T00:00:09.500Z";
captureIndex += 1; captureIndex += 1;
return Promise.resolve( return Promise.resolve(
ok({ ok(
...structuredClone(base), parseProcessCapture({
manifest: { ...structuredClone(base),
...base.manifest, manifest: {
started_at: completedAt, ...base.manifest,
completed_at: completedAt, started_at: completedAt,
}, completed_at: completedAt,
}), },
}),
),
); );
}, },
}; };
+29 -17
View File
@@ -26,8 +26,7 @@ export interface ProcessCapturePort {
): Promise<Result<ProcessCapture, ProcessCaptureError>>; ): Promise<Result<ProcessCapture, ProcessCaptureError>>;
} }
/** Repeatability evidence and an optional stable cross-side comparison. */ interface PairedProcessExperimentEvidence {
export interface PairedProcessExperimentResult {
readonly authority_runs: readonly ProcessCapture[]; readonly authority_runs: readonly ProcessCapture[];
readonly candidate_runs: readonly ProcessCapture[]; readonly candidate_runs: readonly ProcessCapture[];
readonly authority_repeatability: ReturnType< readonly authority_repeatability: ReturnType<
@@ -36,10 +35,21 @@ export interface PairedProcessExperimentResult {
readonly candidate_repeatability: ReturnType< readonly candidate_repeatability: ReturnType<
typeof analyzeProcessRepeatability 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 = { const productionCapturePort: ProcessCapturePort = {
capture: captureProcessScenario, capture: captureProcessScenario,
}; };
@@ -114,27 +124,29 @@ export const runPairedProcessExperiment = async (
); );
const authorityLatest = authorityRuns.value.at(-1); const authorityLatest = authorityRuns.value.at(-1);
const candidateLatest = candidateRuns.value.at(-1); const candidateLatest = candidateRuns.value.at(-1);
const crossSide = const crossSideOutcome =
stable && stable &&
allDimensionsRequired && allDimensionsRequired &&
authorityLatest !== undefined && authorityLatest !== undefined &&
candidateLatest !== undefined candidateLatest !== undefined
? compareProcessCaptures(authorityLatest, candidateLatest, { ? {
maxCaptureAgeMs: experiment.freshness_policy.max_capture_age_ms, cross_side: compareProcessCaptures(authorityLatest, candidateLatest, {
...(options.now === undefined ? {} : { now: options.now }), maxCaptureAgeMs: experiment.freshness_policy.max_capture_age_ms,
}) ...(options.now === undefined ? {} : { now: options.now }),
: null; }),
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({ return ok({
authority_runs: authorityRuns.value, authority_runs: authorityRuns.value,
candidate_runs: candidateRuns.value, candidate_runs: candidateRuns.value,
authority_repeatability: authorityRepeatability, authority_repeatability: authorityRepeatability,
candidate_repeatability: candidateRepeatability, candidate_repeatability: candidateRepeatability,
cross_side: crossSide, ...crossSideOutcome,
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.",
}); });
}; };
@@ -2,19 +2,19 @@ import { describe, expect, it } from "vitest";
import { import {
ProcessReactiveCoordinator, ProcessReactiveCoordinator,
type ProcessReactiveTimerHost, type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js"; } from "./ProcessReactiveCoordinator.js";
import { executeProcessReactiveEffects } from "../../../src/application/ProcessReactiveEffects.js"; import { executeProcessReactiveEffects } from "./ProcessReactiveEffects.js";
import { createProcessCaptureJournal } from "../../../src/application/ProcessCaptureJournal.js"; import { createProcessCaptureJournal } from "./ProcessCaptureJournal.js";
import { subscribeProcessReactiveObservations } from "../../../src/application/ProcessReactiveObservations.js"; import { subscribeProcessReactiveObservations } from "./ProcessReactiveObservations.js";
import type { import type {
FilesystemCheckpoint, FilesystemCheckpoint,
InteractionEvent, InteractionEvent,
TerminalFrame, TerminalFrame,
} from "../../../src/domain/processCapture.js"; } from "../domain/processCapture.js";
import { import {
processReactiveScenarioSchema, processReactiveScenarioSchema,
type ProcessReactiveScenario, type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js"; } from "../domain/processReactiveScenario.js";
const terminalTrigger = () => ({ const terminalTrigger = () => ({
kind: "terminal_text" as const, kind: "terminal_text" as const,
view: "decoded" as const, view: "decoded" as const,
@@ -2,14 +2,14 @@ import { describe, expect, it } from "vitest";
import { import {
ProcessReactiveCoordinator, ProcessReactiveCoordinator,
type ProcessReactiveTimerHost, type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js"; } from "./ProcessReactiveCoordinator.js";
import { unsupportedProcessReactiveFeatures } from "../../../src/application/ProcessReactiveEffects.js"; import { unsupportedProcessReactiveFeatures } from "./ProcessReactiveEffects.js";
import { createProcessObservation } from "../../../src/domain/processObservation.js"; import { createProcessObservation } from "../domain/processObservation.js";
import type { ProcessReactiveEffectResult } from "../../../src/domain/processReactiveRuntime.js"; import type { ProcessReactiveEffectResult } from "../domain/processReactiveRuntime.js";
import { import {
processReactiveScenarioSchema, processReactiveScenarioSchema,
type ProcessReactiveScenario, type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js"; } from "../domain/processReactiveScenario.js";
const terminalTrigger = () => ({ const terminalTrigger = () => ({
kind: "terminal_text" as const, kind: "terminal_text" as const,
view: "decoded" as const, view: "decoded" as const,
@@ -2,12 +2,12 @@ import { describe, expect, it } from "vitest";
import { import {
ProcessReactiveCoordinator, ProcessReactiveCoordinator,
type ProcessReactiveTimerHost, type ProcessReactiveTimerHost,
} from "../../../src/application/ProcessReactiveCoordinator.js"; } from "./ProcessReactiveCoordinator.js";
import { createProcessObservation } from "../../../src/domain/processObservation.js"; import { createProcessObservation } from "../domain/processObservation.js";
import { import {
processReactiveScenarioSchema, processReactiveScenarioSchema,
type ProcessReactiveScenario, type ProcessReactiveScenario,
} from "../../../src/domain/processReactiveScenario.js"; } from "../domain/processReactiveScenario.js";
const terminalTrigger = () => ({ const terminalTrigger = () => ({
kind: "terminal_text" as const, kind: "terminal_text" as const,
view: "decoded" as const, view: "decoded" as const,
+14 -10
View File
@@ -167,13 +167,17 @@ export const startProcessReactiveHarness = (options: {
/** Project internal reducer state into the stable Process Capture shape. */ /** Project internal reducer state into the stable Process Capture shape. */
export const projectProcessReactiveRun = ( export const projectProcessReactiveRun = (
harness: ProcessReactiveHarness | undefined, harness: ProcessReactiveHarness | undefined,
): ProcessCapture["reactive_run"] => ): ProcessCapture["reactive_run"] => {
harness === undefined if (harness === undefined) return null;
? null const snapshot = harness.coordinator.snapshot;
: { const completion =
status: harness.coordinator.snapshot.status, snapshot.status === "running"
outcome: harness.coordinator.snapshot.outcome, ? { status: snapshot.status, outcome: null }
active_state: harness.coordinator.snapshot.active_state, : { status: snapshot.status, outcome: snapshot.outcome };
transitions: harness.coordinator.snapshot.transitions, return {
controls: harness.controls, ...completion,
}; active_state: snapshot.active_state,
transitions: snapshot.transitions,
controls: harness.controls,
};
};
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { createProgressReporter } from "../../../src/application/ProgressReporter.js"; import { createProgressReporter } from "./ProgressReporter.js";
describe("progress reporter", () => { describe("progress reporter", () => {
it("preserves monotonic order, rate bounds intermediate updates, and always emits terminal state", async () => { it("preserves monotonic order, rate bounds intermediate updates, and always emits terminal state", async () => {
@@ -1,21 +1,21 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js"; import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import { import {
buildReconstructionObligationLedgerEvidenceValidated, buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest, resolveReconstructionObligationLedgerRequest,
} from "../../../src/application/ReconstructionObligationLedgerService.js"; } from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js"; import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js"; import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../../../src/domain/processCapture.js"; import { processCaptureSchema } from "../domain/processCapture.js";
import { import {
reconstructionObligationLedgerPageSchema, reconstructionObligationLedgerPageSchema,
type ReconstructionObligationLedgerInput, type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedgerPage, type ReconstructionObligationLedgerPage,
type ReviewedReconstructionObligation, type ReviewedReconstructionObligation,
} from "../../../src/domain/reconstructionObligationLedgerSchemas.js"; } from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) => const proofEvidence = (id: string) =>
createEvidence( createEvidence(
@@ -1,22 +1,22 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "../../../src/application/ProcessEvidence.js"; import { PROCESS_PROVIDER } from "./ProcessEvidence.js";
import { import {
buildReconstructionObligationLedgerEvidenceValidated, buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest, resolveReconstructionObligationLedgerRequest,
} from "../../../src/application/ReconstructionObligationLedgerService.js"; } from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../../../src/contracts/processCaptureExample.js"; import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../contracts/processCaptureExample.js";
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js"; import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../../../src/domain/processCapture.js"; import { processCaptureSchema } from "../domain/processCapture.js";
import { import {
reconstructionObligationLedgerPageSchema, reconstructionObligationLedgerPageSchema,
serializeReconstructionObligationLedger, serializeReconstructionObligationLedger,
type ReconstructionObligationLedgerInput, type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedgerPage, type ReconstructionObligationLedgerPage,
type ReviewedReconstructionObligation, type ReviewedReconstructionObligation,
} from "../../../src/domain/reconstructionObligationLedgerSchemas.js"; } from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) => const proofEvidence = (id: string) =>
createEvidence( createEvidence(
@@ -27,18 +27,29 @@ interface RuntimeProbeFailure {
readonly stderr: string; readonly stderr: string;
} }
/** One lexical PATH candidate and its canonical executable probe result. */ interface RuntimeExecutableIdentity {
interface RuntimeExecutableDiagnostic {
readonly tool: RuntimeToolName; readonly tool: RuntimeToolName;
readonly lexical_path: string; readonly lexical_path: string;
readonly canonical_path: string; readonly canonical_path: string;
readonly path_index: number | null; readonly path_index: number | null;
readonly selection: "rea-launcher" | "path-primary" | "path-shadowed"; 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. */ /** Runtime identities observed under one exact effective environment. */
export interface RuntimeExecutableInventory { export interface RuntimeExecutableInventory {
readonly launcher_node: string; readonly launcher_node: string;
@@ -148,16 +159,21 @@ const probeCandidate = async (
): Promise<RuntimeExecutableDiagnostic> => { ): Promise<RuntimeExecutableDiagnostic> => {
const canonical = await canonicalPath(candidate.path); const canonical = await canonicalPath(candidate.path);
const result = await executeVersion(candidate.path, timeoutMs, effectivePath); const result = await executeVersion(candidate.path, timeoutMs, effectivePath);
return { const identity = {
tool: candidate.tool, tool: candidate.tool,
lexical_path: candidate.path, lexical_path: candidate.path,
canonical_path: canonical, canonical_path: canonical,
path_index: candidate.pathIndex, path_index: candidate.pathIndex,
selection: candidate.selection, 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 = type VersionResult =
+2 -2
View File
@@ -74,8 +74,8 @@ export class SessionProviderRouter {
private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime, private readonly runtime: SingleProviderRuntime | SelectableProviderRuntime,
) {} ) {}
/** Preserve the existing provider/factory seam used by focused embedders. */ /** Create routing for an embedding backed by one fixed provider or factory. */
static legacy( static single(
provider: AnalysisProvider | AnalysisClientFactory, provider: AnalysisProvider | AnalysisClientFactory,
options: { options: {
readonly resolveAnalysisProfile?: ( readonly resolveAnalysisProfile?: (
@@ -1,13 +1,10 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import { runCapabilityStatus, runProviderStatus } from "./DirectAnalysis.js";
runCapabilityStatus, import { projectDoctorReport } from "./DoctorProjection.js";
runProviderStatus, import { runDoctor, type DoctorHost } from "./Doctor.js";
} from "../../../src/application/DirectAnalysis.js"; import { CATALOG_IDENTITY } from "../catalogIdentity.js";
import { projectDoctorReport } from "../../../src/application/DoctorProjection.js"; import { PRODUCT_IDENTITY } from "../identity.js";
import { runDoctor, type DoctorHost } from "../../../src/application/Doctor.js";
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
import { PRODUCT_IDENTITY } from "../../../src/identity.js";
const doctorHost = (): DoctorHost => ({ const doctorHost = (): DoctorHost => ({
platform: "darwin", platform: "darwin",
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { BrowserScenarioSecrets } from "../../../src/browser/BrowserScenarioSecrets.js"; import { BrowserScenarioSecrets } from "./BrowserScenarioSecrets.js";
import { browserScenarioSchema } from "../../../src/domain/browserScenario.js"; import { browserScenarioSchema } from "../domain/browserScenario.js";
const secret = (secret_id: string) => ({ source: "secret", secret_id }); const secret = (secret_id: string) => ({ source: "secret", secret_id });
const literal = (value: string) => ({ const literal = (value: string) => ({
+2 -4
View File
@@ -5,6 +5,7 @@ import type {
BrowserScenarioUrl, BrowserScenarioUrl,
BrowserScenarioValue, BrowserScenarioValue,
} from "../domain/browserScenario.js"; } from "../domain/browserScenario.js";
import type { BrowserStorageValueFingerprint } from "../domain/browserScenarioCaptureValues.js";
const REDACTION_PREFIX = "[REDACTED:"; const REDACTION_PREFIX = "[REDACTED:";
@@ -53,10 +54,7 @@ export class BrowserScenarioSecrets {
return output; return output;
} }
fingerprint(value: string): { fingerprint(value: string): BrowserStorageValueFingerprint {
readonly value_state: "hashed" | "redacted-secret";
readonly value_sha256: string | null;
} {
for (const secret of this.values.values()) for (const secret of this.values.values())
if (secret !== "" && value.includes(secret)) if (secret !== "" && value.includes(secret))
return { value_state: "redacted-secret", value_sha256: null }; 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"; } from "../domain/browserScenario.js";
import { import {
browserScenarioCaptureSchema, browserScenarioCaptureSchema,
browserScenarioCompletenessSchema, classifyBrowserScenarioCompleteness,
browserScenarioStepSchema, browserScenarioStepSchema,
browserStepArtifactsSchema, browserStepArtifactsSchema,
type BrowserScenarioCapture, type BrowserScenarioCapture,
type BrowserScenarioCompleteness, type BrowserScenarioCompleteness,
type BrowserScenarioCompletenessSection,
type BrowserScenarioStep, type BrowserScenarioStep,
type BrowserScenarioStepOutcome,
type BrowserStepArtifacts, type BrowserStepArtifacts,
} from "../domain/browserScenarioCapture.js"; } from "../domain/browserScenarioCapture.js";
import { import {
@@ -51,6 +53,14 @@ export const PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY: ProviderIdentity =
}); });
type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number]; type SnapshotKind = BrowserScenario["capture"]["after_each_step"][number];
const SNAPSHOT_KINDS = [
"screenshot",
"dom",
"accessibility",
"url",
"history",
"storage",
] as const satisfies readonly SnapshotKind[];
const requestedForStep = ( const requestedForStep = (
scenario: BrowserScenario, scenario: BrowserScenario,
@@ -83,40 +93,29 @@ const stepCompleteness = (
artifacts: BrowserStepArtifacts, artifacts: BrowserStepArtifacts,
status: BrowserScenarioStep["status"], status: BrowserScenarioStep["status"],
): BrowserScenarioCompleteness => { ): BrowserScenarioCompleteness => {
const missing = Object.entries(artifacts) const missing: BrowserScenarioCompletenessSection[] = SNAPSHOT_KINDS.filter(
.filter(([, state]) => state.state === "missing") (section) => artifacts[section].state === "missing",
.map(([section]) => section); );
const truncated = Object.entries(artifacts) const truncated = SNAPSHOT_KINDS.filter(
.filter(([, state]) => state.state === "truncated") (section) => artifacts[section].state === "truncated",
.map(([section]) => section); );
if (status !== "completed") missing.push("action"); if (status !== "completed") missing.push("action");
const condition = return classifyBrowserScenarioCompleteness(missing, truncated);
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(),
});
}; };
const createStep = (input: { const createStep = (
readonly stepIndex: number; input: {
readonly stepId: string; readonly stepIndex: number;
readonly action: string; readonly stepId: string;
readonly status: BrowserScenarioStep["status"]; readonly action: string;
readonly elapsedMs: number; readonly elapsedMs: number;
readonly beforeUrl: string; readonly beforeUrl: string;
readonly afterUrl: string; readonly afterUrl: string;
readonly error: string | null; readonly eventStart: number;
readonly eventStart: number; readonly eventEnd: number;
readonly eventEnd: number; readonly artifacts: BrowserStepArtifacts;
readonly artifacts: BrowserStepArtifacts; } & BrowserScenarioStepOutcome,
}): BrowserScenarioStep => ): BrowserScenarioStep =>
browserScenarioStepSchema.parse({ browserScenarioStepSchema.parse({
step_index: input.stepIndex, step_index: input.stepIndex,
step_id: input.stepId, step_id: input.stepId,
@@ -207,11 +206,12 @@ const executeStep = async (input: {
const actionStartedAt = Date.now(); const actionStartedAt = Date.now();
session.setStep(stepIndex); session.setStep(stepIndex);
const requestCancelled = (): boolean => signal?.aborted === true; const requestCancelled = (): boolean => signal?.aborted === true;
let status: BrowserScenarioStep["status"] = "completed"; let outcome: BrowserScenarioStepOutcome = {
let error: string | null = null; status: "completed",
error: null,
};
if (requestCancelled()) { if (requestCancelled()) {
status = "cancelled"; outcome = { status: "cancelled", error: "scenario request cancelled" };
error = "scenario request cancelled";
} else { } else {
try { try {
const elapsed = Date.now() - startedAt; const elapsed = Date.now() - startedAt;
@@ -219,16 +219,18 @@ const executeStep = async (input: {
if (remaining <= 0) throw new Error("Scenario duration limit reached"); if (remaining <= 0) throw new Error("Scenario duration limit reached");
await session.perform(action, remaining, signal); await session.perform(action, remaining, signal);
} catch (cause: unknown) { } catch (cause: unknown) {
status = requestCancelled() ? "cancelled" : "failed"; outcome = {
error = session.redactError(cause); status: requestCancelled() ? "cancelled" : "failed",
error: session.redactError(cause),
};
} }
} }
const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt); const remaining = scenario.limits.max_duration_ms - (Date.now() - startedAt);
const artifacts = const artifacts =
status === "cancelled" || remaining <= 0 outcome.status === "cancelled" || remaining <= 0
? unavailableArtifacts( ? unavailableArtifacts(
requested, requested,
status === "cancelled" outcome.status === "cancelled"
? "scenario request cancelled" ? "scenario request cancelled"
: "scenario duration limit reached", : "scenario duration limit reached",
) )
@@ -237,11 +239,10 @@ const executeStep = async (input: {
stepIndex, stepIndex,
stepId: action.step_id, stepId: action.step_id,
action: action.action, action: action.action,
status, ...outcome,
elapsedMs: Date.now() - actionStartedAt, elapsedMs: Date.now() - actionStartedAt,
beforeUrl, beforeUrl,
afterUrl: session.currentUrl(), afterUrl: session.currentUrl(),
error,
eventStart, eventStart,
eventEnd: session.lastEventSequence(), eventEnd: session.lastEventSequence(),
artifacts, artifacts,
@@ -261,18 +262,7 @@ const globalCompleteness = (
); );
truncated.push(...session.eventTruncationSections()); truncated.push(...session.eventTruncationSections());
if (session.mode === "connect") missing.push("events"); if (session.mode === "connect") missing.push("events");
const status = return classifyBrowserScenarioCompleteness(missing, truncated);
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(),
});
}; };
const runScenario = async ( const runScenario = async (
+32 -12
View File
@@ -241,22 +241,31 @@ export class PlaywrightScenarioEvents {
} }
private request(kind: "request" | "request-failed", request: Request): void { private request(kind: "request" | "request-failed", request: Request): void {
this.push({ const observation = {
kind,
method: this.secrets.redact(request.method()).slice(0, 32), method: this.secrets.redact(request.method()).slice(0, 32),
url: this.safeUrl(request.url()), url: this.safeUrl(request.url()),
resource_type: this.secrets.redact(request.resourceType()).slice(0, 64), resource_type: this.secrets.redact(request.resourceType()).slice(0, 64),
status: null,
header_names: Object.keys(request.headers()) header_names: Object.keys(request.headers())
.map((name) => this.secrets.redact(name).slice(0, 256)) .map((name) => this.secrets.redact(name).slice(0, 256))
.sort() .sort()
.slice(0, 256), .slice(0, 256),
failure: };
kind === "request-failed" if (kind === "request-failed") {
? this.secrets this.push({
.redact(request.failure()?.errorText ?? "unknown") ...observation,
.slice(0, 1_024) kind,
: null, 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 { ): void {
const bytes = Buffer.byteLength(payload); const bytes = Buffer.byteLength(payload);
const isText = typeof payload === "string"; 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({ this.push({
kind, kind,
url, url,
payload_type: isText ? "text" : "binary", payload_type: "text",
payload_bytes: bytes, payload_bytes: bytes,
payload_text: text, payload_text: text,
truncated: isText && text !== null && text.length < payload.length, truncated: text.length < payload.length,
}); });
} }
@@ -2,11 +2,12 @@ import { deflateSync } from "node:zlib";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { comparePngScreenshots } from "../../../src/browser/PngVisualDiff.js"; import { comparePngScreenshots } from "./PngVisualDiff.js";
import { import {
compareWebScreenshotsInputSchema, compareWebScreenshotsInputSchema,
createWebScreenshotArtifact, createWebScreenshotArtifact,
} from "../../../src/domain/webScreenshot.js"; webScreenshotDiffSchema,
} from "../domain/webScreenshot.js";
describe("PNG visual diff", () => { describe("PNG visual diff", () => {
it("reports exact changed-pixel and channel metrics", () => { it("reports exact changed-pixel and channel metrics", () => {
@@ -60,6 +61,26 @@ describe("PNG visual diff", () => {
), ),
).toThrow("oversized PNG"); ).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[]) => const artifact = (width: number, height: number, pixels: readonly number[]) =>
+15 -5
View File
@@ -50,19 +50,29 @@ export const comparePngScreenshots = (
if (changed) changedPixels += 1; if (changed) changedPixels += 1;
} }
const pixels = before.width * before.height; const pixels = before.width * before.height;
return { const context = {
schema_version: 1, schema_version: 1 as const,
status: changedPixels === 0 ? "identical" : "different",
before: dimensions(before), before: dimensions(before),
after: dimensions(after), after: dimensions(after),
channel_threshold: input.channel_threshold, channel_threshold: input.channel_threshold,
compared_pixels: pixels, compared_pixels: pixels,
changed_pixels: changedPixels,
changed_ratio: changedPixels / pixels,
maximum_channel_delta: maximumDelta, maximum_channel_delta: maximumDelta,
mean_absolute_channel_delta: totalDelta / (pixels * 4), mean_absolute_channel_delta: totalDelta / (pixels * 4),
limitations: limitations(), 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 = ( const decodePng = (
@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";
import { import {
boundedSensitiveText, boundedSensitiveText,
redactSensitiveText, redactSensitiveText,
} from "../../../src/browser/SensitiveTextCapture.js"; } from "./SensitiveTextCapture.js";
describe("sensitive console text", () => { describe("sensitive console text", () => {
it("redacts assignments, bearer credentials, and JWT-shaped values", () => { it("redacts assignments, bearer credentials, and JWT-shaped values", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js"; import { parseConfig } from "./config.js";
describe("browser runtime configuration", () => { describe("browser runtime configuration", () => {
it("builds an exact-origin browser observation ceiling only when enabled", () => { it("builds an exact-origin browser observation ceiling only when enabled", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js"; import { parseConfig } from "./config.js";
describe("capability flags", () => { describe("capability flags", () => {
it("rejects values outside the exact true/false boundary", () => { it("rejects values outside the exact true/false boundary", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js"; import { parseConfig } from "./config.js";
describe("passive browser observation policy", () => { describe("passive browser observation policy", () => {
it("requires both endpoint and origin scopes when enabled", () => { it("requires both endpoint and origin scopes when enabled", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js"; import { parseConfig } from "./config.js";
describe("process capture configuration", () => { describe("process capture configuration", () => {
it("parses all authority required by enabled capture", () => { it("parses all authority required by enabled capture", () => {
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { parseConfig } from "../../../src/config.js"; import { parseConfig } from "./config.js";
describe("runtime configuration", () => { describe("runtime configuration", () => {
it("allows target-free startup and defaults to Hopper's documented launcher", () => { it("allows target-free startup and defaults to Hopper's documented launcher", () => {
@@ -6,27 +6,24 @@ import {
OFFICIAL_TOOL_CONTRACTS, OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS, SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS, TOOL_CONTRACTS,
} from "../../../src/contracts/toolContracts.js"; } from "./toolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/nativeToolContracts.js"; import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../../../src/contracts/artifactToolContracts.js"; import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "../../../src/contracts/managedToolContracts.js"; import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js"; import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js"; import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "../../../src/contracts/browserScenarioToolContracts.js"; import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "./browserScenarioToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../../../src/contracts/electronToolContracts.js"; import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../../../src/contracts/javascriptRuntimeObservationToolContracts.js"; import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "./javascriptRuntimeObservationToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js"; import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
import { import {
enhancedOutputSchemas, enhancedOutputSchemas,
managedOutputSchemas, managedOutputSchemas,
managedWorkflowOutputSchemas, managedWorkflowOutputSchemas,
officialOutputSchemas, officialOutputSchemas,
sessionOutputSchemas, sessionOutputSchemas,
} from "../../../src/contracts/toolOutputSchemas.js"; } from "./toolOutputSchemas.js";
import { import { annotationsFromEffects, TOOL_EFFECTS } from "./toolEffects.js";
annotationsFromEffects,
TOOL_EFFECTS,
} from "../../../src/contracts/toolEffects.js";
const convertContractJsonSchema = (schema: z.ZodType) => const convertContractJsonSchema = (schema: z.ZodType) =>
z.toJSONSchema(schema, { z.toJSONSchema(schema, {
+2 -2
View File
@@ -3,7 +3,7 @@ import { createEvidence } from "../domain/evidence.js";
import { jsonValueSchema } from "../domain/jsonValue.js"; import { jsonValueSchema } from "../domain/jsonValue.js";
import { import {
compareProcessCaptures, compareProcessCaptures,
processCaptureSchema, parseProcessCapture,
} from "../domain/processCapture.js"; } from "../domain/processCapture.js";
import { FUNCTION_COMPARISON_EXAMPLE } from "./functionComparisonExample.js"; import { FUNCTION_COMPARISON_EXAMPLE } from "./functionComparisonExample.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js"; import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "./processCaptureExample.js";
@@ -46,7 +46,7 @@ const PROCESS_PROVIDER = {
name: "REA deterministic process harness", name: "REA deterministic process harness",
version: "3", version: "3",
} as const; } as const;
const capture = processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE); const capture = parseProcessCapture(EMPTY_PROCESS_CAPTURE_EXAMPLE);
const captureEvidence = (scenario: string) => const captureEvidence = (scenario: string) =>
createEvidence(undefined, PROCESS_PROVIDER, { createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture/v4", predicateType: "rea.process-capture/v4",
@@ -1,10 +1,7 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { import { PROMPT_CONTRACTS, renderGuidedPrompt } from "./promptContracts.js";
PROMPT_CONTRACTS, import { TOOL_CONTRACTS } from "./toolContracts.js";
renderGuidedPrompt,
} from "../../../src/contracts/promptContracts.js";
import { TOOL_CONTRACTS } from "../../../src/contracts/toolContracts.js";
const promptNames = [ const promptNames = [
"investigate_feature", "investigate_feature",
@@ -5,14 +5,14 @@ import {
OFFICIAL_TOOL_CONTRACTS, OFFICIAL_TOOL_CONTRACTS,
SESSION_TOOL_CONTRACTS, SESSION_TOOL_CONTRACTS,
TOOL_CONTRACTS, TOOL_CONTRACTS,
} from "../../../src/contracts/toolContracts.js"; } from "./toolContracts.js";
import { ARTIFACT_TOOL_CONTRACTS } from "../../../src/contracts/artifactToolContracts.js"; import { ARTIFACT_TOOL_CONTRACTS } from "./artifactToolContracts.js";
import { MANAGED_TOOL_CONTRACTS } from "../../../src/contracts/managedToolContracts.js"; import { MANAGED_TOOL_CONTRACTS } from "./managedToolContracts.js";
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../../../src/contracts/managedWorkflowToolContracts.js"; import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "./managedWorkflowToolContracts.js";
import { NATIVE_TOOL_CONTRACTS } from "../../../src/contracts/nativeToolContracts.js"; import { NATIVE_TOOL_CONTRACTS } from "./nativeToolContracts.js";
import { BROWSER_TOOL_CONTRACTS } from "../../../src/contracts/browserToolContracts.js"; import { BROWSER_TOOL_CONTRACTS } from "./browserToolContracts.js";
import { ELECTRON_TOOL_CONTRACTS } from "../../../src/contracts/electronToolContracts.js"; import { ELECTRON_TOOL_CONTRACTS } from "./electronToolContracts.js";
import { APPLICATION_TOOL_CONTRACTS } from "../../../src/contracts/applicationToolContracts.js"; import { APPLICATION_TOOL_CONTRACTS } from "./applicationToolContracts.js";
describe("tool contract inventory", () => { describe("tool contract inventory", () => {
it("publishes the canonical analysis and session tool inventory", () => { it("publishes the canonical analysis and session tool inventory", () => {
@@ -1,30 +1,17 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { traceJavaScriptSemanticsRequestSchema } from "../../../src/contracts/applicationWorkflowInputContracts.js"; import { traceJavaScriptSemanticsRequestSchema } from "./applicationWorkflowInputContracts.js";
import { buildCapabilityInventory } from "../../../src/application/CapabilityInventory.js";
import { import {
artifactInspectionInputSchema, artifactInspectionInputSchema,
artifactInventoryInputSchema, artifactInventoryInputSchema,
} from "../../../src/contracts/artifactToolContracts.js"; } from "./artifactToolContracts.js";
import { JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE } from "./javascriptApplicationWorkflowExamples.js";
import { import {
MANAGED_WORKFLOW_TOOL_CONTRACTS, MANAGED_WORKFLOW_TOOL_CONTRACTS,
compareManagedMembersReferenceInputSchema,
managedApplicationGraphReferenceInputSchema, managedApplicationGraphReferenceInputSchema,
managedNativeVerificationReferenceInputSchema, managedNativeVerificationReferenceInputSchema,
compareManagedMembersReferenceInputSchema, } from "./managedWorkflowToolContracts.js";
} 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";
const EVIDENCE_ID = `ev_${"a".repeat(64)}`; const EVIDENCE_ID = `ev_${"a".repeat(64)}`;
@@ -36,22 +23,24 @@ const workflowInput = (name: string) => {
return contract.examples[0].input; return contract.examples[0].input;
}; };
describe("contract validation boundaries", () => { describe("workflow input contracts", () => {
it("rejects missing and duplicated application Evidence references", () => { it("rejects missing and duplicated application Evidence references", () => {
const query = { const query = {
seed: { kind: "literal" as const, value: "renderer" }, seed: { kind: "literal" as const, value: "renderer" },
direction: "callers" as const, direction: "callers" as const,
}; };
const missing = traceJavaScriptSemanticsRequestSchema.safeParse({ query }); expect(
expect(missing.success).toBe(false); traceJavaScriptSemanticsRequestSchema.safeParse({ query }).success,
).toBe(false);
const evidence = JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application; const evidence = JAVASCRIPT_FEATURE_TRACE_FULL_EVIDENCE_EXAMPLE.application;
const duplicated = traceJavaScriptSemanticsRequestSchema.safeParse({ expect(
application: evidence, traceJavaScriptSemanticsRequestSchema.safeParse({
application_evidence_id: evidence.evidence_id, application: evidence,
query, application_evidence_id: evidence.evidence_id,
}); query,
expect(duplicated.success).toBe(false); }).success,
).toBe(false);
}); });
it("rejects managed Evidence identity collisions", () => { it("rejects managed Evidence identity collisions", () => {
@@ -103,54 +92,4 @@ describe("contract validation boundaries", () => {
expect(artifactInventoryInputSchema.safeParse(input).success).toBe(false); expect(artifactInventoryInputSchema.safeParse(input).success).toBe(false);
expect(artifactInspectionInputSchema.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,
);
});
}); });
+10 -6
View File
@@ -28,12 +28,16 @@ export const analysisErrorRemediationAction = (
return "Check that the unknown_id belongs to this session, then retry."; return "Check that the unknown_id belongs to this session, then retry.";
if (error instanceof ReplayPlanStaleError) if (error instanceof ReplayPlanStaleError)
return "Review the rebuilt replay plan and explicitly approve its new digest."; return "Review the rebuilt replay plan and explicitly approve its new digest.";
if (error instanceof PermissionRequiredError) if (error instanceof PermissionRequiredError) {
return error.restartRequired switch (error.remediation) {
? "Add the exact missing scope to the administrator configuration, then restart the registered MCP server or client." case "configure":
: error.elicitationSupported return "Add the exact missing scope beneath the administrator ceiling, then retry.";
? "Approve the exact missing scope, then retry the operation." case "elicit":
: "Add the exact missing scope beneath the administrator ceiling, then retry."; 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); return analysisErrorUserMessage(error);
}; };
+3 -2
View File
@@ -50,9 +50,10 @@ export const projectAnalysisError = (
remediation: { remediation: {
action: analysisErrorRemediationAction(error), action: analysisErrorRemediationAction(error),
restart_required: restart_required:
error instanceof PermissionRequiredError && error.restartRequired, error instanceof PermissionRequiredError &&
error.remediation === "restart",
...(error instanceof PermissionRequiredError ...(error instanceof PermissionRequiredError
? { elicitation_supported: error.elicitationSupported } ? { elicitation_supported: error.remediation === "elicit" }
: {}), : {}),
}, },
...(details === undefined ? {} : { details }), ...(details === undefined ? {} : { details }),
@@ -4,7 +4,7 @@ import {
analysisProfileSchema, analysisProfileSchema,
analysisProfilesEqual, analysisProfilesEqual,
createAnalysisProfile, createAnalysisProfile,
} from "../../../src/domain/analysisProfile.js"; } from "./analysisProfile.js";
const PROVIDER = { const PROVIDER = {
id: "fixture", id: "fixture",
+26
View File
@@ -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" },
);
+73
View File
@@ -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,
);
});
});
+61
View File
@@ -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;
};
+82
View File
@@ -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);
});
});
@@ -1,10 +1,5 @@
import { describe, expect, it } from "vitest"; 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 { import {
browserEndpointSchema, browserEndpointSchema,
browserOriginSchema, browserOriginSchema,
@@ -12,8 +7,8 @@ import {
isLiteralLoopbackHostname, isLiteralLoopbackHostname,
listBrowserTargetsInputSchema, listBrowserTargetsInputSchema,
sanitizeBrowserUrl, sanitizeBrowserUrl,
} from "../../../src/domain/browserObservation.js"; } from "./browserObservation.js";
import { captureWebScreenshotInputSchema } from "../../../src/domain/webScreenshot.js"; import { captureWebScreenshotInputSchema } from "./webScreenshot.js";
describe("browser observation contracts", () => { describe("browser observation contracts", () => {
it("normalizes exact HTTP origins without accepting broader URL scopes", () => { it("normalizes exact HTTP origins without accepting broader URL scopes", () => {
@@ -57,46 +52,6 @@ describe("browser observation contracts", () => {
expect(isLiteralLoopbackHostname(hostname), hostname).toBe(false); 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", () => { it("applies conservative bounded defaults to public tool input", () => {
expect( expect(
listBrowserTargetsInputSchema.parse({ listBrowserTargetsInputSchema.parse({
@@ -194,58 +149,6 @@ describe("browser observation sensitive surfaces and retention", () => {
).toBe(true); ).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", () => { it("removes credentials, query values, and fragments from observed URLs", () => {
expect( expect(
sanitizeBrowserUrl( sanitizeBrowserUrl(
+106
View File
@@ -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);
});
+3
View File
@@ -7,14 +7,17 @@ import {
} from "./browserScenarioCaptureValues.js"; } from "./browserScenarioCaptureValues.js";
export { export {
classifyBrowserScenarioCompleteness,
browserScenarioCompletenessSchema, browserScenarioCompletenessSchema,
browserScenarioEventSchema, browserScenarioEventSchema,
browserScenarioStepSchema, browserScenarioStepSchema,
browserStepArtifactsSchema, browserStepArtifactsSchema,
captureStateSchema, captureStateSchema,
type BrowserScenarioCompleteness, type BrowserScenarioCompleteness,
type BrowserScenarioCompletenessSection,
type BrowserScenarioEvent, type BrowserScenarioEvent,
type BrowserScenarioStep, type BrowserScenarioStep,
type BrowserScenarioStepOutcome,
type BrowserStepArtifacts, type BrowserStepArtifacts,
} from "./browserScenarioCaptureValues.js"; } from "./browserScenarioCaptureValues.js";
+150 -61
View File
@@ -65,25 +65,49 @@ const historySchema = z.strictObject({
.max(256), .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), name: z.string().max(1_024),
value_state: z.enum(["hashed", "redacted-secret"]), domain: z.string().max(2_048),
value_sha256: digestSchema.nullable(), path: z.string().max(4_096),
}); secure: z.boolean(),
http_only: z.boolean(),
same_site: z.enum(["Strict", "Lax", "None"]),
};
const storageSnapshotSchema = z.strictObject({ const storageSnapshotSchema = z.strictObject({
cookies: z cookies: z
.array( .array(
z.strictObject({ z.discriminatedUnion("value_state", [
name: z.string().max(1_024), z.strictObject({ ...cookieShape, ...hashedStorageValueShape }),
domain: z.string().max(2_048), z.strictObject({ ...cookieShape, ...redactedStorageValueShape }),
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(),
}),
) )
.max(512), .max(512),
local_storage: z.array(storageValueSchema).max(512), local_storage: z.array(storageValueSchema).max(512),
@@ -106,8 +130,22 @@ const eventBase = {
}; };
const eventUrl = sanitizedBrowserUrlSchema.nullable(); 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({ z.strictObject({
...eventBase, ...eventBase,
kind: z.literal("console"), kind: z.literal("console"),
@@ -122,14 +160,22 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
stack: z.string().max(262_144).nullable(), stack: z.string().max(262_144).nullable(),
}), }),
z.strictObject({ z.strictObject({
...eventBase, ...networkEventShape,
kind: z.enum(["request", "response", "request-failed"]), kind: z.literal("request"),
method: z.string().min(1).max(32), status: z.null(),
url: sanitizedBrowserUrlSchema, failure: z.null(),
resource_type: z.string().min(1).max(64), }),
status: z.number().int().min(100).max(599).nullable(), z.strictObject({
header_names: z.array(z.string().max(256)).max(256), ...networkEventShape,
failure: z.string().max(1_024).nullable(), 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({ z.strictObject({
...eventBase, ...eventBase,
@@ -137,13 +183,14 @@ export const browserScenarioEventSchema = z.discriminatedUnion("kind", [
url: sanitizedBrowserUrlSchema, url: sanitizedBrowserUrlSchema,
}), }),
z.strictObject({ z.strictObject({
...eventBase, ...webSocketFrameShape,
kind: z.enum(["websocket-frame-sent", "websocket-frame-received"]), payload_type: z.literal("text"),
url: sanitizedBrowserUrlSchema, payload_text: z.string().max(65_536),
payload_type: z.enum(["text", "binary"]), }),
payload_bytes: z.number().int().min(0), z.strictObject({
payload_text: z.string().max(65_536).nullable(), ...webSocketFrameShape,
truncated: z.boolean(), payload_type: z.literal("binary"),
payload_text: z.null(),
}), }),
z.strictObject({ z.strictObject({
...eventBase, ...eventBase,
@@ -182,50 +229,92 @@ const completenessSectionSchema = z.enum([
"popups", "popups",
"websockets", "websockets",
]); ]);
export type BrowserScenarioCompletenessSection = z.infer<
typeof completenessSectionSchema
>;
export const browserScenarioCompletenessSchema = z export const browserScenarioCompletenessSchema = z.discriminatedUnion(
.strictObject({ "status",
status: z.enum(["complete", "incomplete", "truncated"]), [
equality_eligible: z.boolean(), z.strictObject({
missing_sections: z.array(completenessSectionSchema), status: z.literal("complete"),
truncated_sections: z.array(completenessSectionSchema), equality_eligible: z.literal(true),
}) missing_sections: z.tuple([]),
.superRefine((value, context) => { truncated_sections: z.tuple([]),
const expectedStatus = }),
value.truncated_sections.length > 0 z.strictObject({
? "truncated" status: z.literal("incomplete"),
: value.missing_sections.length > 0 equality_eligible: z.literal(false),
? "incomplete" missing_sections: z.array(completenessSectionSchema).min(1),
: "complete"; truncated_sections: z.tuple([]),
if (value.status !== expectedStatus) }),
context.addIssue({ z.strictObject({
code: "custom", status: z.literal("truncated"),
path: ["status"], equality_eligible: z.literal(false),
message: "Completeness status does not match section accounting", missing_sections: z.array(completenessSectionSchema),
}); truncated_sections: z.array(completenessSectionSchema).min(1),
if (value.equality_eligible !== (expectedStatus === "complete")) }),
context.addIssue({ ],
code: "custom", );
path: ["equality_eligible"],
message: "Missing or truncated evidence is never equality-eligible",
});
});
export type BrowserScenarioCompleteness = z.infer< export type BrowserScenarioCompleteness = z.infer<
typeof browserScenarioCompletenessSchema 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_index: z.number().int().min(0),
step_id: z.string().min(1).max(64), step_id: z.string().min(1).max(64),
action: 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), elapsed_ms: z.number().int().min(0),
before_url: sanitizedBrowserUrlSchema, before_url: sanitizedBrowserUrlSchema,
after_url: sanitizedBrowserUrlSchema, after_url: sanitizedBrowserUrlSchema,
error: z.string().max(4_096).nullable(),
event_sequence_start: z.number().int().min(1), event_sequence_start: z.number().int().min(1),
event_sequence_end: z.number().int().min(0), event_sequence_end: z.number().int().min(0),
artifacts: browserStepArtifactsSchema, artifacts: browserStepArtifactsSchema,
completeness: browserScenarioCompletenessSchema, 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>; export type BrowserScenarioStep = z.infer<typeof browserScenarioStepSchema>;
type StepOutcome<Step> = Step extends BrowserScenarioStep
? Pick<Step, "status" | "error">
: never;
export type BrowserScenarioStepOutcome = StepOutcome<BrowserScenarioStep>;
@@ -5,11 +5,11 @@ import { describe, expect, it } from "vitest";
import { import {
compareBrowserScenarios, compareBrowserScenarios,
compareBrowserScenariosInputSchema, compareBrowserScenariosInputSchema,
} from "../../../src/domain/browserScenarioDiff.js"; } from "./browserScenarioDiff.js";
import { import {
browserScenarioCaptureSchema, browserScenarioCaptureSchema,
type BrowserScenarioCapture, type BrowserScenarioCapture,
} from "../../../src/domain/browserScenarioCapture.js"; } from "./browserScenarioCapture.js";
describe("browser scenario comparison", () => { describe("browser scenario comparison", () => {
it("records canonical literal normalization and ignores declared volatile fields", () => { it("records canonical literal normalization and ignores declared volatile fields", () => {
+20 -93
View File
@@ -1,8 +1,16 @@
import { import {
type BrowserScenarioCapture, type BrowserScenarioCapture,
type BrowserScenarioStep, type BrowserScenarioStep,
type BrowserStepArtifacts,
} from "./browserScenarioCapture.js"; } from "./browserScenarioCapture.js";
import {
actionState,
artifactEvidenceState,
captured,
eventEvidenceState,
eventsFor,
screenshotProjection,
type CaptureState,
} from "./browserScenarioDiffEvidence.js";
import { import {
browserScenarioDiffSchema, browserScenarioDiffSchema,
type BrowserScenarioAlignmentFailure, type BrowserScenarioAlignmentFailure,
@@ -26,22 +34,18 @@ export {
type CompareBrowserScenariosInput, type CompareBrowserScenariosInput,
} from "./browserScenarioDiffValues.js"; } from "./browserScenarioDiffValues.js";
type CaptureState<T> = type ComparableArtifact = {
| { 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 {
readonly artifact: BrowserScenarioArtifactKind; 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 { interface ScenarioAlignment {
readonly before: ReadonlyMap<string, BrowserScenarioStep>; 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,
});
+123
View File
@@ -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,
});
@@ -3,15 +3,15 @@ import { describe, expect, it } from "vitest";
import { import {
bundleComparisonResultSchema, bundleComparisonResultSchema,
compareBundles, compareBundles,
} from "../../../src/domain/bundleComparison.js"; } from "./bundleComparison.js";
import { createEvidence } from "../../../src/domain/evidence.js"; import { createEvidence } from "./evidence.js";
import { createEvidenceBundle } from "../../../src/domain/evidenceBundle.js"; import { createEvidenceBundle } from "./evidenceBundle.js";
import { import {
createResidualUnknown, createResidualUnknown,
recordUnknownInputSchema, recordUnknownInputSchema,
updateResidualUnknown, updateResidualUnknown,
updateUnknownInputSchema, updateUnknownInputSchema,
} from "../../../src/domain/residualUnknown.js"; } from "./residualUnknown.js";
const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const; const PROVIDER = { id: "fixture", name: "Fixture", version: "1" } as const;
const evidence = (label: string) => const evidence = (label: string) =>
@@ -1,14 +1,14 @@
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { enhancedInputSchemas } from "../../../src/contracts/enhancedInputs.js"; import { enhancedInputSchemas } from "../contracts/enhancedInputs.js";
import { import {
buildCallPath, buildCallPath,
callPathInputSchema, callPathInputSchema,
callPathResultSchema, callPathResultSchema,
} from "../../../src/domain/callPath.js"; } from "./callPath.js";
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js"; import { createEvidence, type Evidence } from "./evidence.js";
import { functionDossierSchema } from "../../../src/domain/hopperValues.js"; import { functionDossierSchema } from "./hopperValues.js";
import { jsonValueSchema } from "../../../src/domain/jsonValue.js"; import { jsonValueSchema } from "./jsonValue.js";
const bounded = <Item>(items: readonly Item[], complete = true) => ({ const bounded = <Item>(items: readonly Item[], complete = true) => ({
items, items,
@@ -3,9 +3,9 @@ import { describe, expect, it } from "vitest";
import { import {
changedBehaviorResultSchema, changedBehaviorResultSchema,
findChangedBehavior, findChangedBehavior,
} from "../../../src/domain/changedBehavior.js"; } from "./changedBehavior.js";
import { createEvidence, type Evidence } from "../../../src/domain/evidence.js"; import { createEvidence, type Evidence } from "./evidence.js";
import type { JsonValue } from "../../../src/domain/jsonValue.js"; import type { JsonValue } from "./jsonValue.js";
const source = (digit: string): Evidence => const source = (digit: string): Evidence =>
createEvidence( createEvidence(
@@ -5,8 +5,8 @@ import {
createCompletionLedgerArtifacts, createCompletionLedgerArtifacts,
parseCompletionManifest, parseCompletionManifest,
type CompletionVerifierReport, type CompletionVerifierReport,
} from "../../../src/domain/completionLedgerGeneration.js"; } from "./completionLedgerGeneration.js";
import { parseEvidenceCompletionLedger } from "../../../src/domain/evidenceCompletionLedger.js"; import { parseEvidenceCompletionLedger } from "./evidenceCompletionLedger.js";
const digest = (digit: string): string => digit.repeat(64); const digest = (digit: string): string => digit.repeat(64);
const evidenceId = (digit: string): string => `ev_${digest(digit)}`; const evidenceId = (digit: string): string => `ev_${digest(digit)}`;
+226 -114
View File
@@ -5,22 +5,16 @@ import { z } from "zod";
import { evidenceEnvelopeSchema } from "./evidence.js"; import { evidenceEnvelopeSchema } from "./evidence.js";
import { evidenceBundleSchema } from "./evidenceBundle.js"; import { evidenceBundleSchema } from "./evidenceBundle.js";
import { err, ok, type Result } from "./result.js";
/** Schema version for the conformance package format. */ /** Schema version for the conformance package format. */
export const CONFORMANCE_PACKAGE_VERSION = 1; export const CONFORMANCE_PACKAGE_VERSION = 1;
/** A stable, path-independent identifier for a conformance package. */ const conformancePackageIdSchema = z.string().regex(/^cp_[a-f0-9]{64}$/u);
export const conformancePackageIdSchema = z
.string()
.regex(/^cp_[a-f0-9]{64}$/u);
/** Identifier for a single scenario within a package. */ const scenarioIdSchema = z.string().regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
export const scenarioIdSchema = z
.string()
.regex(/^[A-Za-z][A-Za-z0-9._-]{0,99}$/u);
/** Deterministic manifest for a scenario fixture. */ const scenarioManifestSchema = z.strictObject({
export const scenarioManifestSchema = z.strictObject({
scenario_id: scenarioIdSchema, scenario_id: scenarioIdSchema,
name: z.string().min(1), name: z.string().min(1),
description: 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([]), expected_patterns: z.array(z.string()).default([]),
}); });
/** Replay plan describing how a scenario is replayed deterministically. */ const replayPlanSchema = z.strictObject({
export const replayPlanSchema = z.strictObject({
scenario_id: scenarioIdSchema, scenario_id: scenarioIdSchema,
/** Ordered steps to execute during replay. */ /** Ordered steps to execute during replay. */
steps: z steps: z
@@ -51,8 +44,7 @@ export const replayPlanSchema = z.strictObject({
environment: z.record(z.string(), z.string()).default({}), environment: z.record(z.string(), z.string()).default({}),
}); });
/** Shim plan for intercepting observable effects. */ const shimPlanSchema = z.strictObject({
export const shimPlanSchema = z.strictObject({
scenario_id: scenarioIdSchema, scenario_id: scenarioIdSchema,
/** Shims to install, each intercepting a named effect. */ /** Shims to install, each intercepting a named effect. */
shims: z shims: z
@@ -64,23 +56,20 @@ export const shimPlanSchema = z.strictObject({
policy: z.enum(["observe", "allow", "block", "emulate"]), policy: z.enum(["observe", "allow", "block", "emulate"]),
}), }),
) )
.min(0)
.max(50), .max(50),
}); });
/** Expected evidence for a scenario, checked against the captured run. */ const expectedEvidenceSchema = z.strictObject({
export const expectedEvidenceSchema = z.strictObject({
scenario_id: scenarioIdSchema, scenario_id: scenarioIdSchema,
/** Expected evidence envelopes. */ /** Expected evidence envelopes. */
envelopes: z.array(evidenceEnvelopeSchema).min(0).max(100), envelopes: z.array(evidenceEnvelopeSchema).max(100),
/** Expected evidence bundle. */ /** Expected evidence bundle. */
bundle: evidenceBundleSchema.nullable(), bundle: evidenceBundleSchema.nullable(),
/** Required dimensions that must be present in the evidence. */ /** Required dimensions that must be present in the evidence. */
required_dimensions: z.array(z.string().min(1)).default([]), required_dimensions: z.array(z.string().min(1)).default([]),
}); });
/** Verifier contract describing how to validate conformance. */ const verifierContractSchema = z.strictObject({
export const verifierContractSchema = z.strictObject({
scenario_id: scenarioIdSchema, scenario_id: scenarioIdSchema,
/** Dimensions to verify. */ /** Dimensions to verify. */
dimensions: z dimensions: z
@@ -97,122 +86,245 @@ export const verifierContractSchema = z.strictObject({
timing_tolerance_ms: z.number().int().nonnegative().default(0), timing_tolerance_ms: z.number().int().nonnegative().default(0),
}); });
/** Top-level conformance package manifest. */ const conformancePackageContentsSchema = z.strictObject({
export const conformancePackageSchema = z.strictObject({
schema_version: z.literal(CONFORMANCE_PACKAGE_VERSION), schema_version: z.literal(CONFORMANCE_PACKAGE_VERSION),
package_id: conformancePackageIdSchema,
name: z.string().min(1), name: z.string().min(1),
description: z.string().min(1), description: z.string().min(1),
created_at: z.string().datetime(), created_at: z.string().datetime(),
/** Scenario manifests. */ /** Scenario manifests. */
scenarios: z.array(scenarioManifestSchema).min(1).max(100), 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), 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([]), 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), 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), verifier_contracts: z.array(verifierContractSchema).min(1).max(100),
}); });
export type ConformancePackage = z.infer<typeof conformancePackageSchema>; const conformancePackageRecordSchema = conformancePackageContentsSchema.extend({
export type ScenarioManifest = z.infer<typeof scenarioManifestSchema>; package_id: conformancePackageIdSchema,
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>;
/** 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 = export type ConformancePackageError =
| { kind: "invalid_package"; message: string } | {
| { kind: "scenario_not_found"; scenario_id: string } readonly kind: "invalid_package";
| { kind: "duplicate_scenario"; scenario_id: string }; readonly message: string;
}
/** Result type for package operations. */ | {
export type ConformancePackageResult<T> = readonly kind: "duplicate_scenario";
| { ok: true; value: T } readonly scenario_id: string;
| { ok: false; error: ConformancePackageError }; readonly message: string;
}
/** Validate a conformance package and cross-check internal references. */ | {
export function validateConformancePackage( readonly kind: "unknown_scenario_reference";
input: unknown, readonly section: ConformancePackageSection;
): ConformancePackageResult<ConformancePackage> { readonly scenario_id: string;
const parsed = conformancePackageSchema.safeParse(input); readonly message: string;
if (!parsed.success) }
return { | {
ok: false, readonly kind: "duplicate_scenario_reference";
error: { readonly section: ConformancePackageSection;
kind: "invalid_package", readonly scenario_id: string;
message: parsed.error.issues[0]?.message ?? "invalid package", 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 /** Parse unknown input once into a package whose aggregate invariants hold. */
const seen = new Set<string>(); export function parseConformancePackage(
for (const s of pkg.scenarios) { input: unknown,
if (seen.has(s.scenario_id)) ): Result<ConformancePackage, ConformancePackageError> {
return { const parsed = conformancePackageSchema.safeParse(input);
ok: false, if (!parsed.success)
error: { kind: "duplicate_scenario", scenario_id: s.scenario_id }, return err({
}; kind: "invalid_package",
seen.add(s.scenario_id); message: parsed.error.issues[0]?.message ?? "Invalid package",
} });
// Check that replay plans reference existing scenarios const relationError = parseScenarioRelations(parsed.data);
for (const rp of pkg.replay_plans) { if (relationError !== undefined) return err(relationError);
if (!seen.has(rp.scenario_id))
return {
ok: false,
error: {
kind: "scenario_not_found",
scenario_id: rp.scenario_id,
},
};
}
// Check that expected evidence references existing scenarios const expectedPackageId = computePackageId(packageContents(parsed.data));
for (const ee of pkg.expected_evidence) { if (parsed.data.package_id !== expectedPackageId)
if (!seen.has(ee.scenario_id)) return err({
return { kind: "package_id_mismatch",
ok: false, actual: parsed.data.package_id,
error: { expected: expectedPackageId,
kind: "scenario_not_found", message: "Package identifier does not match its canonical contents",
scenario_id: ee.scenario_id, });
},
};
}
// Check that verifier contracts reference existing scenarios return ok(parsed.data);
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 };
} }
/** Compute a deterministic package ID from the canonical JSON. */ /** Create a content-addressed package from source-owned typed fields. */
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. */
export function createConformancePackage( export function createConformancePackage(
pkg: Omit<ConformancePackage, "package_id">, input: ConformancePackageInput,
): ConformancePackage { ): ConformancePackage {
const package_id = computePackageId(pkg); const contents = conformancePackageContentsSchema.safeParse(input);
return { package_id, ...pkg }; 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")}`;
};
+5 -10
View File
@@ -1,9 +1,6 @@
import { z } from "zod"; import { z } from "zod";
import { import { parseConformancePackage } from "./conformancePackage.js";
conformancePackageSchema,
type ConformancePackage,
} from "./conformancePackage.js";
import { import {
evaluatePackageTrustGates, evaluatePackageTrustGates,
trustGateResultSchema, trustGateResultSchema,
@@ -74,12 +71,10 @@ export async function replayConformancePackage(
runner: ScenarioRunner = defaultRunner, runner: ScenarioRunner = defaultRunner,
options: { truncated?: boolean } = {}, options: { truncated?: boolean } = {},
): Promise<PackageReplayResult> { ): Promise<PackageReplayResult> {
const parsed = conformancePackageSchema.safeParse(packageInput); const parsed = parseConformancePackage(packageInput);
if (!parsed.success) if (!parsed.ok)
throw new TypeError( throw new TypeError(`invalid conformance package: ${parsed.error.message}`);
`invalid conformance package: ${parsed.error.issues[0]?.message ?? "unknown"}`, const pkg = parsed.value;
);
const pkg: ConformancePackage = parsed.data;
const scenarioResults: ScenarioReplayResult[] = []; const scenarioResults: ScenarioReplayResult[] = [];
let passed = 0; let passed = 0;
+4 -1
View File
@@ -389,7 +389,10 @@ export function evaluatePackageTrustGates(
const expected = pkg.expected_evidence.find( const expected = pkg.expected_evidence.find(
(e) => e.scenario_id === contract.scenario_id, (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 expectedEvidence = expected.envelopes[0] ?? {};
const actual = actualEvidence[contract.scenario_id] ?? {}; const actual = actualEvidence[contract.scenario_id] ?? {};
const result = evaluateTrustGate( const result = evaluateTrustGate(
+15 -4
View File
@@ -235,7 +235,7 @@ const coverageSchema = z.strictObject({
pre_capture_activity: z.literal("unavailable"), pre_capture_activity: z.literal("unavailable"),
}); });
const actionResultSchema = z.strictObject({ const actionResultContextShape = {
step_id: z.string().min(1).max(128), step_id: z.string().min(1).max(128),
kind: z.enum([ kind: z.enum([
"click", "click",
@@ -246,10 +246,21 @@ const actionResultSchema = z.strictObject({
]), ]),
window_index: windowIndexSchema.nullable(), window_index: windowIndexSchema.nullable(),
target: z.string().max(256).nullable(), target: z.string().max(256).nullable(),
status: z.enum(["completed", "failed", "cancelled"]),
elapsed_ms: z.number().int().min(0), 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. */ /** Bounded result of a provider-owned Electron runtime experiment. */
export const electronActiveObservationResultSchema = z.strictObject({ export const electronActiveObservationResultSchema = z.strictObject({
+39 -37
View File
@@ -2,6 +2,8 @@ import * as t from "@babel/types";
import type { import type {
ElectronBrowserWindowFinding, ElectronBrowserWindowFinding,
ElectronBrowserWindowPreload,
ElectronContextBridgeApiKey,
ElectronContextBridgeFinding, ElectronContextBridgeFinding,
ElectronStaticValue, ElectronStaticValue,
ElectronUtilityProcessFinding, ElectronUtilityProcessFinding,
@@ -57,8 +59,7 @@ const inspectBrowserWindow = (
web_preferences_status: collected.status, web_preferences_status: collected.status,
web_preferences: collected.preferences, web_preferences: collected.preferences,
omitted_web_preferences: collected.omitted, omitted_web_preferences: collected.omitted,
preload_path: collected.preloadPath, ...collected.preload,
preload_resolution_context: collected.preloadResolutionContext,
module_key: null, module_key: null,
location: range(node), location: range(node),
}; };
@@ -76,8 +77,7 @@ const collectWindowOptions = (
): { ): {
readonly status: ElectronBrowserWindowFinding["web_preferences_status"]; readonly status: ElectronBrowserWindowFinding["web_preferences_status"];
readonly preferences: readonly ElectronWebPreference[]; readonly preferences: readonly ElectronWebPreference[];
readonly preloadPath: string | null; readonly preload: ElectronBrowserWindowPreload;
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
readonly unknown: number; readonly unknown: number;
readonly omitted: number; readonly omitted: number;
} => { } => {
@@ -85,8 +85,7 @@ const collectWindowOptions = (
return { return {
status: options === undefined ? "missing" : "dynamic", status: options === undefined ? "missing" : "dynamic",
preferences: [], preferences: [],
preloadPath: null, preload: { preload_path: null, preload_resolution_context: null },
preloadResolutionContext: null,
unknown: options === undefined ? 0 : 1, unknown: options === undefined ? 0 : 1,
omitted: 0, omitted: 0,
}; };
@@ -95,8 +94,7 @@ const collectWindowOptions = (
return { return {
status: "missing", status: "missing",
preferences: [], preferences: [],
preloadPath: null, preload: { preload_path: null, preload_resolution_context: null },
preloadResolutionContext: null,
unknown: 0, unknown: 0,
omitted: 0, omitted: 0,
}; };
@@ -104,8 +102,7 @@ const collectWindowOptions = (
return { return {
status: "dynamic", status: "dynamic",
preferences: [], preferences: [],
preloadPath: null, preload: { preload_path: null, preload_resolution_context: null },
preloadResolutionContext: null,
unknown: 1, unknown: 1,
omitted: 0, omitted: 0,
}; };
@@ -118,16 +115,16 @@ const collectWebPreferences = (
): { ): {
readonly status: "object-literal"; readonly status: "object-literal";
readonly preferences: readonly ElectronWebPreference[]; readonly preferences: readonly ElectronWebPreference[];
readonly preloadPath: string | null; readonly preload: ElectronBrowserWindowPreload;
readonly preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"];
readonly unknown: number; readonly unknown: number;
readonly omitted: number; readonly omitted: number;
} => { } => {
const preferences: ElectronWebPreference[] = []; const preferences: ElectronWebPreference[] = [];
let unknown = 0; let unknown = 0;
let preloadPath: string | null = null; let preload: ElectronBrowserWindowPreload = {
let preloadResolutionContext: ElectronBrowserWindowFinding["preload_resolution_context"] = preload_path: null,
null; preload_resolution_context: null,
};
for (const property of object.properties) { for (const property of object.properties) {
if (t.isSpreadElement(property)) { if (t.isSpreadElement(property)) {
unknown += 1; unknown += 1;
@@ -155,10 +152,11 @@ const collectWebPreferences = (
continue; continue;
} }
const path = name === "preload" ? staticPath(property.value) : undefined; const path = name === "preload" ? staticPath(property.value) : undefined;
if (path !== undefined) { if (path !== undefined)
preloadPath = path; preload = {
preloadResolutionContext = staticPathResolutionContext(property.value); preload_path: path,
} preload_resolution_context: staticPathResolutionContext(property.value),
};
const value: ElectronStaticValue = const value: ElectronStaticValue =
path === undefined path === undefined
? electronStaticValue(source, property.value) ? electronStaticValue(source, property.value)
@@ -170,8 +168,7 @@ const collectWebPreferences = (
return { return {
status: "object-literal", status: "object-literal",
preferences: preferences.slice(0, MAX_WEB_PREFERENCES), preferences: preferences.slice(0, MAX_WEB_PREFERENCES),
preloadPath, preload,
preloadResolutionContext,
unknown, unknown,
omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES), omitted: Math.max(0, preferences.length - MAX_WEB_PREFERENCES),
}; };
@@ -201,14 +198,16 @@ const inspectContextBridge = (
(worldId?.status === "dynamic" ? 1 : 0) + (worldId?.status === "dynamic" ? 1 : 0) +
api.unknown; api.unknown;
accountForStructure(context, unknown, api.omitted); 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 = { const finding: ElectronContextBridgeFinding = {
...apiKey,
world: isolated ? "isolated" : "main", world: isolated ? "isolated" : "main",
world_id: worldId, 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, api_status: api.status,
members: api.members, members: api.members,
unknown_members: api.unknown, unknown_members: api.unknown,
@@ -234,10 +233,6 @@ const inspectUtilityProcess = (
const moduleNode = argumentNode(node.arguments[0]); const moduleNode = argumentNode(node.arguments[0]);
const modulePath = const modulePath =
moduleNode === undefined ? undefined : staticPath(moduleNode); moduleNode === undefined ? undefined : staticPath(moduleNode);
const moduleResolutionContext =
modulePath === undefined || moduleNode === undefined
? null
: staticPathResolutionContext(moduleNode);
const options = argumentNode(node.arguments[2]); const options = argumentNode(node.arguments[2]);
const serviceName = const serviceName =
t.isObjectExpression(options) && t.isObjectExpression(options) &&
@@ -245,20 +240,27 @@ const inspectUtilityProcess = (
? staticPath(objectProperty(options, "serviceName")?.value ?? options) ? staticPath(objectProperty(options, "serviceName")?.value ?? options)
: undefined; : undefined;
if (modulePath === undefined) context.accumulator.unknownFindings += 1; 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 = { const finding: ElectronUtilityProcessFinding = {
module_path: modulePath ?? null, ...moduleReference,
module_resolution_context: moduleResolutionContext,
module_expression:
modulePath === undefined
? boundedExpression(context.source, moduleNode)
: null,
service_name: serviceName ?? null, service_name: serviceName ?? null,
module_key: null, module_key: null,
location: range(node), location: range(node),
}; };
addLocatedFinding(context, { addLocatedFinding(context, {
collection: context.accumulator.utilityProcesses, collection: context.accumulator.utilityProcesses,
key: `electron-utility\0${modulePath ?? finding.module_expression ?? "[missing]"}`, key: `electron-utility\0${finding.module_path ?? finding.module_expression}`,
node, node,
value: finding, value: finding,
}); });
+43 -22
View File
@@ -1,6 +1,7 @@
import * as t from "@babel/types"; import * as t from "@babel/types";
import type { import type {
ElectronIpcDescriptor,
ElectronIpcFinding, ElectronIpcFinding,
ElectronSenderValidationFinding, ElectronSenderValidationFinding,
} from "./electronStaticAnalysisTypes.js"; } from "./electronStaticAnalysisTypes.js";
@@ -18,12 +19,6 @@ import {
} from "./javascriptStaticAnalysisHelpers.js"; } from "./javascriptStaticAnalysisHelpers.js";
import type { JavaScriptFindingContext } from "./javascriptStaticAnalysisState.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. */ /** Inspect Electron IPC operations and validation candidates. */
export const inspectElectronIpcNode = ( export const inspectElectronIpcNode = (
node: t.Node, node: t.Node,
@@ -49,30 +44,56 @@ const inspectIpcCall = (
channelValue.status === "literal" && typeof channelValue.value === "string" channelValue.status === "literal" && typeof channelValue.value === "string"
? channelValue.value ? channelValue.value
: null; : null;
const channelExpression = const channelReference =
channel === null channel === null
? channelValue.status === "dynamic" ? {
? channelValue.expression channel: null,
: boundedExpression(context.source, channelNode) channel_expression:
: null; channelValue.status === "dynamic"
const hasHandler = ? channelValue.expression
descriptor.mode === "listen" || descriptor.mode === "handle"; : boundedExpression(context.source, channelNode),
const handlerNode = hasHandler ? argumentNode(node.arguments[1]) : undefined; }
: { 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 (channel === null) context.accumulator.unknownFindings += 1;
if (hasHandler && handlerNode === undefined) if (findingState.handler_kind === "missing")
context.accumulator.unknownFindings += 1; context.accumulator.unknownFindings += 1;
const finding: ElectronIpcFinding = { const finding: ElectronIpcFinding = {
...descriptor, ...findingState,
channel, ...channelReference,
channel_expression: channelExpression,
handler_kind: hasHandler ? handlerKind(handlerNode) : null,
handler_location: handlerNode === undefined ? null : range(handlerNode),
module_key: null, module_key: null,
location: range(node), location: range(node),
}; };
addLocatedFinding(context, { addLocatedFinding(context, {
collection: context.accumulator.ipc, 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, node,
value: finding, 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"); const renderer = suffixOperation(name, "ipcRenderer");
if (renderer !== undefined) { if (renderer !== undefined) {
switch (renderer) { switch (renderer) {

Some files were not shown because too many files have changed in this diff Show More