Files
reverse-engineering-anything/src/process/ArtifactAnalysisResources.test.ts
T
69a2faa120 feat: add FreeBuff agent support for REA setup (#2736)
* 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 on e2fdec384 with {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 base e2fdec384 (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 on 4dbfdf1a9 (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 base 4dbfdf1a9 (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 on 225cb214a (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 recorded 225cb214a baseline (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 on 7572a7082 with 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>
2026-10-25 11:29:17 +08:00

1131 lines
34 KiB
TypeScript

import { AnalysisCleanupLease } from "../artifacts/AnalysisCleanupLease.js";
import {
ArtifactResourceRetryFailure,
ArtifactResourceScope,
} from "../artifacts/ArtifactResourceScope.js";
import { withArtifactRegularFile } from "../artifacts/ArtifactFileOperation.js";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
import { OwnedCommandFailure } from "./OwnedCommand.js";
import { EventEmitter } from "node:events";
import { PassThrough } from "node:stream";
import { expect, it } from "vitest";
import { readStableArtifact } from "../artifacts/readStableArtifact.js";
import { ArtifactReaderFailure } from "../artifacts/ArtifactReader.js";
import {
AnalysisCancelledError,
AnalysisOutputError,
} from "../domain/analysisErrorCore.js";
import { createEvidence } from "../domain/evidence.js";
import { projectAnalysisError } from "../domain/analysisErrorProjection.js";
import { ProviderAdapterError } from "../domain/providerAdapterError.js";
import { ProviderCleanupError } from "../domain/providerCleanupError.js";
import { err, ok } from "../domain/result.js";
import { ArtifactAnalysisResources } from "./ArtifactAnalysisResources.js";
import { readLinuxResourceLimits } from "./LinuxResourceLimits.js";
import { ProviderProcessSupervisor } from "./ProviderProcess.js";
it.each(["command", "limiter"])(
"attributes post-run %s read failure to its exact artifact and retains producer output",
async (failedPath) => {
const source = new ArtifactReaderFailure("path", "Artifact was replaced");
const reads: string[] = [];
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
async (path) => {
reads.push(path);
if (path === failedPath) throw source;
return { bytes: Buffer.from("executable"), sha256: "unchanged" };
},
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const output = {
stdout: "completed observation",
stderr: "producer warning",
truncated: true,
exit_code: 0,
signal: null,
};
try {
const result = await resources.run(async () =>
ok(
await resources.readCommandAfterRun(
"command",
{ path: "limiter", sha256: "unchanged" },
output,
"inspect_signal_decoders",
),
),
);
if (result.ok) throw new Error("Expected failed post-run verification");
expect(result.error).toMatchObject({
_tag: "AnalysisArtifactChangedError",
operation: "inspect_signal_decoders",
path: failedPath,
capturedOutput: output,
});
expect(result.error.cause).toBe(source);
expect(reads).toEqual(
failedPath === "command" ? ["command"] : ["command", "limiter"],
);
} finally {
await resources.close();
}
},
);
it("projects the specific reason and member evidence for retained cleanup", async () => {
const producer = Object.assign(new EventEmitter(), {
stdout: new PassThrough(),
stderr: new PassThrough(),
exitCode: null,
signalCode: null,
kill: () => true,
});
const owner = new ProviderProcessSupervisor({
process: producer,
ownsProcessLifetime: true,
ownership: {
runId: "rea-tshark-run-1",
leaderPid: 4242,
processGroupId: 4242,
},
cleanup: async () => ({
cleaned: false as const,
reason: "process ownership token could not be read for 1 live process",
failures: [
{
pid: 101,
reason: "environment-unreadable" as const,
diagnostic: "sysctl_errno_22",
},
],
unverified: [
{ pid: 900, diagnostic: "platform_binary_environment_withheld" },
],
}),
});
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
resources.retain({ path: "runtime-root", close: async () => {} }, owner);
const result = await resources.finish(
err(new ProviderAdapterError("fixture-provider", "fixture-operation")),
() => {
throw new Error("unexpected success observation");
},
);
owner.dispose();
if (result.ok) throw new Error("expected cleanup failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cleanup_incomplete",
details: {
resources: [
"rea-tshark-run-1",
"runtime-root",
"pid:4242",
"process-group:4242",
],
diagnostics: {
cleanup_error: {
details: {
diagnostics: {
reason:
"process ownership token could not be read for 1 live process",
failures: [
{
pid: 101,
reason: "environment-unreadable",
diagnostic: "sysctl_errno_22",
},
],
unverified: [
{
pid: 900,
diagnostic: "platform_binary_environment_withheld",
},
],
},
},
},
},
},
});
});
it("preserves the primary error and resolves cleanup status after retry", async () => {
let closes = 0;
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
resources.retain({
path: "runtime-root",
close: async () => {
closes++;
if (closes === 1) throw new Error("temporary close failure");
},
});
const primary = new AnalysisOutputError(
"fixture-operation",
"producer returned malformed output",
{
partialObservation: createEvidence(
undefined,
{
id: "fixture",
name: "Fixture",
version: null,
},
{
operation: "inspect_signal_decoders",
parameters: {},
result: { decoders: [] },
confidence: "observed",
},
),
},
);
const result = await resources.finish(err(primary), () => {
throw new Error("unexpected success observation");
});
if (result.ok) throw new Error("expected cleanup failure");
expect(result.error.cause).toBeInstanceOf(AggregateError);
expect((result.error.cause as AggregateError).errors).toEqual([
primary,
expect.any(ProviderCleanupError),
]);
expect(result.error.partialObservation).toEqual(primary.partialObservation);
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.diagnostics).toMatchObject({
primary_error: { code: "unreadable_output" },
});
await resources.release();
expect(result.error.cleanupIncomplete).toBe(false);
expect(closes).toBe(2);
await resources.close();
});
it("resolves each returned cleanup error with its own retained root", async () => {
let closesA = 0;
let closesB = 0;
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
resources.retain({
path: "runtime-root-a",
close: async () => {
closesA++;
if (closesA === 1) throw new Error("root A close failure");
},
});
const first = await resources.finish(
err(new AnalysisOutputError("fixture-operation", "primary failure")),
() => {
throw new Error("unexpected success observation");
},
);
if (first.ok) throw new Error("expected root A cleanup failure");
resources.retain({
path: "runtime-root-b",
close: async () => {
closesB++;
if (closesB === 1) throw new Error("root B close failure");
},
});
const partial = createEvidence(
undefined,
{ id: "fixture", name: "Fixture", version: null },
{
operation: "fixture-operation",
parameters: {},
result: { state: "partial" },
confidence: "observed",
},
);
const second = await resources.finish(ok("completed"), () => partial);
if (second.ok) throw new Error("expected root B cleanup failure");
expect(second.error.partialObservation).toEqual(partial);
expect(first.error.cleanupIncomplete).toBe(false);
expect(second.error.cleanupIncomplete).toBe(true);
await resources.release();
expect(second.error.cleanupIncomplete).toBe(false);
await resources.close();
});
it("resolves an artifact cleanup error when its scope owner later closes", async () => {
let closes = 0;
const readArtifact: typeof readStableArtifact = async (
_path,
_maximumBytes,
_signal,
_fileSystem,
scope,
) => {
if (scope === undefined) throw new Error("expected scoped artifact read");
if (closes === 0) {
const owner = {
kind: "lease",
resource: "fixture descriptor",
lease: new AnalysisCleanupLease(async () => {
closes++;
if (closes === 1) throw new Error("descriptor remains open");
}, ["fixture descriptor"]),
} as const;
expect(await scope.release(owner)).toMatchObject({ kind: "failed" });
throw new ArtifactResourceRetryFailure(
[{ owner, lease: owner.lease }],
"Descriptor close failed",
{
cleanup: {
reason: "descriptor remains open",
resources: ["fixture descriptor"],
},
},
);
}
return { bytes: Buffer.alloc(0), sha256: "0".repeat(64) };
};
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
readArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const first = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
if (first.ok) throw new Error("expected descriptor cleanup failure");
expect(first.error.cleanupIncomplete).toBe(true);
const retried = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
if (!retried.ok) throw retried.error;
expect(retried.value).toEqual({
bytes: Buffer.alloc(0),
sha256: "0".repeat(64),
});
expect(first.error.cleanupIncomplete).toBe(false);
expect(closes).toBe(2);
await resources.close();
});
it("keeps a runtime root until its descriptor cleanup owner is released", async () => {
let descriptorCloses = 0;
let rootCloses = 0;
const readArtifact: typeof readStableArtifact = async (
_path,
_maximumBytes,
_signal,
_fileSystem,
scope,
) => {
if (scope === undefined) throw new Error("expected scoped artifact read");
if (descriptorCloses === 0) {
const owner = {
kind: "lease",
resource: "fixture descriptor",
lease: new AnalysisCleanupLease(async () => {
descriptorCloses++;
if (descriptorCloses === 1)
throw new Error("descriptor remains open");
}, ["fixture descriptor"]),
} as const;
expect(await scope.release(owner)).toMatchObject({ kind: "failed" });
throw new ArtifactResourceRetryFailure(
[{ owner, lease: owner.lease }],
"Descriptor close failed",
{
cleanup: {
reason: "descriptor remains open",
resources: ["fixture descriptor"],
},
},
);
}
return { bytes: Buffer.alloc(0), sha256: "0".repeat(64) };
};
const resources = new ArtifactAnalysisResources(
"fixture-provider",
"fixture-operation",
readArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const first = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
if (first.ok) throw new Error("expected descriptor cleanup failure");
resources.retain({
path: "runtime-root",
close: async () => {
rootCloses++;
},
});
const outer = await resources.finish(first, () => {
throw new Error("unexpected success observation");
});
if (outer.ok) throw new Error("expected combined cleanup failure");
expect(rootCloses).toBe(0);
expect(outer.error.cleanupResources).toEqual([
"fixture descriptor",
"runtime-root",
]);
expect(outer.error.cause).toBeInstanceOf(AggregateError);
expect((outer.error.cause as AggregateError).errors[0]).toBe(first.error);
expect(first.error.cleanupIncomplete).toBe(true);
const retried = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
if (!retried.ok) throw retried.error;
expect(retried.value).toEqual({
bytes: Buffer.alloc(0),
sha256: "0".repeat(64),
});
expect(first.error.cleanupIncomplete).toBe(false);
await resources.release();
expect(rootCloses).toBe(1);
expect(outer.error.cleanupIncomplete).toBe(false);
await resources.close();
});
it.each([
null,
"opaque reason",
new ProviderCleanupError("foreign", ["foreign-resource"], {
reason: "caller cleanup",
}),
])(
"preserves caller cancellation at resource admission: %s",
async (reason) => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
let calls = 0;
try {
const result = await resources.run(async () => {
calls++;
return ok("unexpected");
}, AbortSignal.abort(reason));
expect(result.ok).toBe(false);
if (result.ok) throw new Error("Expected cancelled admission");
expect(result.error.cause).toBe(reason);
expect(result.error.cleanupResources).toEqual([]);
expect(calls).toBe(0);
if (reason instanceof ProviderCleanupError)
expect(reason.cleanupIncomplete).toBe(true);
} finally {
await resources.close();
}
},
);
it.each([
null,
"opaque reason",
new ProviderCleanupError("foreign", ["foreign-resource"], {
reason: "caller cleanup",
}),
])(
"projects the command owner's exact cancellation independently of physical causes: %s",
async (reason) => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const physical = new Error("physical collection interruption");
const failure = new OwnedCommandFailure(
"cancelled",
"cancelled command",
null,
null,
{ cause: physical, cancellation: { reason } },
);
try {
const error = resources.commandFailure(
failure,
{ command_timeout_ms: 100, output_bytes: 1024 },
undefined,
);
expect(error).toMatchObject({ _tag: "AnalysisCancelledError" });
expect(error.cause).toBe(reason);
expect(error.cleanupResources).toEqual([]);
expect(failure.cause).toBe(physical);
if (reason instanceof ProviderCleanupError)
expect(reason.cleanupIncomplete).toBe(true);
} finally {
await resources.close();
}
},
);
it.each([false, true])(
"preserves artifact cancellation and independent failed cleanup (failed close: %s)",
async (failedClose) => {
const reason = { request: "artifact cancellation" };
const root = await createTestTempDirectory("rea-resource-cancel-");
const path = join(root, "descriptor");
await writeFile(path, "authored bytes");
let mayClose = false;
const readArtifact: typeof readStableArtifact = async (
_path,
_limit,
_signal,
_fs,
scope,
) => {
const primary = new ArtifactReaderFailure("cancelled", "read cancelled", {
cause: reason,
});
if (!failedClose) throw primary;
if (scope === undefined) throw new Error("Expected retained file scope");
return withArtifactRegularFile(
path,
scope,
_signal,
async ({ handle: file }) => {
const close = file.close.bind(file);
file.close = async () => {
if (!mayClose) throw new Error("injected descriptor close failure");
await close();
};
throw primary;
},
);
};
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
try {
const result = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
if (result.ok) throw new Error("Expected cancelled artifact read");
const primary = failedClose ? result.error.cleanupPrimary : result.error;
expect(primary).toMatchObject({ _tag: "AnalysisCancelledError" });
expect(primary?.cause).toBe(reason);
expect(result.error.cleanupIncomplete).toBe(failedClose);
mayClose = true;
await resources.close();
expect(result.error.cleanupIncomplete).toBe(false);
expect(primary?.cause).toBe(reason);
} finally {
mayClose = true;
await resources.close();
}
},
);
it("names the fixed producer command deadline and says it has no override", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_packet_fields",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const failure = new OwnedCommandFailure("timeout", "command timed out", null);
try {
const error = resources.commandFailure(
failure,
{ command_timeout_ms: 30_000, output_bytes: 1024 },
undefined,
);
const projected = projectAnalysisError(error);
expect(projected.message).toContain("30000 ms");
expect(projected.remediation.action).toContain(
"this release has no runtime override",
);
expect(projected.remediation.action).not.toContain(
"REA_SWIFTC_COMPILE_TIMEOUT_MS",
);
} finally {
await resources.close();
}
});
it("says REA retains the tighter inherited limit when a producer signal fires", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_packet_fields",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const empty = { text: "", bytes: 0, observedBytes: 0 };
const failure = new OwnedCommandFailure("process", "producer signal", {
stdout: empty,
stderr: empty,
exitCode: null,
signal: "SIGXCPU",
});
try {
const error = resources.commandFailure(
failure,
{ command_timeout_ms: 30_000, output_bytes: 4_194_304 },
{
address_space_bytes: 1_073_741_824,
file_bytes: 67_108_864,
cpu_seconds: 30,
},
);
const projected = projectAnalysisError(error);
expect(projected.remediation.action).toContain(
"REA retains the tighter inherited limit",
);
expect(projected.remediation.action).toContain("1073741824 bytes");
expect(projected.remediation.action).toContain("67108864 bytes");
expect(projected.remediation.action).toContain("30 CPU seconds");
expect(projected.remediation.action).toContain(
"This release has no runtime override",
);
expect(projected.remediation.action).toContain(
"an unchanged retry may succeed or may fail the same way",
);
expect(projected.remediation.action).not.toContain(
"Repeating the unchanged request fails the same way.",
);
expect(projected.retryable).toBe(true);
expect(projected.details).toMatchObject({
reported_limits: { cpu_seconds: 30 },
});
} finally {
await resources.close();
}
});
it("keeps an unchanged SIGXFSZ retry uncertain when the inherited limit was not reported", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_packet_fields",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const empty = { text: "", bytes: 0, observedBytes: 0 };
const failure = new OwnedCommandFailure("process", "producer signal", {
stdout: empty,
stderr: empty,
exitCode: null,
signal: "SIGXFSZ",
});
try {
const projected = projectAnalysisError(
resources.commandFailure(
failure,
{ command_timeout_ms: 30_000, output_bytes: 4_194_304 },
undefined,
),
);
expect(projected.remediation.action).toContain(
"The effective inherited limit was not reported.",
);
expect(projected.remediation.action).toContain(
"an unchanged retry may succeed or may fail the same way",
);
expect(projected.remediation.action).not.toContain(
"Repeating the unchanged request fails the same way.",
);
expect(projected.retryable).toBe(true);
expect(projected.details).toMatchObject({
resource: "file-size",
reported_limits: null,
});
} finally {
await resources.close();
}
});
it("treats a fixed command-output cap as a non-retryable capture allowance", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_packet_fields",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const failure = new OwnedCommandFailure(
"output-limit",
"command output exceeded the retained limit",
null,
);
try {
const error = resources.commandFailure(
failure,
{ command_timeout_ms: 100, output_bytes: 1024 },
undefined,
);
expect(error).toMatchObject({
_tag: "AnalysisResourceConstraintError",
resource: "memory",
reportedLimits: { output_bytes: 1024 },
retryable: false,
});
const projected = projectAnalysisError(error);
expect(projected.retryable).toBe(false);
expect(projected.remediation.action).toContain(
"The retained command-output allowance of 1024 bytes",
);
expect(projected.remediation.action).toContain(
"this release has no runtime override",
);
expect(projected.remediation.action).not.toMatch(
/Review the reported worker memory limits/u,
);
expect(projected.remediation.action).not.toMatch(
/available host memory\. Retry/u,
);
} finally {
await resources.close();
}
});
it("retains a physical command failure when the owner also observed late cancellation", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const reason = { request: "late cancellation" };
const failure = new OwnedCommandFailure(
"process",
"physical failure",
null,
null,
{ cancellation: { reason } },
);
try {
const error = resources.commandFailure(
failure,
{ command_timeout_ms: 100, output_bytes: 1024 },
undefined,
);
expect(error).toMatchObject({ _tag: "AnalysisOutputError" });
expect(error.cause).toBe(failure);
} finally {
await resources.close();
}
});
it("preserves typed caller cancellation through failed workspace cleanup and retry", async () => {
let denied = true;
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const reason = { request: "cancelled before workspace cleanup" };
const primary = new AnalysisCancelledError("inspect_signal_decoders", {
cause: reason,
});
resources.retain({
path: "workspace",
close: async () => {
if (denied) throw new Error("workspace close denied");
},
});
try {
const result = await resources.finish(err(primary), () => {
throw new Error("Must not produce success Evidence");
});
if (result.ok) throw new Error("Expected retained workspace");
expect(result.error.cleanupPrimary).toBe(primary);
expect(result.error.cleanupPrimary?.cause).toBe(reason);
await expect(resources.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
denied = false;
await resources.close();
expect(result.error.cleanupIncomplete).toBe(false);
expect(result.error.cleanupPrimary?.cause).toBe(reason);
} finally {
denied = false;
await resources.close();
}
});
it("observes cancellation after pending descriptor cleanup before admitting replacement work", async () => {
let closes = 0;
let cleanupStarted: () => void = () => {};
const started = new Promise<void>((resolve) => {
cleanupStarted = resolve;
});
let releaseCleanup: () => void = () => {};
const held = new Promise<void>((resolve) => {
releaseCleanup = resolve;
});
const readArtifact: typeof readStableArtifact = async (
_path,
_limit,
_signal,
_fs,
scope,
) => {
if (scope === undefined) throw new Error("Expected file scope");
const retained = {
kind: "lease",
resource: "descriptor",
lease: new AnalysisCleanupLease(async () => {
closes++;
if (closes === 1) throw new Error("descriptor close denied");
cleanupStarted();
await held;
}, ["descriptor"]),
} as const;
await scope.release(retained);
throw new ArtifactResourceRetryFailure(
[{ owner: retained, lease: retained.lease }],
"descriptor cleanup failed",
{
cleanup: {
reason: "descriptor close denied",
resources: ["descriptor"],
},
},
);
};
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
let calls = 0;
try {
const first = await resources.run(async () =>
ok(await resources.read("fixture", 1)),
);
expect(first).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
const caller = new AbortController();
const reason = { request: "cancel while old descriptor closes" };
const pending = resources.run(async () => {
calls++;
return ok("Must not run");
}, caller.signal);
await started;
caller.abort(reason);
releaseCleanup();
const result = await pending;
if (result.ok) throw new Error("Expected cancelled replacement");
expect(result.error.cause).toBe(reason);
expect(calls).toBe(0);
if (!first.ok) expect(first.error.cleanupIncomplete).toBe(false);
} finally {
releaseCleanup();
await resources.close();
}
});
it.each([false, true])(
"keeps an existing physical primary across cleanup-time cancellation (failed close: %s)",
async (failsClose) => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const caller = new AbortController();
const primary = new AnalysisOutputError(
"inspect_signal_decoders",
"physical producer report failure",
);
let denied = failsClose;
resources.retain({
path: "workspace",
close: async () => {
caller.abort({ request: "late cancellation" });
if (denied) throw new Error("workspace close denied");
},
});
try {
const result = await resources.finish(
err(primary),
() => {
throw new Error("Failed work must not produce success Evidence");
},
"inspect_signal_decoders",
caller.signal,
);
if (result.ok) throw new Error("Expected original physical failure");
expect(failsClose ? result.error.cleanupPrimary : result.error).toBe(
primary,
);
denied = false;
await resources.close();
expect(result.error.cleanupIncomplete).toBe(false);
expect(failsClose ? result.error.cleanupPrimary : result.error).toBe(
primary,
);
} finally {
denied = false;
await resources.close();
}
},
);
it("keeps cleanup with no reported capability unresolved instead of clearing it from an empty scope", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const source = new ArtifactReaderFailure("io", "unverified cleanup", {
cleanup: {
reason: "no cleanup capability reported",
resources: ["unverified-resource"],
},
});
const result = await resources.run(async () => {
throw source;
});
if (result.ok) throw new Error("Expected unresolved cleanup");
expect(result.error.cleanupIncomplete).toBe(true);
expect(result.error.cleanupResources).toEqual(["unverified-resource"]);
let calls = 0;
const blocked = await resources.run(async () => {
calls++;
return ok("Must not run");
});
expect(blocked).toMatchObject({
ok: false,
error: { cleanupIncomplete: true },
});
expect(calls).toBe(0);
await expect(resources.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
expect(result.error.cleanupIncomplete).toBe(true);
// No OS resource was supplied. An unresolved observation never grants cleanup authority.
});
it("joins mixed runtime cleanup and resolves each error only through its exact lease", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
let denied = true;
let healthyCloses = 0;
const bad = {
path: "bad-root",
close: async () => {
if (denied) throw new Error("bad root denied");
},
};
const good = {
path: "good-root",
close: async () => {
healthyCloses++;
},
};
resources.retain(bad);
resources.retain(good);
try {
const failure: unknown = await resources
.release()
.catch((cause: unknown) => cause);
expect(failure).toMatchObject({
cleanupIncomplete: true,
cleanupResources: ["bad-root"],
});
expect(healthyCloses).toBe(1);
expect(resources.pendingPaths).toEqual(["bad-root"]);
denied = false;
await resources.close();
expect(failure).toMatchObject({
cleanupIncomplete: false,
cleanupResources: [],
});
expect(healthyCloses).toBe(1);
} finally {
denied = false;
await resources.close();
}
});
it("retains producer output when a completed read is cancelled during failed close", async () => {
const root = await createTestTempDirectory("rea-completed-read-cancel-");
const path = join(root, "descriptor");
await writeFile(path, "authored bytes");
const caller = new AbortController();
const reason = { request: "cancel during close" };
const scope = new ArtifactResourceScope();
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
let mayClose = false;
const output = {
stdout: "completed producer output",
stderr: "",
truncated: false,
exit_code: 0,
};
try {
const cause: unknown = await withArtifactRegularFile(
path,
scope,
caller.signal,
async ({ handle: file }) => {
const close = file.close.bind(file);
file.close = async () => {
caller.abort(reason);
if (!mayClose) throw new Error("controlled descriptor close failure");
await close();
};
return await file.readFile();
},
).catch((cause: unknown) => cause);
if (!(cause instanceof ArtifactReaderFailure))
throw new Error("Expected retained artifact failure");
const error = resources.cleanupFailure(
cause,
() => {
throw new Error("Completed read has no physical failure");
},
output,
);
const primary = error.cleanupPrimary;
expect(primary).toMatchObject({
_tag: "AnalysisCancelledError",
cause: reason,
capturedOutput: output,
});
expect(error.capturedOutput).toEqual(output);
expect(error.cleanupIncomplete).toBe(true);
await expect(scope.close()).rejects.toMatchObject({
reason: "unavailable",
});
mayClose = true;
await scope.close();
expect(error.cleanupIncomplete).toBe(false);
expect(error.cleanupPrimary).toBe(primary);
expect(error.capturedOutput).toEqual(output);
expect(projectAnalysisError(error)).toMatchObject(
projectAnalysisError(primary!),
);
} finally {
mayClose = true;
await scope.close();
await resources.close();
}
});
it("keeps aggregate cleanup live through partial recovery without reclosing healthy roots", async () => {
const resources = new ArtifactAnalysisResources(
"fixture",
"inspect_signal_decoders",
readStableArtifact,
readLinuxResourceLimits,
{ message: "busy", details: {} },
);
const denied = new Set(["first", "second"]);
const closes = new Map<string, number>();
for (const path of ["first", "healthy", "second"])
resources.retain({
path,
close: async () => {
closes.set(path, (closes.get(path) ?? 0) + 1);
if (denied.has(path)) throw new Error(`Close denied: ${path}`);
},
});
try {
const original: unknown = await resources
.release()
.catch((cause: unknown) => cause);
expect(original).toMatchObject({
cleanupIncomplete: true,
cleanupResources: ["first", "second"],
});
expect(closes.get("healthy")).toBe(1);
denied.delete("first");
const retry: unknown = await resources
.release()
.catch((cause: unknown) => cause);
expect(original).toMatchObject({
cleanupIncomplete: true,
cleanupResources: ["second"],
});
expect(retry).toMatchObject({
cleanupIncomplete: true,
cleanupResources: ["second"],
});
expect(resources.pendingPaths).toEqual(["second"]);
denied.clear();
await resources.close();
for (const error of [original, retry])
expect(error).toMatchObject({
cleanupIncomplete: false,
cleanupResources: [],
});
expect(closes).toEqual(
new Map([
["first", 2],
["healthy", 1],
["second", 3],
]),
);
} finally {
denied.clear();
await resources.close();
}
});