mirror of
https://github.com/morluto/rea.git
synced 2026-12-04 10:04:50 +00:00
* feat: add FreeBuff agent support for REA setup Register FreeBuff as a supported setup client using the shared user agents directory (~/.agents/mcp.json with mcpServers, skills in ~/.agents/skills), which matches what FreeBuff Desktop loads. Adds the client definition, boundary tests, supported-agent docs, and the skill reference client list. * fix(freebuff): detect FreeBuff from its profile directory, not shared .agents The ~/.agents marker made FreeBuff appear installed for any home where REA had installed shared skills (the default skill destination, also Gemini CLI's), producing false doctor failures. Detect FreeBuff from its own fixed profile directory ~/.config/freebuff-desktop instead, and add a regression test covering a home with only the shared agents skill directory. * fix(setup): require product evidence for FreeBuff discovery Address review findings at their producing boundaries and preserve directly affected consumers. Source inspection and git diff --check completed. Tests and automated checks were not run at the user’s explicit request. * fix(uninstall): retain unverified shared client configuration * fix(clients): preserve scoped removal evidence * fix(doctor): omit undefined selectedClientIds under exactOptionalPropertyTypes Passing selectedClientIds explicitly as undefined fails typecheck on this branch (TS2379), which blocks the focused test workflow before any test can run. Spread the option only when defined. * fix(update): separate ownership evidence from product applicability rea update's maintenance scope inspected only product applicability evidence, so when a FreeBuff profile was absent but REA already owned a version-pinned row in the shared ~/.agents/mcp.json, the plan omitted freebuff and left the integration stale. FreeBuff now declares its registration storage as shared, which proves ownership of an owned row but never product applicability, and maintenance requests ownership evidence through that declaration instead of reinterpreting the shared paths. Doctor and setup keep readiness evidence, foreign rows stay out of maintenance, and the Doctor exactOptionalPropertyTypes fix makes the focused test workflow runnable. * test(dotnet): split oversized operand extent diagnostics describe The describe callback reached 162 lines (max 150), failing max-lines-per-function and blocking the pre-push check for this branch. Move the single-case extent scenarios into their own describe; no test content or order changes. * fix(update): preserve ZCode's disabled shared registration during maintenance The shared user agents file doubles as ZCode's fallback, where `enable: false` disables the registration. Ownership-based maintenance read that row as a FreeBuff registration, whose format does not recognize the flag, so the row was selected and the emitted setup command rewrote it, dropping the flag and silently re-enabling a registration the user had disabled. registrationActivation now honors `enable: false` for any client whose registration storage is shared, because the activation fact binds every reader of that storage. Maintenance leaves such rows out; doctor reports them as stale, matching ZCode's own treatment. * fix(doctor): let explicit client selection authorize the config read When an ACL or an inaccessible shared parent made every access probe fail, a client selected by name was omitted before the configuration read could return its unreadable-config detail, so doctor reported it as not detected with installation remediation: an unresolved selected path collapsed to absence. An explicit selection now authorizes the read outright and the probes serve automatic discovery only. A selected client with an unreadable config reports invalid with the read failure; one with no config reports missing; automatic discovery still probes before inspecting. * fix(uninstall): share shared-storage checks between ZCode and FreeBuff clients() queued ~/.agents/mcp.json twice: once as zcode_fallback and once as freebuff. ZCode has no discoveryPaths, so its strict read still blocked uninstall on malformed shared text, despite FreeBuff's new retain-and-continue behavior. For a valid owned entry, ZCode removed it first, so FreeBuff reported skipped rather than removed. Make the shared file's checks and removal one shared decision: - Add zcodeDiscoveryPaths to ZCode so it has its own applicability evidence. - Gate zcode_fallback push on applicable, not just zcodeFallbackPath presence. - Report shared storage ownership as one decision for both clients: FreeBuff and ZCode now use clientOwnershipEvidencePaths together, so a recognizable REA-owned row proves ownership once for the shared storage, and both clients report the same result consistently. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix(uninstall): merge duplicated host and prove shared ownership from owned rows Uninstall.ts declared systemUninstallHost twice, preventing module load, with the exported copy returning only clients and the second copy missing clientWriteBlocker. Merge into one exported host carrying both blockers. hasOwnershipEvidence used access() existence, so an unrelated malformed ~/.agents/mcp.json established ownership and blocked every removal. Ownership now requires a readable, recognizable REA-owned row via the injected filesystem, so unrelated shared data stays retained. Also cover ZCode discoveryPaths in its path test. * fix(uninstall): keep denied product-local configurations fail-closed Unproven product applicability marked every configuration path of that client unverified, so a denied ZCode profile turned an unreadable product-local config into a retained item: uninstall continued and could report complete with REA still registered. The retain-and-continue exception now applies only to storage REA does not own, classified once by clientSharedRegistrationPaths (shared configuration plus another product's same-scope fallback). Covers the Greptile P1 on Uninstall.ts. Validation: the new test fails on the pre-fix Uninstall and passes after it; freebuff/zcode/updateMaintenance/bom/dsh suites green; clientLifecycle, clientRegistrationStatus and claudeDesktop keep the same 8 host failures as the pre-merge baseline (symlink EPERM, stale-vs-aligned on Windows). * fix(update): retain FreeBuff when ZCode reads the shared fallback Maintenance deduplicated clients on the path each inspection read, so ZCode's fallback view of ~/.agents/mcp.json marked that file "covered" and dropped FreeBuff from the scope. ZCode setup writes ~/.zcode/cli/config.json and deliberately leaves the fallback untouched (docs/client-configuration.md), so the emitted command refreshed only ZCode while the shared row both products load stayed pinned to the old package version. Each setup action rewrites only its own configuration path and no other action rewrites the shared row, so every selected client keeps its own maintenance action; the read-path covered/deduped filter is removed. Covers the Codex P2 on UpdateMaintenance.ts:104. Validation: the new regression fails one2fdec384with {clients:["zcode"]} and passes with {clients:["freebuff","zcode"]}; updateMaintenance 31/31, setupClientConfigCleanupOwnership, cliUpdateAlias, updateOutput, cliStartupImports green; tsc --noEmit, oxlint (0 errors) and oxfmt --check clean; clientRegistrationStatus keeps the same 4 symlink/stale-vs-aligned failures this Windows host has on basee2fdec384(verified by stashing the change). 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): preserve completed reads as shared ownership evidence hasOwnershipEvidence caught every read failure and kept scanning, so a handle-close failure after a successful read — a RegularFileCleanupFailure whose completed outcome still contains the exact shared-file text — was discarded as "no proof". FreeBuff's applicability-unverified storage therefore never got its ownership fact, and once the retained handle blocked later reads, readClientConfiguration downgraded them to retained: inspection passed, removals soft-failed, and runUninstall(true) could purge REA data while the active shared registration remained. The catch now parses the completed outcome for the ownership text while missing or unreadable storage and malformed data keep their proves-nothing semantics, so ownership holds and every later read failure stays blocking. Covers the Codex P2 on Uninstall.ts:252. Validation: the new regression fails on4dbfdf1a9(freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 25/25; the other 21 Uninstall-consumer suites are byte-identical to base4dbfdf1a9(61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): keep owned-row proof through removal refusals hasOwnershipEvidence treated any clientRegistrationRemoval refusal as no ownership: an effective REA-owned rea member shadowed by an earlier foreign duplicate (shadowed_unowned_member), or an owned native row beside a foreign V1 fallback (foreign_legacy_fallback), discarded the already-parsed positive row fact. With FreeBuff unverified and close failures recurring on the preflight/removal rereads, those failures were then downgraded to retained, so runUninstall(true) removed the skill and purged REA data while the active owned row remained. The refusal now carries the owned rows that motivated it — the refusal only refuses the edit — and hasOwnershipEvidence evaluates that fact on both paths; preflight and removal keep refusing the unsafe edit exactly as before. Covers the Codex P2 on Uninstall.ts:269. Validation: the new regression fails on225cb214a(freebuff reports no blocking failure while the poisoned-scope error lands on claude_code) and passes after; setupClientConfigCleanupOwnership 26/26; the 21 Uninstall-consumer suites are byte-identical to the recorded225cb214abaseline (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same 6 warnings) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): keep unresolved discovery probes from softening shared failures The discovery probe swallowed every stat failure, so a FreeBuff profile denied with EACCES/EIO was indistinguishable from an absent profile: shared storage was marked applicability-unverified and, when ~/.agents/mcp.json also remained unreadable, the ownership and removal reads softened to retained. runUninstall(true) then removed the skill and purged REA data while an installed FreeBuff could still hold an active registration — the regression even reports complete. Absence (ENOENT) is now the only state that leaves shared paths unverified; any other probe failure leaves applicability unresolved, and shared-config failures stay blocking. Covers the Codex P2 on Uninstall.ts:318. Validation: the new regression fails on7572a7082with status complete and purged data and passes after; freebuffClientConfiguration 13/13; the Uninstall-consumer batches are byte-identical to the recorded baselines (61 pre-existing Windows-host failures: symlink EPERM, stale-vs-aligned); tsc --noEmit, oxlint (0 errors, same warning rules) and oxfmt --check clean. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): retain completed configuration reads as removal evidence A close failure after a completed read discarded the text that read produced, so an owned registration row the text proves softened to retained. The completed text now drives removal, keeping shared-config failures blocking when ownership evidence exists. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(uninstall): stop removal when a cleanup retry leaves a handle unreleased A completed reread whose handle the cleanup retry cannot release now fails blockingly instead of serving the text: with no owned row, the soft path let removeAll purge managed data before close() reported the incomplete cleanup. The completed text is served only after the retry releases the handle; an unreleased handle is REA's own failure, never applicability uncertainty, so it bypasses the retained softening. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(uninstall): keep the ZCode fallback when its profile probe is unresolved A denied or failed profile probe leaves ZCode's applicability unresolved, never absent, but the fallback branch dropped the shared row on applicability alone: with the native config and FreeBuff's profile both absent, an installed ZCode kept its uninspected registration while uninstall purged skill and data. Unresolved probes now keep the fallback in scope with the same fail-closed treatment as other unresolved shared paths; definitive absence still keeps ZCode out of another product's primary storage. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(setup): preserve a shared row's enable:false during FreeBuff repair The shared agents file doubles as ZCode's fallback, so its `enable: false` binds every reader: doctor now reports the disabled row as stale for FreeBuff, but following that remediation rebuilt the generic JSON entry without the flag and silently re-enabled a registration ZCode disabled. Repairs of shared storage now carry the activation fact forward, while a client's own native storage keeps its established single-reader repair contract; the denied-profile uninstall regression also pins the fallback's new fail-closed inspection beside the denied read. Co-Authored-By: Anthropic <noreply@anthropic.com> * test(uninstall): retarget the completed-reread regression to a released retry The concurrent-writer regression held the reread handle open forever, which the fail-closed path now serves: it duplicated the unreleased-handle regression while documenting the opposite contract. The fixture's close spy gains a failure limit so the cleanup retry releases the handle, and the test again proves the completed text drives removal of the concurrently added owned row, with purge verified against the cache layout purge actually removes. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(doctor): report a preserved shared disable as a manual conflict Preserving a shared row's enable:false left doctor recommending a setup run that registrationCurrent correctly treats as already current, so the scoped doctor returned needs_human forever. The shared-enable interpretation now has one owner, sharedEnableFlagBinds, used by both the activation rule and the remediation: a row disabled through the shared flag reports the manual conflict and states that rea setup will not change it, instead of an endlessly ineffective repair. Co-Authored-By: Anthropic <noreply@anthropic.com> * fix(doctor): keep a native ZCode disable on the setup repair path The manual-conflict remediation matched a native zcode row through sharedEnableFlagBinds, but setup drops enable:false on single-reader storage, so a native disabled registration was told setup would not change it. The remediation now reads setup's own writer rule, exported as setupPreservesDisabledActivation: shared storage and the zcode fallback view keep the manual-conflict message, while a native row keeps the working rea setup instruction. Regressions pin both remediations. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * revert: drop the unrelated managed-CIL describe split The split does not belong to FreeBuff client support and only widens this PR's diff. 🤖 Generated with Codebuff Co-Authored-By: Codebuff <noreply@codebuff.com> * fix(uninstall): remove the shared agent registration once for both clients ZCode's ~/.agents/mcp.json fallback and FreeBuff's own configuration queued the same physical file twice, so ZCode removed the row and FreeBuff then reported it absent, losing the outcome for the client that owns the file. Resolve every configuration path to one owner -- the client whose configuration it is -- and project that single inspection and removal to each client that loads it. A fallback reader still contributes its discovery probe, so an installed or unresolved reader keeps the shared file fail-closed. Discovery also accepted a dangling ~/.config/freebuff-desktop link, which setup and doctor reject because they follow the target, so an unrelated malformed shared file blocked every other removal. Resolve the link before treating the profile as installation evidence, keeping lstat for removal safety. Also date the FreeBuff release wording against the published 6.7.0 package. * fix(uninstall): keep a row per client when two clients own one file OPENCODE_CONFIG can point OpenCode at FreeBuff's configuration file, where OpenCode writes `mcp.rea` and FreeBuff writes `mcpServers.rea`. Grouping by filename gave that path a single owner, so uninstall removed only OpenCode's row, reported that removal for FreeBuff, and could purge managed data with FreeBuff's registration still active. Share the decision only through a fallback view of another client's row: every client that declares the path as its own configuration keeps its own inspection and removal, and the fallback reader reports each of them. * fix(clients): preserve discovery and fallback registration identity Follow product discovery link targets without losing configuration entry presence or explicitly selected inspections. Associate fallback readers with the format owner's registration table and project outcomes by owner and path, so OpenCode removal cannot be reported as a ZCode fallback removal. All three new boundary regressions fail against the previous source and pass with the fixes. Validation: check:fast; 217 focused tests passed; the two changed test files were rerun with 50 passing tests. No installed FreeBuff client was launched. --------- Co-authored-by: morluto <76467478+morluto@users.noreply.github.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com> Co-authored-by: Kaoru0822 <208281322+kaoru0822-kitauji@users.noreply.github.com> Co-authored-by: Codebuff <noreply@codebuff.com>
1081 lines
34 KiB
TypeScript
1081 lines
34 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
|
import {
|
|
createAnalysisExecution,
|
|
type AnalysisClient,
|
|
type AnalysisProviderCandidate,
|
|
type AnalysisProviderInspectionOptions,
|
|
type CapabilityDescriptor,
|
|
type ProviderAvailability,
|
|
type ProviderIdentity,
|
|
type ProviderTargetSupport,
|
|
} from "../AnalysisProvider.js";
|
|
import { createAnalysisProfile } from "../../domain/analysisProfile.js";
|
|
import type { BinaryTarget } from "../../domain/binaryTargetTypes.js";
|
|
import { ProviderAdapterError } from "../../domain/providerAdapterError.js";
|
|
import { ProviderCleanupError } from "../../domain/providerCleanupError.js";
|
|
import {
|
|
AnalysisUnsupportedTargetError,
|
|
AnalysisCancelledError,
|
|
} from "../../domain/analysisErrorCore.js";
|
|
import { ProviderSelectionError } from "../../domain/providerSelectionError.js";
|
|
import { projectAnalysisError } from "../../domain/analysisErrorProjection.js";
|
|
import { err, ok } from "../../domain/result.js";
|
|
|
|
const DATABASE_TARGET: BinaryTarget = {
|
|
path: "/tmp/fixture.hop",
|
|
sha256: "a".repeat(64),
|
|
kind: "database",
|
|
format: "analysis-database",
|
|
};
|
|
const ARTIFACT_TARGET: BinaryTarget = {
|
|
path: "/tmp/app.asar",
|
|
sha256: "b".repeat(64),
|
|
kind: "archive",
|
|
format: "asar",
|
|
};
|
|
|
|
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);
|
|
});
|
|
|
|
it("uses one owner readiness snapshot for candidate availability and capabilities", async () => {
|
|
const base = candidate("alpha").provider;
|
|
let observed = 0;
|
|
let capabilityReads = 0;
|
|
const provider: AnalysisProviderCandidate = {
|
|
...base,
|
|
inspectAvailability: () => {
|
|
throw new Error("availability must come from the owner snapshot");
|
|
},
|
|
capabilities: () => {
|
|
capabilityReads += 1;
|
|
return [capability(base.identity())];
|
|
},
|
|
inspectReadinessSnapshot: () => {
|
|
observed += 1;
|
|
return {
|
|
availability: {
|
|
status: "unavailable",
|
|
code: "runtime_unavailable",
|
|
reason: "native inspection failed",
|
|
diagnostics: { failure_stage: "self-test" },
|
|
},
|
|
capabilities: [capability(base.identity())],
|
|
};
|
|
},
|
|
};
|
|
|
|
const [status] = await new AnalysisProviderRegistry([provider]).candidates();
|
|
expect(observed).toBe(1);
|
|
expect(capabilityReads).toBe(1);
|
|
expect(status).toMatchObject({
|
|
availability: {
|
|
status: "unavailable",
|
|
code: "runtime_unavailable",
|
|
diagnostics: { failure_stage: "self-test" },
|
|
},
|
|
capabilities: [{ operation: "address_name" }],
|
|
});
|
|
});
|
|
|
|
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",
|
|
},
|
|
},
|
|
});
|
|
|
|
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(await selected.select(DATABASE_TARGET, "alpha")).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
binding: {
|
|
identity: { id: "alpha" },
|
|
selectionSource: "request",
|
|
},
|
|
},
|
|
});
|
|
});
|
|
|
|
describe("inspection without deep binding", () => {
|
|
it("retains discovery facts without resolving a deep profile for covered automatic inspection", async () => {
|
|
const alpha = candidate("alpha", { profile: "error" });
|
|
const beta = candidate("beta", { profile: "error" });
|
|
const registry = new AnalysisProviderRegistry(
|
|
[alpha.provider, beta.provider],
|
|
"auto",
|
|
(target) => target === DATABASE_TARGET,
|
|
);
|
|
expect(await registry.select(DATABASE_TARGET)).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
requestedProviderId: "auto",
|
|
binding: null,
|
|
candidates: [
|
|
{
|
|
provider: { id: "alpha" },
|
|
selected: false,
|
|
availability: { status: "available" },
|
|
},
|
|
{
|
|
provider: { id: "beta" },
|
|
selected: false,
|
|
availability: { status: "available" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
expect(alpha.created).toEqual([]);
|
|
expect(beta.created).toEqual([]);
|
|
});
|
|
|
|
it("keeps explicit request and environment choices even when auxiliary inspection covers the target", async () => {
|
|
const alpha = candidate("alpha");
|
|
const beta = candidate("beta");
|
|
const registry = new AnalysisProviderRegistry(
|
|
[alpha.provider, beta.provider],
|
|
"beta",
|
|
() => true,
|
|
);
|
|
expect(await registry.select(DATABASE_TARGET)).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
binding: { identity: { id: "beta" }, selectionSource: "environment" },
|
|
},
|
|
});
|
|
expect(await registry.select(DATABASE_TARGET, "alpha")).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
binding: { identity: { id: "alpha" }, selectionSource: "request" },
|
|
},
|
|
});
|
|
expect(await registry.select(DATABASE_TARGET, "auto")).toMatchObject({
|
|
ok: true,
|
|
value: { binding: null },
|
|
});
|
|
expect(await registry.select(DATABASE_TARGET, "missing")).toMatchObject({
|
|
ok: false,
|
|
error: { reason: "unknown_provider" },
|
|
});
|
|
});
|
|
|
|
it("preserves ordinary ambiguity when auxiliary inspection does not cover the target", async () => {
|
|
const registry = new AnalysisProviderRegistry(
|
|
[candidate("alpha").provider, candidate("beta").provider],
|
|
"auto",
|
|
() => false,
|
|
);
|
|
expect(await registry.select(DATABASE_TARGET)).toMatchObject({
|
|
ok: false,
|
|
error: { reason: "ambiguous" },
|
|
});
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
expect(
|
|
await registry.select(DATABASE_TARGET, undefined, {
|
|
signal: controller.signal,
|
|
}),
|
|
).toMatchObject({ ok: false, error: { _tag: "AnalysisCancelledError" } });
|
|
});
|
|
});
|
|
|
|
describe("analysis provider registry: selection failures", () => {
|
|
it("offers only admitted providers for ambiguous automatic selection", async () => {
|
|
const alpha = candidate("alpha");
|
|
const beta = candidate("beta");
|
|
const ghidra = candidate("ghidra", {
|
|
available: false,
|
|
unconfigured: true,
|
|
});
|
|
const kuna = candidate("kuna", {
|
|
available: false,
|
|
unconfigured: true,
|
|
});
|
|
const registry = new AnalysisProviderRegistry([
|
|
alpha.provider,
|
|
beta.provider,
|
|
ghidra.provider,
|
|
kuna.provider,
|
|
]);
|
|
|
|
const ambiguous = await registry.select(DATABASE_TARGET);
|
|
expect(ambiguous.ok).toBe(false);
|
|
if (!ambiguous.ok)
|
|
expect(projectAnalysisError(ambiguous.error)).toMatchObject({
|
|
details: {
|
|
selection_reason: "ambiguous",
|
|
candidate_ids: ["alpha", "beta"],
|
|
rejections: [
|
|
{ provider_id: "ghidra", code: "not_configured" },
|
|
{ provider_id: "kuna", code: "not_configured" },
|
|
],
|
|
},
|
|
});
|
|
|
|
for (const selected of [
|
|
await registry.select(DATABASE_TARGET, "alpha"),
|
|
await registry.select(DATABASE_TARGET, "beta"),
|
|
])
|
|
expect(selected).toMatchObject({ ok: true });
|
|
expect([
|
|
...alpha.created,
|
|
...beta.created,
|
|
...ghidra.created,
|
|
...kuna.created,
|
|
]).toEqual([]);
|
|
});
|
|
|
|
it("returns actionable unknown, unavailable, and unsupported failures", async () => {
|
|
const unavailable = candidate("alpha", { available: false });
|
|
const registry = new AnalysisProviderRegistry([unavailable.provider]);
|
|
|
|
const unknown = await registry.select(DATABASE_TARGET, "missing");
|
|
expect(unknown.ok).toBe(false);
|
|
if (!unknown.ok)
|
|
expect(projectAnalysisError(unknown.error)).toMatchObject({
|
|
details: {
|
|
selection_reason: "unknown_provider",
|
|
requested_provider_id: "missing",
|
|
candidate_ids: ["alpha"],
|
|
},
|
|
});
|
|
|
|
const rejected = await registry.select(DATABASE_TARGET, "alpha");
|
|
expect(rejected.ok).toBe(false);
|
|
if (!rejected.ok)
|
|
expect(projectAnalysisError(rejected.error)).toMatchObject({
|
|
code: "provider_unavailable",
|
|
details: {
|
|
rejections: [
|
|
{
|
|
provider_id: "alpha",
|
|
code: "runtime_missing",
|
|
diagnostics: { executable_path: "/opt/alpha/bin/analyze" },
|
|
},
|
|
],
|
|
},
|
|
});
|
|
|
|
const unsupported = await new AnalysisProviderRegistry([
|
|
candidate("alpha", { available: false }).provider,
|
|
]).select(ARTIFACT_TARGET, "alpha");
|
|
if (unsupported.ok)
|
|
throw new Error("expected unsupported target rejection");
|
|
expect(unsupported.error).toBeInstanceOf(ProviderSelectionError);
|
|
if (
|
|
!unsupported.ok &&
|
|
unsupported.error instanceof ProviderSelectionError
|
|
) {
|
|
expect(unsupported.error).toMatchObject({
|
|
reason: "target_unsupported",
|
|
});
|
|
expect(unsupported.error.rejections.map(({ code }) => code)).toEqual([
|
|
"runtime_missing",
|
|
"target_kind_unsupported",
|
|
]);
|
|
}
|
|
});
|
|
|
|
it("keeps artifact-only targets unbound under auto or environment preference", async () => {
|
|
const alpha = candidate("alpha");
|
|
const environment = new AnalysisProviderRegistry([alpha.provider], "alpha");
|
|
const automatic = new AnalysisProviderRegistry([alpha.provider]);
|
|
|
|
for (const registry of [environment, automatic]) {
|
|
const selected = await registry.select(ARTIFACT_TARGET);
|
|
expect(selected).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
binding: null,
|
|
candidates: [
|
|
{
|
|
selected: false,
|
|
targetSupport: {
|
|
status: "unsupported",
|
|
code: "target_kind_unsupported",
|
|
},
|
|
},
|
|
],
|
|
},
|
|
});
|
|
}
|
|
const explicit = await automatic.select(ARTIFACT_TARGET, "alpha");
|
|
if (explicit.ok) throw new Error("expected provider selection rejection");
|
|
expect(explicit.error).toBeInstanceOf(ProviderSelectionError);
|
|
if (explicit.error instanceof ProviderSelectionError)
|
|
expect(explicit.error.reason).toBe("target_unsupported");
|
|
});
|
|
|
|
it("rejects an unknown environment preference even when every candidate rejects the target", async () => {
|
|
const alpha = candidate("alpha");
|
|
const misconfigured = new AnalysisProviderRegistry(
|
|
[alpha.provider],
|
|
"missing",
|
|
);
|
|
|
|
for (const selected of [
|
|
await misconfigured.select(ARTIFACT_TARGET),
|
|
await misconfigured.select(ARTIFACT_TARGET, "missing"),
|
|
]) {
|
|
if (selected.ok) throw new Error("expected unknown provider rejection");
|
|
expect(projectAnalysisError(selected.error)).toMatchObject({
|
|
details: {
|
|
selection_reason: "unknown_provider",
|
|
requested_provider_id: "missing",
|
|
candidate_ids: ["alpha"],
|
|
},
|
|
});
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("analysis provider registry: profile and cleanup failures", () => {
|
|
it("does not bind a profile with unresolved version or adapter failure", async () => {
|
|
const unresolved = candidate("unresolved", { profile: "missing" });
|
|
const failed = candidate("failed", { profile: "error" });
|
|
|
|
const automatic = await new AnalysisProviderRegistry([
|
|
unresolved.provider,
|
|
]).select(DATABASE_TARGET);
|
|
expect(automatic).toMatchObject({
|
|
ok: true,
|
|
value: {
|
|
binding: null,
|
|
candidates: [
|
|
{
|
|
availability: {
|
|
status: "unavailable",
|
|
code: "version_unresolved",
|
|
},
|
|
},
|
|
],
|
|
},
|
|
});
|
|
|
|
const explicit = await new AnalysisProviderRegistry([
|
|
failed.provider,
|
|
]).select(DATABASE_TARGET, "failed");
|
|
if (explicit.ok) throw new Error("expected provider selection rejection");
|
|
expect(explicit.error).toMatchObject({
|
|
_tag: "ProviderAdapterError",
|
|
providerId: "failed",
|
|
});
|
|
});
|
|
|
|
it("aborts automatic selection when a provider reports unconfirmed cleanup", async () => {
|
|
const ghidra = candidate("ghidra");
|
|
const alternate = candidate("hopper");
|
|
const cleanupFailure = new ProviderCleanupError(
|
|
"ghidra",
|
|
["/opt/ghidra/data/languages/x86.ldefs"],
|
|
{ reason: "descriptor close failed" },
|
|
{ operation: "resolve_analysis_profile" },
|
|
);
|
|
const provider: AnalysisProviderCandidate = {
|
|
...ghidra.provider,
|
|
resolveAnalysisProfile: () => Promise.resolve(err(cleanupFailure)),
|
|
};
|
|
|
|
const selected = await new AnalysisProviderRegistry([
|
|
alternate.provider,
|
|
provider,
|
|
]).select(DATABASE_TARGET);
|
|
|
|
expect(selected).toMatchObject({
|
|
ok: false,
|
|
error: {
|
|
_tag: "ProviderAdapterError",
|
|
providerId: "ghidra",
|
|
cleanupIncomplete: true,
|
|
},
|
|
});
|
|
expect(alternate.created).toEqual([]);
|
|
});
|
|
|
|
it("owns a signal-ignoring profile probe until final completion and joins shutdown", async () => {
|
|
const alpha = candidate("alpha");
|
|
let observedSignal: AbortSignal | undefined;
|
|
let finish: (() => void) | undefined;
|
|
let started: (() => void) | undefined;
|
|
const pending = new Promise<void>((resolve) => {
|
|
started = resolve;
|
|
});
|
|
const gate = new Promise<void>((resolve) => {
|
|
finish = resolve;
|
|
});
|
|
const ignoresCancellation: AnalysisProviderCandidate = {
|
|
...alpha.provider,
|
|
resolveAnalysisProfile: async (target, options) => {
|
|
observedSignal = options?.signal;
|
|
started?.();
|
|
await gate;
|
|
return alpha.provider.resolveAnalysisProfile(target);
|
|
},
|
|
};
|
|
const registry = new AnalysisProviderRegistry([ignoresCancellation]);
|
|
const controller = new AbortController();
|
|
const reason = { caller: "profile finalization" };
|
|
let selected = false;
|
|
const selecting = registry
|
|
.select(DATABASE_TARGET, "alpha", { signal: controller.signal })
|
|
.then((result) => {
|
|
selected = true;
|
|
return result;
|
|
});
|
|
await pending;
|
|
controller.abort(reason);
|
|
let closed = false;
|
|
const closing = registry.closeOwnedResources().then((result) => {
|
|
closed = true;
|
|
return result;
|
|
});
|
|
try {
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
expect(selected).toBe(false);
|
|
expect(closed).toBe(false);
|
|
expect(registry.hasPendingOwnedResources()).toBe(true);
|
|
expect(observedSignal?.aborted).toBe(true);
|
|
expect(observedSignal?.reason).toBe(reason);
|
|
finish?.();
|
|
const result = await selecting;
|
|
expect(result).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError", cause: reason },
|
|
});
|
|
expect(await closing).toEqual(ok(null));
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
expect(alpha.created).toEqual([]);
|
|
} finally {
|
|
finish?.();
|
|
await Promise.all([selecting, closing]);
|
|
}
|
|
});
|
|
});
|
|
|
|
interface CandidateFixture {
|
|
readonly provider: AnalysisProviderCandidate;
|
|
readonly created: string[];
|
|
}
|
|
|
|
const candidate = (
|
|
id: string,
|
|
options: {
|
|
readonly available?: boolean;
|
|
readonly unconfigured?: boolean;
|
|
readonly profile?: "resolved" | "missing" | "error";
|
|
} = {},
|
|
): CandidateFixture => {
|
|
const identity: ProviderIdentity = {
|
|
id,
|
|
name: `${id} provider`,
|
|
version: null,
|
|
};
|
|
const created: string[] = [];
|
|
const available = options.available ?? true;
|
|
const provider: AnalysisProviderCandidate = {
|
|
identity: () => identity,
|
|
capabilities: () => [capability(identity)],
|
|
inspectAvailability: (): ProviderAvailability =>
|
|
available
|
|
? {
|
|
status: "available",
|
|
code: null,
|
|
reason: null,
|
|
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
|
}
|
|
: {
|
|
status: "unavailable",
|
|
code: options.unconfigured ? "not_configured" : "runtime_missing",
|
|
reason: `${id} runtime is unavailable`,
|
|
diagnostics: { executable_path: `/opt/${id}/bin/analyze` },
|
|
},
|
|
inspectTargetSupport: (target): ProviderTargetSupport =>
|
|
target.kind === "database"
|
|
? {
|
|
status: "supported",
|
|
code: null,
|
|
reason: null,
|
|
diagnostics: { target_kind: target.kind },
|
|
}
|
|
: {
|
|
status: "unsupported",
|
|
code: "target_kind_unsupported",
|
|
reason: `${id} only accepts analysis databases in this fixture`,
|
|
diagnostics: { target_kind: target.kind },
|
|
},
|
|
resolveAnalysisProfile: () => {
|
|
if (options.profile === "error")
|
|
return Promise.resolve(
|
|
err(new ProviderAdapterError(id, "resolve_analysis_profile")),
|
|
);
|
|
return Promise.resolve(
|
|
ok({
|
|
profile:
|
|
options.profile === "missing"
|
|
? null
|
|
: createAnalysisProfile(
|
|
{ id, name: identity.name, version: "1" },
|
|
{ fixture: id },
|
|
),
|
|
}),
|
|
);
|
|
},
|
|
createClient: (_target, profile): AnalysisClient => {
|
|
created.push(id);
|
|
const executionIdentity = profile?.provider ?? identity;
|
|
return {
|
|
execute: (operation) =>
|
|
Promise.resolve(
|
|
ok(
|
|
createAnalysisExecution(
|
|
operation === "health" ? null : `${id}:${operation}`,
|
|
executionIdentity,
|
|
),
|
|
),
|
|
),
|
|
close: () => Promise.resolve(ok(null)),
|
|
};
|
|
},
|
|
};
|
|
return { provider, created };
|
|
};
|
|
|
|
const capability = (provider: ProviderIdentity): CapabilityDescriptor => ({
|
|
provider,
|
|
operation: "address_name",
|
|
available: true,
|
|
reason: null,
|
|
effects: {
|
|
mutatesArtifact: false,
|
|
launchesProcess: true,
|
|
mayShowUi: false,
|
|
mayAccessNetwork: false,
|
|
mayWriteFilesystem: false,
|
|
changesPermissions: false,
|
|
requiresRoot: false,
|
|
},
|
|
limitations: [],
|
|
});
|
|
|
|
describe("analysis provider registry: explicit profile refusals", () => {
|
|
const refusing = (refusal: AnalysisUnsupportedTargetError) => ({
|
|
...candidate("ghidra").provider,
|
|
resolveAnalysisProfile: () => Promise.resolve(err(refusal)),
|
|
});
|
|
|
|
it("keeps a refusing provider's reason, recovery and evidence in the selection failure", async () => {
|
|
const capturedOutput = {
|
|
stdout: "",
|
|
stderr: "x86-64 only",
|
|
truncated: false,
|
|
};
|
|
const refusal = new AnalysisUnsupportedTargetError(
|
|
"resolve_analysis_profile",
|
|
DATABASE_TARGET.path,
|
|
"The configured extension supports x86-64 only.",
|
|
{
|
|
remediationAction: "Omit the extension setting for this target.",
|
|
capturedOutput,
|
|
diagnostics: { extension: "fixture" },
|
|
},
|
|
);
|
|
const selected = await new AnalysisProviderRegistry([
|
|
refusing(refusal),
|
|
]).select(DATABASE_TARGET, "ghidra");
|
|
if (selected.ok) throw new Error("expected a profile refusal");
|
|
expect(selected.error).toBeInstanceOf(ProviderSelectionError);
|
|
expect(selected.error.cause).toBe(refusal);
|
|
expect(projectAnalysisError(selected.error)).toMatchObject({
|
|
code: "capability_unavailable",
|
|
message: refusal.message,
|
|
remediation: { action: "Omit the extension setting for this target." },
|
|
details: {
|
|
selection_reason: "target_unsupported",
|
|
requested_provider_id: "ghidra",
|
|
candidate_ids: ["ghidra"],
|
|
rejections: [
|
|
{
|
|
provider_id: "ghidra",
|
|
code: "target_format_unsupported",
|
|
reason: "The configured extension supports x86-64 only.",
|
|
},
|
|
],
|
|
captured_output: capturedOutput,
|
|
diagnostics: { extension: "fixture" },
|
|
},
|
|
});
|
|
});
|
|
|
|
it("returns a refusal with unconfirmed cleanup unchanged", async () => {
|
|
const refusal = new AnalysisUnsupportedTargetError(
|
|
"resolve_analysis_profile",
|
|
DATABASE_TARGET.path,
|
|
"The configured extension supports x86-64 only.",
|
|
{ cleanup: { reason: "probe close failed", resources: ["/tmp/probe"] } },
|
|
);
|
|
const selected = await new AnalysisProviderRegistry([
|
|
refusing(refusal),
|
|
]).select(DATABASE_TARGET, "ghidra");
|
|
if (selected.ok) throw new Error("expected a profile refusal");
|
|
expect(selected.error).toBe(refusal);
|
|
expect(projectAnalysisError(selected.error)).toMatchObject({
|
|
code: "cleanup_incomplete",
|
|
details: { cleanup: "incomplete", resources: ["/tmp/probe"] },
|
|
});
|
|
});
|
|
});
|
|
describe("profile resolution terminal facts", () => {
|
|
it.each([false, true])(
|
|
"preserves a physical profile failure across late caller abort (throws: %s)",
|
|
async (throws) => {
|
|
const alpha = candidate("alpha");
|
|
const controller = new AbortController();
|
|
const primary = new ProviderAdapterError(
|
|
"alpha",
|
|
"resolve_analysis_profile",
|
|
{ cause: new Error("physical profile failure") },
|
|
);
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...alpha.provider,
|
|
resolveAnalysisProfile: async () => {
|
|
controller.abort({ caller: "after physical failure" });
|
|
if (throws) throw primary;
|
|
return err(primary);
|
|
},
|
|
},
|
|
]);
|
|
const result = await registry.select(DATABASE_TARGET, "alpha", {
|
|
signal: controller.signal,
|
|
});
|
|
expect(result).toEqual(err(primary));
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
expect(await registry.closeOwnedResources()).toEqual(ok(null));
|
|
},
|
|
);
|
|
|
|
it("preserves exact cancellation with cleanup and blocks admission until its owner confirms release", async () => {
|
|
const alpha = candidate("alpha");
|
|
const controller = new AbortController();
|
|
const reason = { caller: "final cleanup" };
|
|
const primary = new AnalysisCancelledError("resolve_analysis_profile", {
|
|
cause: reason,
|
|
cleanup: { reason: "file close rejected", resources: ["profile-file"] },
|
|
});
|
|
let attempts = 0;
|
|
let allowClose = false;
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...alpha.provider,
|
|
resolveAnalysisProfile: async () => {
|
|
attempts++;
|
|
controller.abort(reason);
|
|
return err(primary);
|
|
},
|
|
closeOwnedResources: async () => {
|
|
if (!allowClose) return err(primary);
|
|
primary.resolveCleanup();
|
|
return ok(null);
|
|
},
|
|
},
|
|
]);
|
|
const result = await registry.select(DATABASE_TARGET, "alpha", {
|
|
signal: controller.signal,
|
|
});
|
|
expect(result).toEqual(err(primary));
|
|
expect(primary.cause).toBe(reason);
|
|
expect(registry.hasPendingOwnedResources()).toBe(true);
|
|
expect(await registry.select(DATABASE_TARGET, "alpha")).toEqual(
|
|
err(primary),
|
|
);
|
|
expect(attempts).toBe(1);
|
|
allowClose = true;
|
|
expect(await registry.closeOwnedResources()).toEqual(ok(null));
|
|
expect(primary.cleanupIncomplete).toBe(false);
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("automatic profile cleanup ownership", () => {
|
|
it.each(["alpha", "beta"])(
|
|
"keeps automatic mixed-child cleanup conjunctive when %s releases first",
|
|
async (first) => {
|
|
const alpha = candidate("alpha");
|
|
const beta = candidate("beta");
|
|
const controller = new AbortController();
|
|
const reason = { caller: "mixed profile finalization" };
|
|
const failures = {
|
|
alpha: new AnalysisCancelledError("resolve_analysis_profile", {
|
|
cause: reason,
|
|
cleanup: { reason: "alpha descriptor", resources: ["alpha-file"] },
|
|
}),
|
|
beta: new ProviderCleanupError("beta", ["beta-file"], {
|
|
reason: "beta descriptor",
|
|
}),
|
|
};
|
|
let entered = 0;
|
|
let admitChildren: (() => void) | undefined;
|
|
const admitted = new Promise<void>((resolve) => {
|
|
admitChildren = resolve;
|
|
});
|
|
const released = new Set<string>();
|
|
const registry = new AnalysisProviderRegistry(
|
|
[alpha, beta].map((fixture) => {
|
|
const id = fixture.provider.identity().id as "alpha" | "beta";
|
|
return {
|
|
...fixture.provider,
|
|
resolveAnalysisProfile: async () => {
|
|
entered++;
|
|
if (entered === 2) {
|
|
controller.abort(reason);
|
|
admitChildren?.();
|
|
}
|
|
await admitted;
|
|
return err(failures[id]);
|
|
},
|
|
closeOwnedResources: async () => {
|
|
if (!released.has(id)) return err(failures[id]);
|
|
failures[id].resolveCleanup();
|
|
return ok(null);
|
|
},
|
|
};
|
|
}),
|
|
);
|
|
const result = await registry.select(DATABASE_TARGET, "auto", {
|
|
signal: controller.signal,
|
|
});
|
|
if (result.ok) throw new Error("Mixed failed profiles admitted");
|
|
expect(result.error.cleanupIncomplete).toBe(true);
|
|
expect(result.error.cleanupResources).toEqual([
|
|
"alpha-file",
|
|
"beta-file",
|
|
]);
|
|
expect(result.error.diagnostics?.profile_errors).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({ provider_id: "alpha" }),
|
|
expect.objectContaining({ provider_id: "beta" }),
|
|
]),
|
|
);
|
|
const close1 = await registry.closeOwnedResources();
|
|
expect(close1.ok).toBe(false);
|
|
released.add(first);
|
|
const close2 = await registry.closeOwnedResources();
|
|
expect(close2.ok).toBe(false);
|
|
expect(result.error.cleanupIncomplete).toBe(true);
|
|
expect(result.error.cleanupResources).toEqual([
|
|
first === "alpha" ? "beta-file" : "alpha-file",
|
|
]);
|
|
expect(close1.ok ? [] : close1.error.cleanupResources).toEqual([
|
|
first === "alpha" ? "beta-file" : "alpha-file",
|
|
]);
|
|
released.add(first === "alpha" ? "beta" : "alpha");
|
|
expect(await registry.closeOwnedResources()).toEqual(ok(null));
|
|
expect(result.error.cleanupIncomplete).toBe(false);
|
|
if (close1.ok || close2.ok)
|
|
throw new Error("Cleanup unexpectedly succeeded");
|
|
expect(close1.error.cleanupIncomplete).toBe(false);
|
|
expect(close2.error.cleanupIncomplete).toBe(false);
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
},
|
|
);
|
|
});
|
|
|
|
it("registers before production and gates fresh selections until shutdown has joined finalization", async () => {
|
|
const alpha = candidate("alpha");
|
|
let calls = 0;
|
|
let enter: (() => void) | undefined;
|
|
let finish: (() => void) | undefined;
|
|
const entered = new Promise<void>((resolve) => {
|
|
enter = resolve;
|
|
});
|
|
const gate = new Promise<void>((resolve) => {
|
|
finish = resolve;
|
|
});
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...alpha.provider,
|
|
resolveAnalysisProfile: async (target) => {
|
|
calls++;
|
|
if (calls === 1) {
|
|
enter?.();
|
|
await gate;
|
|
}
|
|
return alpha.provider.resolveAnalysisProfile(target);
|
|
},
|
|
},
|
|
]);
|
|
const selecting = registry.select(DATABASE_TARGET, "alpha");
|
|
await entered;
|
|
const closing = registry.closeOwnedResources();
|
|
const next = registry.select(DATABASE_TARGET, "alpha");
|
|
try {
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
expect(calls).toBe(1);
|
|
expect(registry.hasPendingOwnedResources()).toBe(true);
|
|
finish?.();
|
|
expect(await selecting).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError" },
|
|
});
|
|
expect(await closing).toEqual(ok(null));
|
|
expect((await next).ok).toBe(true);
|
|
expect(calls).toBe(2);
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
} finally {
|
|
finish?.();
|
|
await Promise.all([selecting, closing, next]);
|
|
await registry.closeOwnedResources();
|
|
}
|
|
});
|
|
|
|
it("joins cancelled readiness finalization and shutdown before admitting another observation", async () => {
|
|
const base = candidate("alpha").provider;
|
|
let enter!: () => void;
|
|
let finish!: () => void;
|
|
const entered = new Promise<void>((resolve) => {
|
|
enter = resolve;
|
|
});
|
|
const gate = new Promise<void>((resolve) => {
|
|
finish = resolve;
|
|
});
|
|
let calls = 0;
|
|
let observed: AbortSignal | undefined;
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...base,
|
|
inspectAvailability: async ({
|
|
signal,
|
|
}: AnalysisProviderInspectionOptions = {}) => {
|
|
calls++;
|
|
if (calls === 1) {
|
|
observed = signal;
|
|
enter();
|
|
await gate;
|
|
}
|
|
return base.inspectAvailability();
|
|
},
|
|
},
|
|
]);
|
|
const controller = new AbortController();
|
|
const reason = { request: "opaque readiness cancellation" };
|
|
let settled = false;
|
|
const observing = registry
|
|
.candidates(undefined, { signal: controller.signal })
|
|
.catch((cause) => {
|
|
settled = true;
|
|
return cause;
|
|
});
|
|
await entered;
|
|
controller.abort(reason);
|
|
let closed = false;
|
|
const closing = registry.closeOwnedResources().then((value) => {
|
|
closed = true;
|
|
return value;
|
|
});
|
|
const next = registry.candidates();
|
|
try {
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
expect(settled).toBe(false);
|
|
expect(closed).toBe(false);
|
|
expect(calls).toBe(1);
|
|
expect(observed?.reason).toBe(reason);
|
|
expect(registry.hasPendingOwnedResources()).toBe(true);
|
|
finish();
|
|
const failure = await observing;
|
|
expect(failure).toBeInstanceOf(AnalysisCancelledError);
|
|
expect(failure.cause).toBe(reason);
|
|
expect(await closing).toEqual(ok(null));
|
|
expect(await next).toMatchObject([
|
|
{
|
|
availability: {
|
|
status: "unknown",
|
|
diagnostics: { finalization: "in_progress" },
|
|
},
|
|
},
|
|
]);
|
|
expect(await registry.candidates()).toHaveLength(1);
|
|
expect(calls).toBe(2);
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
} finally {
|
|
finish();
|
|
await Promise.allSettled([observing, closing, next]);
|
|
await registry.closeOwnedResources();
|
|
}
|
|
});
|
|
|
|
it("joins every candidate and retains physical failure with exact mixed cleanup owners", async () => {
|
|
const alpha = candidate("alpha").provider;
|
|
const beta = candidate("beta").provider;
|
|
const gamma = candidate("gamma").provider;
|
|
let finish!: () => void;
|
|
let enter!: () => void;
|
|
const entered = new Promise<void>((resolve) => {
|
|
enter = resolve;
|
|
});
|
|
const gate = new Promise<void>((resolve) => {
|
|
finish = resolve;
|
|
});
|
|
const physical = new ProviderAdapterError("alpha", "binary_session", {
|
|
diagnostics: { reason: "physical observation failed" },
|
|
});
|
|
const cleanup = new ProviderCleanupError(
|
|
"beta",
|
|
["beta retained prerequisite"],
|
|
{ reason: "controlled cleanup refusal" },
|
|
);
|
|
let releases = 0;
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...alpha,
|
|
inspectAvailability: async () => {
|
|
throw physical;
|
|
},
|
|
},
|
|
{
|
|
...beta,
|
|
inspectAvailability: async () => {
|
|
enter();
|
|
await gate;
|
|
throw cleanup;
|
|
},
|
|
closeOwnedResources: async () => {
|
|
releases++;
|
|
cleanup.resolveCleanup();
|
|
return ok(null);
|
|
},
|
|
},
|
|
gamma,
|
|
]);
|
|
let settled = false;
|
|
const observing = registry.candidates().catch((cause) => {
|
|
settled = true;
|
|
return cause;
|
|
});
|
|
await entered;
|
|
try {
|
|
await new Promise<void>((resolve) => setImmediate(resolve));
|
|
expect(settled).toBe(false);
|
|
finish();
|
|
const failure = await observing;
|
|
expect(failure.cleanupIncomplete).toBe(true);
|
|
expect(failure.cleanupResources).toContain("beta retained prerequisite");
|
|
expect(failure.diagnostics).toMatchObject({
|
|
readiness_candidates: [
|
|
{ provider: { id: "gamma" }, availability: { status: "available" } },
|
|
],
|
|
});
|
|
expect(failure.cleanupPrimary).toBe(physical);
|
|
expect(projectAnalysisError(failure).details).toMatchObject({
|
|
diagnostics: {
|
|
readiness_errors: expect.arrayContaining([
|
|
{
|
|
provider_id: "alpha",
|
|
error: expect.objectContaining({ code: "execution_failure" }),
|
|
},
|
|
{
|
|
provider_id: "beta",
|
|
error: expect.objectContaining({ code: "cleanup_incomplete" }),
|
|
},
|
|
]),
|
|
},
|
|
});
|
|
expect(registry.hasPendingOwnedResources()).toBe(true);
|
|
expect(await registry.closeOwnedResources()).toEqual(ok(null));
|
|
expect(releases).toBe(1);
|
|
expect(failure.cleanupIncomplete).toBe(false);
|
|
expect(projectAnalysisError(failure)).toMatchObject({
|
|
code: "execution_failure",
|
|
details: { diagnostics: { reason: "physical observation failed" } },
|
|
});
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
} finally {
|
|
finish();
|
|
await observing;
|
|
await registry.closeOwnedResources();
|
|
}
|
|
});
|
|
|
|
it("registers selection before async readiness can race shutdown", async () => {
|
|
let calls = 0;
|
|
let observed: AbortSignal | undefined;
|
|
const base = candidate("alpha").provider;
|
|
const registry = new AnalysisProviderRegistry([
|
|
{
|
|
...base,
|
|
inspectAvailability: async ({
|
|
signal,
|
|
}: AnalysisProviderInspectionOptions = {}) => {
|
|
calls++;
|
|
observed = signal;
|
|
return base.inspectAvailability();
|
|
},
|
|
},
|
|
]);
|
|
const selecting = registry.select(DATABASE_TARGET, "alpha");
|
|
const closing = registry.closeOwnedResources();
|
|
const [selected, closed] = await Promise.all([selecting, closing]);
|
|
expect(selected).toMatchObject({
|
|
ok: false,
|
|
error: { _tag: "AnalysisCancelledError" },
|
|
});
|
|
expect(closed).toEqual(ok(null));
|
|
expect(calls).toBe(1);
|
|
expect(observed?.aborted).toBe(true);
|
|
expect((await registry.select(DATABASE_TARGET, "alpha")).ok).toBe(true);
|
|
expect(calls).toBe(2);
|
|
expect(registry.hasPendingOwnedResources()).toBe(false);
|
|
});
|