mirror of
https://github.com/morluto/rea
synced 2026-10-26 14:25:49 -04:00
69a2faa120
* 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>
1014 lines
35 KiB
TypeScript
1014 lines
35 KiB
TypeScript
import {
|
|
lstat as fsLstat,
|
|
mkdir,
|
|
open as fsOpen,
|
|
readFile,
|
|
realpath as fsRealpath,
|
|
rename,
|
|
writeFile,
|
|
type FileHandle,
|
|
} from "node:fs/promises";
|
|
import { dirname, join } from "node:path";
|
|
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import {
|
|
readClientRegistrationInspections,
|
|
readClientRegistrationStatuses,
|
|
} from "../../../src/application/ClientRegistrationStatus.js";
|
|
import {
|
|
existingMaintenanceScope,
|
|
planIntegrationMaintenance,
|
|
} from "../../../src/application/UpdateMaintenance.js";
|
|
import { ArtifactResourceScope } from "../../../src/artifacts/ArtifactResourceScope.js";
|
|
import { ok } from "../../../src/domain/result.js";
|
|
import type { DoctorHost } from "../../../src/application/Doctor.js";
|
|
import { ConfigurationError } from "../../../src/domain/configurationErrors.js";
|
|
import {
|
|
filterClientsNeedingConfigure,
|
|
systemSetupHost,
|
|
} from "../../../src/application/SetupHost.js";
|
|
import { RegularFileCleanupFailure } from "../../../src/filesystem/OwnedRegularFile.js";
|
|
import { configureDetectedClients } from "../../../src/application/SetupClients.js";
|
|
import { configureClientConfiguration } from "../../../src/application/SetupClientConfiguration.js";
|
|
import {
|
|
systemUninstallHost,
|
|
runUninstall,
|
|
} from "../../../src/application/Uninstall.js";
|
|
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
|
|
|
vi.mock("node:fs/promises", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof import("node:fs/promises")>();
|
|
return {
|
|
...actual,
|
|
open: vi.fn(actual.open),
|
|
lstat: vi.fn(actual.lstat),
|
|
realpath: vi.fn(actual.realpath),
|
|
};
|
|
});
|
|
|
|
const openMock = vi.mocked(fsOpen);
|
|
const lstatMock = vi.mocked(fsLstat);
|
|
const realpathMock = vi.mocked(fsRealpath);
|
|
let actualFs: typeof import("node:fs/promises");
|
|
|
|
beforeEach(async () => {
|
|
actualFs =
|
|
await vi.importActual<typeof import("node:fs/promises")>(
|
|
"node:fs/promises",
|
|
);
|
|
openMock.mockImplementation((...args) => actualFs.open(...args));
|
|
lstatMock.mockImplementation((...args) => actualFs.lstat(...args));
|
|
realpathMock.mockImplementation((...args) => actualFs.realpath(...args));
|
|
});
|
|
|
|
afterEach(() => {
|
|
openMock.mockReset();
|
|
lstatMock.mockReset();
|
|
realpathMock.mockReset();
|
|
});
|
|
|
|
const holdReadHandle = (
|
|
path: string,
|
|
reason: string,
|
|
initiallyHeld = true,
|
|
maxFailures = Number.POSITIVE_INFINITY,
|
|
) => {
|
|
const closeAttempts: FileHandle[] = [];
|
|
let released = false;
|
|
let held = initiallyHeld;
|
|
let remainingFailures = maxFailures;
|
|
openMock.mockImplementation(async (...args) => {
|
|
const handle = await actualFs.open(...args);
|
|
if (String(args[0]) !== path) return handle;
|
|
const nativeClose = handle.close.bind(handle);
|
|
vi.spyOn(handle, "close").mockImplementation(async () => {
|
|
closeAttempts.push(handle);
|
|
if (held && !released && remainingFailures > 0) {
|
|
remainingFailures -= 1;
|
|
throw new Error(reason);
|
|
}
|
|
await nativeClose();
|
|
});
|
|
return handle;
|
|
});
|
|
return {
|
|
closeAttempts,
|
|
hold: () => {
|
|
held = true;
|
|
},
|
|
release: () => {
|
|
released = true;
|
|
},
|
|
};
|
|
};
|
|
|
|
/** Linux setup host with its VS Code client configuration directory prepared. */
|
|
const preparedVsCodeSetupHost = async (prefix: string) => {
|
|
const home = await createTestTempDirectory(prefix);
|
|
const host = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home, XDG_CONFIG_HOME: join(home, "xdg") },
|
|
);
|
|
const client = (await host.supportedClients()).find(
|
|
({ name }) => name === "vscode",
|
|
);
|
|
if (client === undefined) throw new Error("VS Code setup client missing");
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
return { home, host, client };
|
|
};
|
|
|
|
/** Release the held read handle and verify host cleanup retries that same owner. */
|
|
const expectCloseReclaimsHandle = async (
|
|
host: { close?: () => Promise<unknown> },
|
|
closeAttempts: readonly object[],
|
|
release: () => void,
|
|
) => {
|
|
const attemptsBeforeClose = closeAttempts.length;
|
|
release();
|
|
expect(await host.close?.()).toBeUndefined();
|
|
expect(closeAttempts).toHaveLength(attemptsBeforeClose + 1);
|
|
expect(closeAttempts.at(-1)).toBe(closeAttempts[0]);
|
|
};
|
|
|
|
/** Give up on the assertion path: release the handle and let cleanup close it. */
|
|
const cleanupHeldHandle = async (
|
|
host: { close?: () => Promise<unknown> },
|
|
release: () => void,
|
|
) => {
|
|
release();
|
|
await host.close?.();
|
|
};
|
|
|
|
it("retains invalid UTF-8 diagnostics and the uninstall read owner when close fails", async () => {
|
|
const home = await createTestTempDirectory("rea-uninstall-utf8-close-");
|
|
const path = join(home, "client.json");
|
|
const original = Buffer.from([0xff]);
|
|
await writeFile(path, original);
|
|
const { closeAttempts, release } = holdReadHandle(
|
|
path,
|
|
"held uninstall handle",
|
|
);
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
expect(
|
|
await host.removeClient({
|
|
name: "cursor",
|
|
format: "json",
|
|
configPath: path,
|
|
}),
|
|
).toMatchObject({
|
|
status: "failed",
|
|
detail: expect.stringContaining("not valid UTF-8"),
|
|
});
|
|
expect(Buffer.compare(await readFile(path), original)).toBe(0);
|
|
expect(closeAttempts).toHaveLength(3);
|
|
expect(closeAttempts.every((handle) => handle === closeAttempts[0])).toBe(
|
|
true,
|
|
);
|
|
await expectCloseReclaimsHandle(host, closeAttempts, release);
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
it("stops uninstall and retains the backup read owner when its close fails", async () => {
|
|
const home = await createTestTempDirectory("rea-uninstall-backup-close-");
|
|
const path = join(home, "client.json");
|
|
const client = { name: "cursor", format: "json", configPath: path } as const;
|
|
await writeFile(path, '{"keep":"before setup"}\n');
|
|
expect(
|
|
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
|
).toMatchObject({ status: "configured" });
|
|
const configured = await readFile(path, "utf8");
|
|
const { closeAttempts, release } = holdReadHandle(
|
|
`${path}.rea.backup`,
|
|
"held backup handle",
|
|
);
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
expect(await host.removeClient(client)).toEqual({
|
|
name: "cursor",
|
|
status: "failed",
|
|
detail:
|
|
"Configuration could not be backed up, so no change was made. Check file permissions, then rerun uninstall.",
|
|
});
|
|
expect(await readFile(path, "utf8")).toBe(configured);
|
|
expect(closeAttempts).toHaveLength(2);
|
|
await expectCloseReclaimsHandle(host, closeAttempts, release);
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
it("keeps shared-ownership proof when the ownership read completes but its close fails", async () => {
|
|
// FreeBuff without a profile marker leaves its shared storage applicability-
|
|
// unverified. The completed ownership read is the proof that later read
|
|
// failures are blocking; discarding it softens every failure to retained,
|
|
// so purge runs while the active shared registration remains.
|
|
const home = await createTestTempDirectory("rea-freebuff-ownership-close-");
|
|
const setupHost = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home },
|
|
);
|
|
const client = (await setupHost.supportedClients()).find(
|
|
({ name }) => name === "freebuff",
|
|
);
|
|
if (client === undefined) throw new Error("freebuff client missing");
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
await writeFile(
|
|
client.configPath,
|
|
JSON.stringify({ mcpServers: { other: { command: "other" } } }),
|
|
);
|
|
expect(
|
|
await configureClientConfiguration(client, {}, ["rea", "mcp"]),
|
|
).toMatchObject({ status: "configured" });
|
|
const state = join(home, ".rea", "state.json");
|
|
await mkdir(dirname(state), { recursive: true });
|
|
await writeFile(state, "{}\n");
|
|
const { release } = holdReadHandle(
|
|
client.configPath,
|
|
"held ownership read handle",
|
|
);
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
const result = await runUninstall(true, host);
|
|
expect(result.status).toBe("failed");
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({ name: "freebuff", status: "failed" }),
|
|
);
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({
|
|
name: "uninstall",
|
|
status: "skipped",
|
|
detail: expect.stringContaining(
|
|
"No REA registration, skill, or data was removed",
|
|
),
|
|
}),
|
|
);
|
|
// Data must not be purged while the shared registration is still active.
|
|
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
it("keeps shared-ownership proof when removal refuses a shadowed duplicate", async () => {
|
|
// The effective row is REA-owned while an earlier duplicate is foreign, so
|
|
// removal refuses the edit. That refusal must not erase ownership: without
|
|
// the positive row fact, recurring close failures soften to retained and
|
|
// purge runs while the owned row remains active.
|
|
const home = await createTestTempDirectory("rea-freebuff-shadowed-close-");
|
|
const setupHost = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home },
|
|
);
|
|
const client = (await setupHost.supportedClients()).find(
|
|
({ name }) => name === "freebuff",
|
|
);
|
|
if (client === undefined) throw new Error("freebuff client missing");
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
await writeFile(
|
|
client.configPath,
|
|
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]},"rea":{"command":"rea","args":["mcp"]}}}',
|
|
);
|
|
const state = join(home, ".rea", "state.json");
|
|
await mkdir(dirname(state), { recursive: true });
|
|
await writeFile(state, "{}\n");
|
|
const { release } = holdReadHandle(
|
|
client.configPath,
|
|
"held ownership read handle",
|
|
);
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
const result = await runUninstall(true, host);
|
|
expect(result.status).toBe("failed");
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({ name: "freebuff", status: "failed" }),
|
|
);
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({
|
|
name: "uninstall",
|
|
status: "skipped",
|
|
detail: expect.stringContaining(
|
|
"No REA registration, skill, or data was removed",
|
|
),
|
|
}),
|
|
);
|
|
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
it("stops removal when a completed reread leaves its handle unreleased", async () => {
|
|
// Greptile P1: preflight and reread both complete with a foreign-only row,
|
|
// but the reread handle cannot be closed even by the cleanup retry. REA
|
|
// still owns that open handle, so removal must stop before purge: serving
|
|
// the completed text would let removeAll delete managed data while the
|
|
// incomplete cleanup is only reported later, by close().
|
|
const home = await createTestTempDirectory("rea-freebuff-reread-leak-");
|
|
const setupHost = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home },
|
|
);
|
|
const client = (await setupHost.supportedClients()).find(
|
|
({ name }) => name === "freebuff",
|
|
);
|
|
if (client === undefined) throw new Error("freebuff client missing");
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
await writeFile(
|
|
client.configPath,
|
|
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
|
|
);
|
|
const state = join(home, ".rea", "state.json");
|
|
await mkdir(dirname(state), { recursive: true });
|
|
await writeFile(state, "{}\n");
|
|
const { hold, release } = holdReadHandle(
|
|
client.configPath,
|
|
"held removal reread handle",
|
|
false,
|
|
);
|
|
const base = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
const host = {
|
|
...base,
|
|
inspectSkill: async () => {
|
|
hold();
|
|
return base.inspectSkill?.();
|
|
},
|
|
};
|
|
try {
|
|
const result = await runUninstall(true, host);
|
|
expect(result.status).toBe("failed");
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({
|
|
name: "freebuff",
|
|
status: "failed",
|
|
detail: expect.stringContaining("its resources could not be released"),
|
|
}),
|
|
);
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({
|
|
name: "uninstall",
|
|
status: "skipped",
|
|
detail: expect.stringContaining("Uninstall stopped at this failure"),
|
|
}),
|
|
);
|
|
// Managed data must survive an unreleased read handle.
|
|
await expect(readFile(state, "utf8")).resolves.toBe("{}\n");
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
it("keeps the shared registration fail-closed when ZCode's probe is unresolved", async () => {
|
|
// A denied profile probe leaves ZCode's applicability unresolved, never
|
|
// absent: the shared file stays fail-closed so its row is inspected and
|
|
// removed instead of leaving an installed ZCode wired to purged data.
|
|
// Definitive absence still leaves the file to FreeBuff, ZCode's owner.
|
|
const home = await createTestTempDirectory("rea-zcode-fallback-unresolved-");
|
|
const fallback = join(home, ".agents", "mcp.json");
|
|
const profile = join(home, ".zcode", "cli");
|
|
lstatMock.mockImplementation((path) =>
|
|
String(path) === profile
|
|
? Promise.reject(
|
|
Object.assign(new Error("EACCES: permission denied, lstat"), {
|
|
code: "EACCES",
|
|
}),
|
|
)
|
|
: actualFs.lstat(path),
|
|
);
|
|
const unresolved = systemUninstallHost(
|
|
home,
|
|
undefined,
|
|
{ HOME: home },
|
|
"linux",
|
|
);
|
|
try {
|
|
const rows = (await unresolved.clients()).filter(
|
|
(candidate) => candidate.configPath === fallback,
|
|
);
|
|
// One physical file, one owner: FreeBuff edits the shared file once and
|
|
// ZCode reports that same outcome instead of racing it to "absent".
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]).toMatchObject({ name: "freebuff", sharedWith: ["zcode"] });
|
|
// Fail-closed: the unresolved reader carries no unverified softening, so a
|
|
// failed read blocks removal instead of retaining around the purge.
|
|
expect(rows[0]?.applicability).toBeUndefined();
|
|
} finally {
|
|
await unresolved.close?.();
|
|
}
|
|
lstatMock.mockImplementation((...args) => actualFs.lstat(...args));
|
|
const absent = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
const rows = (await absent.clients()).filter(
|
|
(candidate) => candidate.configPath === fallback,
|
|
);
|
|
expect(rows).toHaveLength(1);
|
|
// Definitive absence keeps ZCode out of another product's primary storage.
|
|
expect(rows[0]?.sharedWith).toBeUndefined();
|
|
} finally {
|
|
await absent.close?.();
|
|
}
|
|
});
|
|
|
|
it("removes a shared registration once and reports that outcome to both clients", async () => {
|
|
// ZCode and FreeBuff both load ~/.agents/mcp.json. Queuing it per client
|
|
// removed the row as ZCode and then reported FreeBuff as "absent", losing
|
|
// the outcome for the client that owns the file, and it read and edited one
|
|
// shared resource twice.
|
|
const home = await createTestTempDirectory("rea-shared-removal-once-");
|
|
const shared = join(home, ".agents", "mcp.json");
|
|
await mkdir(join(home, ".zcode", "cli"), { recursive: true });
|
|
await mkdir(join(home, ".config", "freebuff-desktop"), { recursive: true });
|
|
expect(
|
|
await configureClientConfiguration(
|
|
{ name: "freebuff", format: "json", configPath: shared },
|
|
{},
|
|
["rea", "mcp"],
|
|
),
|
|
).toMatchObject({ status: "configured" });
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
const result = await runUninstall(false, host);
|
|
expect(result.status).toBe("complete");
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({
|
|
name: "freebuff",
|
|
status: "removed",
|
|
configuration_path: shared,
|
|
}),
|
|
);
|
|
// The fallback reader reports the owner's removal, never "absent".
|
|
const zcode = result.items.find(({ name }) => name === "zcode");
|
|
expect(zcode?.actions).toContainEqual(
|
|
expect.objectContaining({
|
|
status: "removed",
|
|
configuration_path: shared,
|
|
}),
|
|
);
|
|
expect(zcode?.actions).not.toContainEqual(
|
|
expect.objectContaining({
|
|
status: "skipped",
|
|
configuration_path: shared,
|
|
}),
|
|
);
|
|
expect(JSON.parse(await readFile(shared, "utf8"))).toEqual({
|
|
mcpServers: {},
|
|
});
|
|
} finally {
|
|
await host.close?.();
|
|
}
|
|
});
|
|
|
|
it("keeps one row per client when OpenCode is pointed at FreeBuff's file", async () => {
|
|
// OPENCODE_CONFIG can make OpenCode and FreeBuff edit one file with different
|
|
// tables (`mcp.rea` and `mcpServers.rea`). Sharing one decision by filename
|
|
// would remove only OpenCode's row and report it for FreeBuff too, leaving
|
|
// FreeBuff registered while uninstall reports complete.
|
|
const home = await createTestTempDirectory("rea-shared-dialects-");
|
|
const shared = join(home, ".agents", "mcp.json");
|
|
await mkdir(dirname(shared), { recursive: true });
|
|
await mkdir(join(home, ".config", "freebuff-desktop"), { recursive: true });
|
|
expect(
|
|
await configureClientConfiguration(
|
|
{ name: "freebuff", format: "json", configPath: shared },
|
|
{},
|
|
["rea", "mcp"],
|
|
),
|
|
).toMatchObject({ status: "configured" });
|
|
const host = systemUninstallHost(
|
|
home,
|
|
undefined,
|
|
{ HOME: home, OPENCODE_CONFIG: shared },
|
|
"linux",
|
|
);
|
|
try {
|
|
const rows = (await host.clients()).filter(
|
|
(candidate) => candidate.configPath === shared,
|
|
);
|
|
expect(rows.map(({ name }) => name).sort()).toEqual([
|
|
"freebuff",
|
|
"opencode",
|
|
]);
|
|
expect(await runUninstall(false, host)).toMatchObject({
|
|
status: "complete",
|
|
});
|
|
expect(JSON.parse(await readFile(shared, "utf8"))).toEqual({
|
|
mcpServers: {},
|
|
});
|
|
} finally {
|
|
await host.close?.();
|
|
}
|
|
});
|
|
|
|
it.each([true, false])(
|
|
"projects only the shared table's outcome to ZCode (shared row owned: %s)",
|
|
async (sharedOwned) => {
|
|
const home = await createTestTempDirectory("rea-shared-table-outcome-");
|
|
const shared = join(home, ".agents", "mcp.json");
|
|
const zcodePath = join(home, ".zcode", "cli", "config.json");
|
|
await mkdir(dirname(shared), { recursive: true });
|
|
await mkdir(dirname(zcodePath), { recursive: true });
|
|
await writeFile(zcodePath, '{"mcp":{"servers":{}}}');
|
|
await writeFile(
|
|
shared,
|
|
JSON.stringify({
|
|
mcp: {
|
|
rea: {
|
|
type: "local",
|
|
command: [sharedOwned ? "foreign-server" : "rea", "mcp"],
|
|
},
|
|
},
|
|
mcpServers: {
|
|
rea: {
|
|
command: sharedOwned ? "rea" : "foreign-server",
|
|
args: ["mcp"],
|
|
},
|
|
},
|
|
}),
|
|
);
|
|
const host = systemUninstallHost(
|
|
home,
|
|
undefined,
|
|
{ HOME: home, OPENCODE_CONFIG: shared },
|
|
"linux",
|
|
);
|
|
try {
|
|
const result = await runUninstall(false, host);
|
|
expect(result.status).toBe("complete");
|
|
const zcode = result.items.find(({ name }) => name === "zcode");
|
|
expect(zcode?.status).toBe(sharedOwned ? "removed" : "retained");
|
|
expect(
|
|
zcode?.actions?.filter(
|
|
({ configuration_path }) => configuration_path === shared,
|
|
),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
status: sharedOwned ? "removed" : "retained",
|
|
}),
|
|
]);
|
|
const remaining = JSON.parse(await readFile(shared, "utf8"));
|
|
expect(remaining.mcp).toEqual(
|
|
sharedOwned
|
|
? { rea: { type: "local", command: ["foreign-server", "mcp"] } }
|
|
: {},
|
|
);
|
|
expect(remaining.mcpServers).toEqual(
|
|
sharedOwned
|
|
? {}
|
|
: { rea: { command: "foreign-server", args: ["mcp"] } },
|
|
);
|
|
} finally {
|
|
await host.close?.();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("does not treat a dangling FreeBuff profile link as installed", async () => {
|
|
// Setup and doctor follow ~/.config/freebuff-desktop and reject a link whose
|
|
// target is gone. Discovery must agree: counting the leftover link as an
|
|
// installed product turns an unrelated malformed shared file into a blocking
|
|
// failure that stops every other REA removal.
|
|
const home = await createTestTempDirectory("rea-freebuff-dangling-profile-");
|
|
const shared = join(home, ".agents", "mcp.json");
|
|
const profile = join(home, ".config", "freebuff-desktop");
|
|
const cursor = join(home, ".cursor", "mcp.json");
|
|
await mkdir(dirname(shared), { recursive: true });
|
|
await writeFile(shared, "{ not json");
|
|
await mkdir(dirname(cursor), { recursive: true });
|
|
await writeFile(cursor, '{"keep":"before setup"}\n');
|
|
expect(
|
|
await configureClientConfiguration(
|
|
{ name: "cursor", format: "json", configPath: cursor },
|
|
{},
|
|
["rea", "mcp"],
|
|
),
|
|
).toMatchObject({ status: "configured" });
|
|
lstatMock.mockImplementation((path) =>
|
|
String(path) === profile
|
|
? Promise.resolve({
|
|
isFile: () => false,
|
|
isDirectory: () => false,
|
|
isSymbolicLink: () => true,
|
|
} as unknown as Awaited<ReturnType<typeof fsLstat>>)
|
|
: actualFs.lstat(path),
|
|
);
|
|
realpathMock.mockImplementation((path) =>
|
|
String(path) === profile
|
|
? Promise.reject(
|
|
Object.assign(
|
|
new Error("ENOENT: no such file or directory, realpath"),
|
|
{ code: "ENOENT" },
|
|
),
|
|
)
|
|
: actualFs.realpath(path),
|
|
);
|
|
const host = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
try {
|
|
const result = await runUninstall(false, host);
|
|
expect(result.status).toBe("complete");
|
|
// The unrelated registration is removed instead of blocked.
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({ name: "cursor", status: "removed" }),
|
|
);
|
|
expect(JSON.parse(await readFile(cursor, "utf8"))).not.toHaveProperty(
|
|
"mcpServers.rea",
|
|
);
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({ name: "freebuff", status: "retained" }),
|
|
);
|
|
} finally {
|
|
await host.close?.();
|
|
}
|
|
});
|
|
|
|
it("serves a completed removal reread when its close retry releases the handle", async () => {
|
|
// Preflight saw no owned row; another writer adds one before removal. The
|
|
// reread's first close fails but its cleanup retry releases the handle:
|
|
// the completed text is the ownership evidence that drives removal of the
|
|
// concurrently added row instead of softening to retained and leaving it
|
|
// active while data is purged.
|
|
const home = await createTestTempDirectory("rea-freebuff-reread-close-");
|
|
const setupHost = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home },
|
|
);
|
|
const client = (await setupHost.supportedClients()).find(
|
|
({ name }) => name === "freebuff",
|
|
);
|
|
if (client === undefined) throw new Error("freebuff client missing");
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
await writeFile(
|
|
client.configPath,
|
|
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
|
|
);
|
|
const cacheOwned = join(home, ".rea", "cache", "owned");
|
|
await mkdir(dirname(cacheOwned), { recursive: true });
|
|
await writeFile(cacheOwned, "owned\n");
|
|
const { hold, release } = holdReadHandle(
|
|
client.configPath,
|
|
"held removal reread handle",
|
|
false,
|
|
1,
|
|
);
|
|
const base = systemUninstallHost(home, undefined, { HOME: home }, "linux");
|
|
const host = {
|
|
...base,
|
|
inspectSkill: async () => {
|
|
// Another writer registers REA between preflight and removal.
|
|
await writeFile(
|
|
client.configPath,
|
|
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}',
|
|
);
|
|
hold();
|
|
return base.inspectSkill?.();
|
|
},
|
|
};
|
|
try {
|
|
const result = await runUninstall(true, host);
|
|
expect(result.status).toBe("complete");
|
|
expect(result.items).toContainEqual(
|
|
expect.objectContaining({ name: "freebuff", status: "removed" }),
|
|
);
|
|
expect(await readFile(client.configPath, "utf8")).not.toContain("rea");
|
|
await expect(readFile(cacheOwned)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
});
|
|
|
|
describe("ZCode fallback cleanup ownership", () => {
|
|
it.each(["preflight", "configure"])(
|
|
"retains a failed ZCode fallback close during %s until host cleanup",
|
|
async (operation) => {
|
|
const home = await createTestTempDirectory("rea-zcode-fallback-close-");
|
|
const host = systemSetupHost(
|
|
{ platform: "linux", homeDirectory: home } as DoctorHost,
|
|
{ HOME: home },
|
|
);
|
|
const client = (await host.supportedClients()).find(
|
|
({ name }) => name === "zcode",
|
|
);
|
|
if (client?.zcodeFallbackPath === undefined)
|
|
throw new Error("ZCode fallback path missing");
|
|
const fallback = client.zcodeFallbackPath;
|
|
await mkdir(dirname(fallback), { recursive: true });
|
|
const original = '{"mcpServers":{"other":{"command":"other"}}}\n';
|
|
await writeFile(fallback, original);
|
|
const { closeAttempts, release } = holdReadHandle(
|
|
fallback,
|
|
"held fallback handle",
|
|
);
|
|
try {
|
|
const action =
|
|
operation === "preflight"
|
|
? host.inspectClientConfiguration?.(client, {}, ["rea", "mcp"])
|
|
: host.configureClient(client, {}, ["rea", "mcp"]);
|
|
if (action === undefined) throw new Error("setup preflight missing");
|
|
await expect(action).rejects.toMatchObject({
|
|
_tag: "ConfigurationError",
|
|
cause: expect.any(RegularFileCleanupFailure),
|
|
cleanup: { resources: [fallback] },
|
|
});
|
|
expect(closeAttempts).toHaveLength(2);
|
|
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
|
expect(await readFile(fallback, "utf8")).toBe(original);
|
|
await expect(readFile(client.configPath)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
await expectCloseReclaimsHandle(host, closeAttempts, release);
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
},
|
|
);
|
|
});
|
|
|
|
describe("setup client configuration cleanup ownership", () => {
|
|
it.each([
|
|
["valid UTF-8", Buffer.from('{"servers": {"other": {}}}\n')],
|
|
["malformed UTF-8", Buffer.from([0xff])],
|
|
] as const)(
|
|
"stops configuration and retains the %s read owner until host close",
|
|
async (encoding, original) => {
|
|
const { host, client } = await preparedVsCodeSetupHost(
|
|
"rea-setup-config-close-",
|
|
);
|
|
await writeFile(client.configPath, original);
|
|
|
|
const { closeAttempts, release } = holdReadHandle(
|
|
client.configPath,
|
|
"test holds the config handle open",
|
|
);
|
|
const configure = vi.spyOn(host, "configureClient");
|
|
|
|
try {
|
|
const failure = await filterClientsNeedingConfigure(
|
|
host,
|
|
[client],
|
|
{},
|
|
["rea", "mcp"],
|
|
)
|
|
.then((detectedClients) =>
|
|
configureDetectedClients({
|
|
host,
|
|
detectedClients,
|
|
providerEnvironment: {},
|
|
command: ["rea", "mcp"],
|
|
clients: {},
|
|
appliedActions: [],
|
|
}),
|
|
)
|
|
.then(
|
|
() => undefined,
|
|
(cause: unknown) => cause,
|
|
);
|
|
expect(failure).toBeInstanceOf(ConfigurationError);
|
|
if (!(failure instanceof ConfigurationError))
|
|
throw new Error(
|
|
"Expected the configuration failure to retain cleanup authority",
|
|
);
|
|
if (encoding === "malformed UTF-8")
|
|
expect(failure).toMatchObject({
|
|
cause: {
|
|
outcome: { kind: "failed", cause: expect.any(TypeError) },
|
|
},
|
|
});
|
|
expect(failure).toMatchObject({
|
|
_tag: "ConfigurationError",
|
|
cause: expect.any(RegularFileCleanupFailure),
|
|
cleanup: {
|
|
resources: [client.configPath],
|
|
reason: expect.stringContaining(
|
|
"test holds the config handle open",
|
|
),
|
|
},
|
|
});
|
|
expect(configure).not.toHaveBeenCalled();
|
|
expect(closeAttempts).toHaveLength(2);
|
|
expect(closeAttempts[0]).toBe(closeAttempts[1]);
|
|
expect(
|
|
Buffer.compare(await readFile(client.configPath), original),
|
|
).toBe(0);
|
|
|
|
await expectCloseReclaimsHandle(host, closeAttempts, release);
|
|
expect(failure.cleanupIncomplete).toBe(false);
|
|
expect(failure.cleanupResources).toEqual([]);
|
|
} finally {
|
|
await cleanupHeldHandle(host, release);
|
|
}
|
|
},
|
|
);
|
|
|
|
it("waits for an admitted configuration read and rejects later admissions", async () => {
|
|
const { host, client } = await preparedVsCodeSetupHost(
|
|
"rea-setup-config-inflight-",
|
|
);
|
|
await writeFile(client.configPath, '{"servers": {}}\n');
|
|
|
|
let beginRead!: () => void;
|
|
const readStarted = new Promise<void>((resolve) => {
|
|
beginRead = resolve;
|
|
});
|
|
let unblockRead!: () => void;
|
|
const readGate = new Promise<void>((resolve) => {
|
|
unblockRead = resolve;
|
|
});
|
|
let heldRead = false;
|
|
openMock.mockImplementation(async (...args) => {
|
|
const handle = await actualFs.open(...args);
|
|
if (String(args[0]) !== client.configPath || heldRead) return handle;
|
|
heldRead = true;
|
|
const nativeRead = handle.read.bind(handle);
|
|
vi.spyOn(handle, "read").mockImplementation(async (...readArgs) => {
|
|
beginRead();
|
|
await readGate;
|
|
return nativeRead(...readArgs);
|
|
});
|
|
return handle;
|
|
});
|
|
|
|
let hostCloseFinished = false;
|
|
let alignment: Promise<boolean> | undefined;
|
|
try {
|
|
alignment = host.clientNeedsConfigure(client, {}, ["rea", "mcp"]);
|
|
await readStarted;
|
|
|
|
const close = host.close;
|
|
if (close === undefined) throw new Error("Setup host close is missing");
|
|
const closeResult = close().then((result) => {
|
|
hostCloseFinished = true;
|
|
return result;
|
|
});
|
|
|
|
const lateAdmission = await host
|
|
.clientNeedsConfigure(client, {}, ["rea", "mcp"])
|
|
.then(
|
|
() => undefined,
|
|
(cause: unknown) => cause,
|
|
);
|
|
expect(lateAdmission).toBeInstanceOf(ConfigurationError);
|
|
expect(lateAdmission).toMatchObject({
|
|
message: expect.stringContaining("Artifact resource scope is closed"),
|
|
});
|
|
expect(hostCloseFinished).toBe(false);
|
|
|
|
unblockRead();
|
|
await expect(alignment).resolves.toBe(true);
|
|
expect(await closeResult).toBeUndefined();
|
|
expect(hostCloseFinished).toBe(true);
|
|
} finally {
|
|
unblockRead();
|
|
await alignment?.catch(() => undefined);
|
|
await host.close?.();
|
|
}
|
|
});
|
|
});
|
|
|
|
const unscopedRegistrationReaders: readonly {
|
|
readonly name: string;
|
|
readonly read: (
|
|
home: string,
|
|
environment: NodeJS.ProcessEnv,
|
|
execute: Parameters<typeof planIntegrationMaintenance>[3],
|
|
) => Promise<unknown>;
|
|
}[] = [
|
|
{
|
|
name: "inspections",
|
|
read: (home, environment) =>
|
|
readClientRegistrationInspections(home, "/current/rea", { environment }),
|
|
},
|
|
{
|
|
name: "statuses",
|
|
read: (home, environment) =>
|
|
readClientRegistrationStatuses(home, "/current/rea", { environment }),
|
|
},
|
|
{
|
|
name: "maintenance scope",
|
|
read: (home, environment) =>
|
|
existingMaintenanceScope(home, "/current/rea", environment),
|
|
},
|
|
{
|
|
name: "maintenance plan",
|
|
read: (home, environment, execute) =>
|
|
planIntegrationMaintenance(home, "/current/rea", environment, execute),
|
|
},
|
|
];
|
|
|
|
it.each(
|
|
unscopedRegistrationReaders.flatMap((reader) =>
|
|
["configuration", "policy"].flatMap((source) =>
|
|
["completed", "failed"].map((readOutcome) => ({
|
|
...reader,
|
|
source,
|
|
readOutcome,
|
|
})),
|
|
),
|
|
),
|
|
)(
|
|
"$name transfers the exact $source owner after a $readOutcome read without a supplied scope",
|
|
async ({ read, source, readOutcome }) => {
|
|
const home = await createTestTempDirectory(
|
|
"rea-registration-unscoped-close-",
|
|
);
|
|
const config = join(
|
|
home,
|
|
source === "policy" ? ".gemini/settings.json" : ".cursor/mcp.json",
|
|
);
|
|
await mkdir(dirname(config), { recursive: true });
|
|
const registration =
|
|
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}\n';
|
|
await writeFile(config, registration);
|
|
const heldPath = source === "policy" ? join(home, "system.json") : config;
|
|
const heldText = source === "policy" ? "{}\n" : registration;
|
|
await writeFile(
|
|
heldPath,
|
|
readOutcome === "failed" ? Buffer.from([0xff]) : heldText,
|
|
);
|
|
const environment = {
|
|
HOME: home,
|
|
GEMINI_CLI_SYSTEM_SETTINGS_PATH: join(home, "system.json"),
|
|
GEMINI_CLI_SYSTEM_DEFAULTS_PATH: join(home, "absent-defaults.json"),
|
|
};
|
|
const held = holdReadHandle(
|
|
heldPath,
|
|
"held standalone registration descriptor",
|
|
);
|
|
const execute = vi.fn(async () =>
|
|
ok('{"status":"planned","plannedActions":[]}'),
|
|
);
|
|
try {
|
|
const outcome = await read(home, environment, execute).then(
|
|
(value) => ({ kind: "returned" as const, value }),
|
|
(cause: unknown) => ({ kind: "threw" as const, cause }),
|
|
);
|
|
expect(outcome).toMatchObject({
|
|
kind: "threw",
|
|
cause: expect.any(RegularFileCleanupFailure),
|
|
});
|
|
if (
|
|
outcome.kind !== "threw" ||
|
|
!(outcome.cause instanceof RegularFileCleanupFailure)
|
|
)
|
|
throw new Error("Read lost its failed cleanup owner");
|
|
const failure = outcome.cause;
|
|
expect(failure.path).toBe(heldPath);
|
|
if (readOutcome === "completed")
|
|
expect(failure.outcome).toEqual({ kind: "completed", value: heldText });
|
|
else
|
|
expect(failure.outcome).toMatchObject({
|
|
kind: "failed",
|
|
cause: { _tag: "InvalidUtf8FileError", path: heldPath },
|
|
});
|
|
expect(failure.owner.handle).toBe(held.closeAttempts[0]);
|
|
await expect(failure.owner.close()).rejects.toThrow("held standalone");
|
|
await rename(heldPath, `${heldPath}.retired`);
|
|
await writeFile(heldPath, "replacement");
|
|
held.release();
|
|
await failure.owner.close();
|
|
expect(failure.owner.handle.fd).toBe(-1);
|
|
expect(new Set(held.closeAttempts).size).toBe(1);
|
|
expect(await readFile(heldPath, "utf8")).toBe("replacement");
|
|
expect(execute).not.toHaveBeenCalled();
|
|
} finally {
|
|
held.release();
|
|
for (const handle of new Set(held.closeAttempts)) await handle.close();
|
|
}
|
|
},
|
|
);
|
|
|
|
it("keeps a supplied registration scope responsible for diagnostics and cleanup retry", async () => {
|
|
const home = await createTestTempDirectory("rea-registration-scoped-close-");
|
|
const config = join(home, ".cursor/mcp.json");
|
|
await mkdir(dirname(config), { recursive: true });
|
|
await writeFile(
|
|
config,
|
|
'{"mcpServers":{"rea":{"command":"rea","args":["mcp"]}}}',
|
|
);
|
|
const held = holdReadHandle(config, "held scoped registration descriptor");
|
|
const resources = new ArtifactResourceScope();
|
|
try {
|
|
expect(
|
|
(
|
|
await readClientRegistrationStatuses(home, "/current/rea", {
|
|
environment: { HOME: home },
|
|
resources,
|
|
})
|
|
).find((status) => status.client === "cursor"),
|
|
).toMatchObject({ state: "invalid", command: [] });
|
|
expect(resources.hasPending).toBe(true);
|
|
await expect(resources.close()).rejects.toThrow();
|
|
held.release();
|
|
await resources.close();
|
|
expect(resources.hasPending).toBe(false);
|
|
expect(new Set(held.closeAttempts).size).toBe(1);
|
|
expect(held.closeAttempts[0]!.fd).toBe(-1);
|
|
} finally {
|
|
held.release();
|
|
await resources.close();
|
|
}
|
|
});
|