test: consolidate service and process fixtures

This commit is contained in:
morluto
2026-10-08 04:03:24 +08:00
parent d88d6c1897
commit f8a53a8c06
25 changed files with 471 additions and 1176 deletions
@@ -1,47 +1,14 @@
import { describe, expect, it } from "vitest";
import { expect, it } from "vitest";
import { compareDirectoryChildNames } from "./ArtifactGraphConstruction.js";
const tiedNames = ["a.txt", "a\u200b.txt", "a\u200c.txt", "a\u200d.txt"];
describe("directory child-name ordering", () => {
it("orders the tied subset lexically with reflexivity and antisymmetry", () => {
for (const left of tiedNames) {
expect(compareDirectoryChildNames(left, left)).toBe(0);
for (const right of tiedNames) {
expect(left.localeCompare(right)).toBe(0);
const compared = compareDirectoryChildNames(left, right);
const lexical = left < right ? -1 : left > right ? 1 : 0;
expect(compared).toBe(lexical);
expect(compared + compareDirectoryChildNames(right, left)).toBe(0);
}
}
});
it("is transitive across the tied subset", () => {
for (const first of tiedNames)
for (const second of tiedNames)
for (const third of tiedNames)
if (
compareDirectoryChildNames(first, second) <= 0 &&
compareDirectoryChildNames(second, third) <= 0
)
expect(
compareDirectoryChildNames(first, third),
).toBeLessThanOrEqual(0);
});
it.each([
["a.txt", "b.txt"],
["z.txt", "ä.txt"],
["Z", "a"],
["a/data.txt", "b/data.txt"],
])("preserves the current non-tied collation for %s / %s", (left, right) => {
const collated = left.localeCompare(right);
expect(collated).not.toBe(0);
expect(compareDirectoryChildNames(left, right)).toBe(collated);
expect(compareDirectoryChildNames(right, left)).toBe(
right.localeCompare(left),
);
});
it("breaks locale-collation ties deterministically by code unit", () => {
const names = ["a\u200d.txt", "a.txt", "a\u200b.txt", "a\u200c.txt"];
expect("a\u200d.txt".localeCompare("a.txt")).toBe(0);
expect(names.sort(compareDirectoryChildNames)).toEqual([
"a.txt",
"a\u200b.txt",
"a\u200c.txt",
"a\u200d.txt",
]);
});
@@ -1,14 +0,0 @@
import { describe, expect, it } from "vitest";
import { resolveArtifactIntegrityPolicy } from "./ArtifactInventory/policy.js";
describe("artifact inventory policy resolution", () => {
it("preserves the selected integrity behavior without disabling verification", () => {
expect(resolveArtifactIntegrityPolicy({ mode: "fail" })).toEqual({
mode: "fail",
});
expect(
resolveArtifactIntegrityPolicy({ mode: "record-and-continue" }),
).toEqual({ mode: "record-and-continue" });
});
});
@@ -1,28 +0,0 @@
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,
},
);
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,5 +1,6 @@
import { describe, expect, it } from "vitest";
import { toolAvailability } from "../contracts/toolOutputSchemaPrimitives.js";
import { buildCapabilityInventory } from "./CapabilityInventory.js";
it("reports module syntax and native resolution availability separately", () => {
@@ -249,6 +250,23 @@ describe("capability inventory: caller guidance", () => {
}
});
it("keeps the public availability schema consistent with generated states", () => {
const inventory = buildCapabilityInventory(status(), enabledPolicy);
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("does not require interactive elicitation for process capture", () => {
const withoutElicitation = buildCapabilityInventory(
status(),
@@ -105,30 +105,13 @@ const unknownLimitation = (graphId: string, nodeId: string): string =>
`Application graph ${graphId} contains unresolved node ${nodeId}; reconstruction obligations remain unknown.`;
describe("reconstruction obligation candidates", () => {
it("preserves admitted unknown application nodes as limitations", () => {
const { graph, unknownNodes, generated } = applicationWithUnknowns([
"unclassified-boundary",
]);
const unknownNode = unknownNodes[0];
if (unknownNode === undefined) throw new Error("Expected one unknown node");
expect(generated.candidates.length).toBeGreaterThan(0);
expect(
generated.candidates.some(
({ target }) => target.application_node_id === unknownNode.node_id,
),
).toBe(false);
expect(generated.limitations).toEqual([
unknownLimitation(graph.graph_id, unknownNode.node_id),
]);
});
it("emits one deterministic limitation per unknown node", () => {
it("preserves unresolved application nodes as deterministic limitations", () => {
const { graph, unknownNodes, generated } = applicationWithUnknowns([
"unclassified-first",
"unclassified-second",
]);
expect(generated.candidates.length).toBeGreaterThan(0);
expect([...generated.limitations].sort()).toEqual(
unknownNodes
.map((node) => unknownLimitation(graph.graph_id, node.node_id))
@@ -1,112 +1,16 @@
import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "./process/ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/process/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/process/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
boundProofEvidence,
build,
originalCases,
processEvidence,
proofEvidence,
request,
reviewedObligation,
} from "./ReconstructionObligationLedger.fixture.js";
import { createEvidence } from "../domain/evidence.js";
import type { ReviewedReconstructionObligation } from "../domain/reconstructionObligationLedgerSchemas.js";
describe("reconstruction obligation ledger", () => {
it("does not authenticate packaged-process proof with generic replay evidence", () => {
@@ -315,32 +219,3 @@ describe("reconstruction obligation ledger fail-closed behavior", () => {
]);
});
});
const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
@@ -1,141 +1,14 @@
import { describe, expect, it } from "vitest";
import { PROCESS_PROVIDER } from "./process/ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/process/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/process/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
boundProofEvidence,
build,
originalCases,
processEvidence,
proofEvidence,
request,
reviewedObligation,
} from "./ReconstructionObligationLedger.fixture.js";
describe("reconstruction obligation ledger", () => {
it("emits the complete deterministic ledger and closure identity", () => {
@@ -0,0 +1,143 @@
import { PROCESS_PROVIDER } from "./process/ProcessEvidence.js";
import {
buildReconstructionObligationLedgerEvidenceValidated,
resolveReconstructionObligationLedgerRequest,
} from "./ReconstructionObligationLedgerService.js";
import { EMPTY_PROCESS_CAPTURE_EXAMPLE } from "../domain/process/processCapture.fixture.js";
import { createEvidence, type Evidence } from "../domain/evidence.js";
import { createEvidenceBundle } from "../domain/evidenceBundle.js";
import { jsonValueSchema } from "../domain/jsonValue.js";
import { processCaptureSchema } from "../domain/process/processCapture.js";
import {
reconstructionObligationLedgerSchema,
type ReconstructionObligationLedgerInput,
type ReconstructionObligationLedger,
type ReviewedReconstructionObligation,
} from "../domain/reconstructionObligationLedgerSchemas.js";
/** Build controlled fixture Evidence used by reconstruction-ledger scenarios. */
export const proofEvidence = (id: string) =>
createEvidence(
undefined,
{ id: `fixture-${id}`, name: "Fixture verifier", version: "1" },
{
predicateType: "rea.fixture-verification",
operation: "run_fixture_verifier",
parameters: { id },
result: { passed: true },
confidence: "observed",
authority: "controlled-replay",
},
);
/** Use the canonical empty process capture as a controlled Evidence example. */
export const processEvidence = () =>
createEvidence(undefined, PROCESS_PROVIDER, {
predicateType: "rea.process-capture",
operation: "capture_process_scenario",
parameters: {},
result: jsonValueSchema.parse(
processCaptureSchema.parse(EMPTY_PROCESS_CAPTURE_EXAMPLE),
),
confidence: "observed",
authority: "controlled-replay",
});
/** Build verifier Evidence bound to enumerated fixture and obligation identities. */
export const boundProofEvidence = (
id: string,
result: {
readonly obligation_ids: readonly string[];
readonly fixture_ids: readonly string[];
readonly case_kinds: readonly string[];
readonly verifier_ids: readonly string[];
readonly claim_ids: readonly string[];
},
authority: "shipped-artifact" | "controlled-replay" = "controlled-replay",
) =>
createEvidence(
undefined,
{ id: `proof-${id}`, name: "Reconstruction proof", version: "1" },
{
predicateType: "rea.reconstruction-proof",
operation: "verify_reconstruction_obligations",
parameters: {},
result: {
passed: true,
obligation_ids: [...result.obligation_ids],
fixture_ids: [...result.fixture_ids],
case_kinds: [...result.case_kinds],
verifier_ids: [...result.verifier_ids],
claim_ids: [...result.claim_ids],
},
confidence: "observed",
authority,
},
);
/** Build a ledger request with empty reviewed input and manifest defaults. */
export const request = (
records: readonly Evidence[],
overrides: Partial<ReconstructionObligationLedgerInput> = {},
): ReconstructionObligationLedgerInput => ({
evidence_bundle: createEvidenceBundle(records),
reviewed_obligations: [],
manifest: { bindings: [], contradictions: [] },
...overrides,
});
/** Run request resolution, Evidence validation, and output parsing for a fixture. */
export const build = (
input: ReconstructionObligationLedgerInput,
): ReconstructionObligationLedger => {
const parsed = resolveReconstructionObligationLedgerRequest(input);
if (!parsed.ok) throw parsed.error;
const result = buildReconstructionObligationLedgerEvidenceValidated(
parsed.value,
);
if (!result.ok) throw result.error;
return reconstructionObligationLedgerSchema.parse(
result.value.normalized_result,
);
};
/** Create provenance for each required case from one source Evidence record. */
export const originalCases = (
obligation: ReconstructionObligationLedger["obligations"][number],
evidenceId: string,
) =>
obligation.required_case_kinds.map((caseKind) => ({
kind: caseKind,
evidence_id: evidenceId,
location: `/normalized_result/cases/${caseKind}`,
}));
/** Create a minimal reviewed obligation for ledger closure scenarios. */
export const reviewedObligation = (
obligationId: string,
evidenceId: string,
): ReviewedReconstructionObligation => ({
obligation_id: obligationId,
obligation_version: 1,
title: `Reviewed obligation ${obligationId}`,
application_layer: "other",
family: "reviewed",
target: {
artifact_sha256: null,
application_node_id: null,
semantic_node_id: null,
location: `/reviewed/${obligationId}`,
},
required: true,
required_case_kinds: ["positive"],
required_original_authority: "static",
required_fixture_authority: "unit",
required_verifier_authority: "unit",
requires_parser_type: false,
dependency_obligation_ids: [],
residual_unknown_ids: [],
unavailable_authority: [],
required_next_evidence: ["Bind an owner and verifier."],
disposition: "active",
review_evidence_ids: [evidenceId],
});
-9
View File
@@ -165,15 +165,6 @@ describe("setup workflow lifecycle and provider planning", () => {
remediation: null,
},
];
host.productRegistrations = [
{
client: "codex",
config_path: "/codex.toml",
command: ["rea", "mcp"],
state: "aligned",
remediation: null,
},
];
const progress: SetupProgressEvent[] = [];
await runSetup(
{ ...options(true), onProgress: (event) => progress.push(event) },
@@ -1,31 +0,0 @@
import { describe, expect, it } from "vitest";
import {
setupInstallFailure,
type HopperInstallFailureReason,
} from "./SetupInstallFailure.js";
describe("setup installer failure projection", () => {
it.each([
["unsupported_host", "unsupported_host"],
["download", "download_failed"],
["release_metadata", "download_failed"],
["integrity", "integrity_mismatch"],
[
"authorization_or_package_manager",
"authorization_or_package_manager_failed",
],
["launcher_missing", "launcher_missing"],
["runtime_dependencies", "runtime_dependency_unavailable"],
["unsupported_hopper_build", "unsupported_hopper_build"],
["cancelled", "setup_cancelled"],
["destination_exists", "destination_exists"],
["mount", "mount_failed"],
["bundle", "bundle_invalid"],
["copy", "copy_failed"],
] as const)("maps %s to %s", (reason, code) => {
const result = setupInstallFailure(reason as HopperInstallFailureReason);
expect(result).toMatchObject({ status: "failed", code });
expect(result).toMatchObject({ remediation: expect.stringMatching(/\S/u) });
});
});
@@ -1,40 +0,0 @@
import { describe, expect, it } from "vitest";
import type { DoctorProviderInspection } from "./Doctor.js";
import { providerRegistrationEnvironment } from "./SetupRegistrationEnvironment.js";
const inspection = (
overrides: Partial<DoctorProviderInspection> = {},
): DoctorProviderInspection => ({
id: "fixture",
configured: true,
available: false,
providerVersion: "1",
registrationEnvironment: {
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
},
checks: [],
...overrides,
});
describe("provider registration settings", () => {
it("retains valid published paths when runtime capabilities are unavailable", () => {
expect(providerRegistrationEnvironment([inspection()])).toEqual({
REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider",
});
});
it("does not invent settings when the adapter cannot publish an installation", () => {
expect(
providerRegistrationEnvironment([
inspection({ configured: false, registrationEnvironment: {} }),
]),
).toEqual({});
});
it("keeps available-provider settings unchanged", () => {
expect(
providerRegistrationEnvironment([inspection({ available: true })]),
).toEqual({ REA_FIXTURE_PROVIDER_ROOT: "C:\\Tools\\Provider" });
});
});
@@ -1,9 +1,6 @@
import { describe, expect, it } from "vitest";
import {
AnalysisProviderRegistry,
type AnalysisProviderBinding,
} from "./AnalysisProviderRegistry.js";
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
import {
createAnalysisExecution,
type AnalysisClient,
@@ -33,132 +30,77 @@ const ARTIFACT_TARGET: BinaryTarget = {
format: "asar",
};
describe("analysis provider registry: discovery and selection", () => {
it("admits overlapping operations, sorts discovery, and rejects duplicate IDs", () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
it("rejects malformed provider capability declarations", () => {
const alpha = candidate("alpha");
expect(
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
).toThrow(/Duplicate analysis provider ID: alpha/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => {
const descriptor = capability(alpha.provider.identity());
return [descriptor, descriptor];
},
},
]),
).toThrow(/declares operation address_name more than once/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => [
capability({ ...alpha.provider.identity(), name: "forged" }),
],
},
]),
).toThrow(/published mismatched capability provenance/u);
expect(
() => new AnalysisProviderRegistry([candidate("auto").provider]),
).toThrow(/Invalid analysis provider ID: auto/u);
});
expect(registry.identities().map(({ id }) => id)).toEqual([
"alpha",
"beta",
]);
expect(
registry.candidates().map(({ provider, targetSupport }) => ({
id: provider.id,
support: targetSupport.status,
})),
).toEqual([
{ id: "alpha", support: "unknown" },
{ id: "beta", support: "unknown" },
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
expect(
() => new AnalysisProviderRegistry([alpha.provider, alpha.provider]),
).toThrow(/Duplicate analysis provider ID: alpha/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => {
const descriptor = capability(alpha.provider.identity());
return [descriptor, descriptor];
},
},
]),
).toThrow(/declares operation address_name more than once/u);
expect(
() =>
new AnalysisProviderRegistry([
{
...alpha.provider,
capabilities: () => [
capability({
...alpha.provider.identity(),
name: "mismatched provider",
}),
],
},
]),
).toThrow(/published mismatched capability provenance/u);
expect(
() => new AnalysisProviderRegistry([candidate("auto").provider]),
).toThrow(/Invalid analysis provider ID: auto/u);
it("selects the sole available provider and honors explicit selection precedence", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta", { available: false });
const sole = await new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]).select(DATABASE_TARGET);
expect(sole).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "alpha" },
selectionSource: "auto-single-candidate",
},
},
});
it("selects the sole usable candidate without creating a client", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta", { available: false });
const registry = new AnalysisProviderRegistry([
beta.provider,
alpha.provider,
]);
const selected = await registry.select(DATABASE_TARGET);
expect(selected.ok).toBe(true);
if (!selected.ok) throw new Error("provider selection failed");
if (selected.value.binding === null)
throw new Error("expected a bound provider");
expect(bindingProjection(selected.value.binding)).toEqual({
id: "alpha",
source: "auto-single-candidate",
version: "1",
});
expect(selected.value.candidates).toMatchObject([
{ provider: { id: "alpha", version: "1" }, selected: true },
{
provider: { id: "beta" },
selected: false,
availability: { status: "unavailable", code: "runtime_missing" },
const selected = new AnalysisProviderRegistry(
[alpha.provider, candidate("beta").provider],
"beta",
);
expect(await selected.select(DATABASE_TARGET)).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "beta" },
selectionSource: "environment",
},
]);
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
},
});
it("makes auto ambiguity explicit and honors request over environment", async () => {
const alpha = candidate("alpha");
const beta = candidate("beta");
const registry = new AnalysisProviderRegistry(
[alpha.provider, beta.provider],
"beta",
);
const environment = await registry.select(DATABASE_TARGET);
expect(environment.ok).toBe(true);
if (environment.ok)
expect(environment.value.binding?.selectionSource).toBe("environment");
expect(environment.ok && environment.value.binding?.identity.id).toBe(
"beta",
);
const request = await registry.select(DATABASE_TARGET, "alpha");
expect(request.ok && request.value.binding?.identity.id).toBe("alpha");
if (request.ok)
expect(request.value.binding?.selectionSource).toBe("request");
const automatic = await registry.select(DATABASE_TARGET, "auto");
expect(automatic.ok).toBe(false);
if (automatic.ok) return;
expect(automatic.error).toMatchObject({
reason: "ambiguous",
requestedProviderId: "auto",
candidateIds: ["alpha", "beta"],
});
expect(projectAnalysisError(automatic.error)).toMatchObject({
code: "capability_unavailable",
details: {
selection_reason: "ambiguous",
candidate_ids: ["alpha", "beta"],
expect(await selected.select(DATABASE_TARGET, "alpha")).toMatchObject({
ok: true,
value: {
binding: {
identity: { id: "alpha" },
selectionSource: "request",
},
});
expect(alpha.created).toEqual([]);
expect(beta.created).toEqual([]);
},
});
});
@@ -414,9 +356,3 @@ const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
},
limitations: [],
});
const bindingProjection = (binding: AnalysisProviderBinding) => ({
id: binding.identity.id,
source: binding.selectionSource,
version: binding.identity.version,
});