mirror of
https://github.com/morluto/rea
synced 2026-10-25 22:08:11 -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>
817 lines
27 KiB
TypeScript
817 lines
27 KiB
TypeScript
import { mkdir, readFile, rm, writeFile, access } from "node:fs/promises";
|
|
import { delimiter, dirname, join, relative, resolve } from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
import { err, ok } from "../../src/domain/result.js";
|
|
import { runUpdate, type UpdateResult } from "../../src/application/Update.js";
|
|
import { PRODUCT_IDENTITY } from "../../src/identity.js";
|
|
import { supportedClients } from "../../src/application/SupportedClients.js";
|
|
import { readClientRegistrationInspections } from "../../src/application/ClientRegistrationStatus.js";
|
|
import {
|
|
existingMaintenanceScope,
|
|
planIntegrationMaintenance,
|
|
} from "../../src/application/UpdateMaintenance.js";
|
|
import {
|
|
runUpdateCommand,
|
|
UPDATE_COMMAND_OUTPUT_BYTES,
|
|
systemUpdateHost,
|
|
} from "../../src/application/UpdateRuntime.js";
|
|
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
|
|
import { cliTest } from "../support/cli/cliFixture.js";
|
|
|
|
const entryPoint = resolve("scripts/rea.mjs");
|
|
let home: string;
|
|
|
|
beforeEach(async () => {
|
|
home = await createTestTempDirectory("rea-update-maintenance-");
|
|
for (const [name, value] of Object.entries({
|
|
HOME: home,
|
|
USERPROFILE: home,
|
|
APPDATA: join(home, "AppData", "Roaming"),
|
|
LOCALAPPDATA: join(home, "AppData", "Local"),
|
|
CLAUDE_CONFIG_DIR: home,
|
|
CODEX_HOME: join(home, ".codex"),
|
|
COPILOT_HOME: join(home, ".copilot"),
|
|
GROK_HOME: join(home, ".grok"),
|
|
SAND_DATA_ROOT: join(home, ".grokbot"),
|
|
XDG_CONFIG_HOME: join(home, ".config"),
|
|
OPENCODE_CONFIG: join(home, ".config", "opencode", "opencode.jsonc"),
|
|
OMP_PROFILE: undefined,
|
|
PI_CODING_AGENT_DIR: undefined,
|
|
PI_CONFIG_DIR: undefined,
|
|
PI_PROFILE: undefined,
|
|
}))
|
|
vi.stubEnv(name, value);
|
|
});
|
|
|
|
afterEach(async () => {
|
|
vi.unstubAllEnvs();
|
|
await rm(home, { recursive: true, force: true });
|
|
});
|
|
|
|
const writeClient = async (id: string, content: string): Promise<string> => {
|
|
const client = supportedClients(home).find(({ name }) => name === id);
|
|
if (client === undefined) throw new Error(`Unknown test client ${id}`);
|
|
await mkdir(dirname(client.configPath), { recursive: true });
|
|
await writeFile(client.configPath, content);
|
|
return client.configPath;
|
|
};
|
|
|
|
const writeSkill = async (content: string): Promise<string> => {
|
|
const path = join(
|
|
home,
|
|
".agents",
|
|
"skills",
|
|
PRODUCT_IDENTITY.skillName,
|
|
"SKILL.md",
|
|
);
|
|
await mkdir(dirname(path), { recursive: true });
|
|
await writeFile(path, content);
|
|
return path;
|
|
};
|
|
|
|
const staleCodex =
|
|
'[mcp_servers.rea]\ncommand = "npx"\nargs = ["-y", "rea-agents@0.1.0", "mcp"]\n';
|
|
const action = {
|
|
id: "configure_client:codex",
|
|
kind: "configure_client",
|
|
label: "Codex",
|
|
target: "/test/.codex/config.toml",
|
|
detail: "Refresh the pinned REA version",
|
|
external: false,
|
|
operation: "update",
|
|
backupPath: "/test/.codex/config.toml.rea.backup",
|
|
commands: ["rea mcp"],
|
|
};
|
|
|
|
describe("OMP integration maintenance", () => {
|
|
it("refreshes an OMP entry that enabledServers forces on", async () => {
|
|
const entry = { type: "stdio", command: entryPoint, args: ["mcp"] };
|
|
await writeClient(
|
|
"omp",
|
|
JSON.stringify({ mcpServers: { rea: { ...entry, enabled: false } } }),
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: [] });
|
|
await writeClient(
|
|
"omp",
|
|
JSON.stringify({
|
|
mcpServers: { rea: { ...entry, enabled: false } },
|
|
enabledServers: ["rea"],
|
|
}),
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: ["omp"] });
|
|
});
|
|
|
|
it("preserves Grok Build disabled_mcp_servers during maintenance planning", async () => {
|
|
// Strict identity: a user-disabled integration must never be selected
|
|
// for maintenance, even with a healthy owned entry underneath.
|
|
const registration = `[mcp_servers.rea]\ncommand = ${JSON.stringify(process.execPath)}\nargs = [${JSON.stringify(entryPoint)}, "mcp"]\nstartup_timeout_sec = 30\n`;
|
|
const configPath = await writeClient(
|
|
"grok_build",
|
|
`disabled_mcp_servers = ["rea", "other"]\n${registration}`,
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: [] });
|
|
expect(await readFile(configPath, "utf8")).toContain(
|
|
'disabled_mcp_servers = ["rea", "other"]',
|
|
);
|
|
await writeFile(
|
|
configPath,
|
|
`disabled_mcp_servers = ["other"]\n${registration}`,
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: ["grok_build"] });
|
|
});
|
|
});
|
|
|
|
describe("maintenance activation and layered configuration", () => {
|
|
it("keeps unresolved registrations out of writes without calling them current", async () => {
|
|
await writeClient("codex", staleCodex);
|
|
const cursor = await writeClient(
|
|
"cursor",
|
|
JSON.stringify({
|
|
mcpServers: {
|
|
rea: { command: join(home, "removed-release", "rea"), args: ["mcp"] },
|
|
},
|
|
}),
|
|
);
|
|
const before = await readFile(cursor, "utf8");
|
|
const result = await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
() => {
|
|
throw new Error("An unresolved maintenance scope must not be executed");
|
|
},
|
|
);
|
|
expect(result).toMatchObject({
|
|
status: "unavailable",
|
|
scope: {
|
|
clients: ["codex"],
|
|
unresolved: [
|
|
expect.objectContaining({
|
|
client: "cursor",
|
|
state: "unknown",
|
|
config_path: cursor,
|
|
}),
|
|
],
|
|
},
|
|
remediation: expect.stringContaining("cursor"),
|
|
});
|
|
expect(await readFile(cursor, "utf8")).toBe(before);
|
|
});
|
|
|
|
it("leaves an inherited disabled OpenCode V2 registration outside maintenance", async () => {
|
|
const upper = await writeClient(
|
|
"opencode",
|
|
JSON.stringify({ mcp: { servers: {} }, theme: "user-selected" }),
|
|
);
|
|
const lower = join(home, ".config", "opencode", "config.json");
|
|
const originalLower = JSON.stringify({
|
|
mcp: {
|
|
servers: {
|
|
rea: { type: "local", command: [entryPoint, "mcp"], disabled: true },
|
|
},
|
|
},
|
|
});
|
|
await writeFile(lower, originalLower);
|
|
const originalUpper = await readFile(upper, "utf8");
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: [] });
|
|
expect(await readFile(lower, "utf8")).toBe(originalLower);
|
|
expect(await readFile(upper, "utf8")).toBe(originalUpper);
|
|
});
|
|
|
|
it("leaves a natively disabled ZCode registration outside maintenance", async () => {
|
|
const configPath = await writeClient(
|
|
"zcode",
|
|
JSON.stringify({
|
|
mcp: {
|
|
servers: {
|
|
rea: { command: entryPoint, args: ["mcp"], enable: false },
|
|
},
|
|
},
|
|
}),
|
|
);
|
|
const original = await readFile(configPath, "utf8");
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: [] });
|
|
expect(await readFile(configPath, "utf8")).toBe(original);
|
|
});
|
|
|
|
it("selects a ZCode registration loaded from the same-scope fallback", async () => {
|
|
await writeClient("zcode", JSON.stringify({ mcp: { servers: {} } }));
|
|
const fallbackPath = join(home, ".agents", "mcp.json");
|
|
await mkdir(join(home, ".agents"), { recursive: true });
|
|
await writeFile(
|
|
fallbackPath,
|
|
JSON.stringify({
|
|
mcpServers: { rea: { command: entryPoint, args: ["mcp"] } },
|
|
}),
|
|
);
|
|
|
|
// The fallback row is also FreeBuff's registration, and FreeBuff is the
|
|
// setup action that rewrites it, so both views stay in maintenance scope.
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: ["freebuff", "zcode"] });
|
|
});
|
|
|
|
it("selects an enabled registration inherited through layered OpenCode files", async () => {
|
|
const directory = join(home, ".config", "opencode");
|
|
await mkdir(directory, { recursive: true });
|
|
await writeFile(
|
|
join(directory, "opencode.json"),
|
|
JSON.stringify({
|
|
mcp: { rea: { type: "local", command: [entryPoint, "mcp"] } },
|
|
}),
|
|
);
|
|
await writeClient("opencode", JSON.stringify({ theme: "user-selected" }));
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: ["opencode"] });
|
|
});
|
|
});
|
|
|
|
describe("registration ownership in maintenance", () => {
|
|
it("selects owned registrations while preserving unconfigured, foreign, and disabled choices", async () => {
|
|
await writeClient("codex", staleCodex);
|
|
await writeClient("claude_code", '{"mcpServers":{}}');
|
|
await writeClient(
|
|
"cursor",
|
|
'{"mcpServers":{"rea":{"command":"foreign-server","args":[]}}}',
|
|
);
|
|
await writeClient(
|
|
"opencode",
|
|
'{"mcp":{"rea":{"type":"local","command":["npx","-y","rea-agents@0.1.0","mcp"],"enabled":false}}}',
|
|
);
|
|
await writeClient(
|
|
"vscode",
|
|
JSON.stringify({
|
|
servers: { rea: { type: "stdio", command: entryPoint, args: ["mcp"] } },
|
|
}),
|
|
);
|
|
expect(
|
|
await readClientRegistrationInspections(home, entryPoint, {
|
|
environment: process.env,
|
|
}),
|
|
).toEqual(
|
|
expect.arrayContaining([
|
|
expect.objectContaining({
|
|
status: expect.objectContaining({ client: "codex", state: "stale" }),
|
|
activation: "enabled",
|
|
commandIdentity: "owned",
|
|
}),
|
|
expect.objectContaining({
|
|
status: expect.objectContaining({ client: "cursor", state: "stale" }),
|
|
activation: "enabled",
|
|
commandIdentity: "foreign",
|
|
}),
|
|
expect.objectContaining({
|
|
status: expect.objectContaining({
|
|
client: "opencode",
|
|
state: "stale",
|
|
}),
|
|
activation: "disabled",
|
|
commandIdentity: "owned",
|
|
}),
|
|
expect.objectContaining({
|
|
status: expect.objectContaining({
|
|
client: "claude_code",
|
|
state: "missing",
|
|
}),
|
|
activation: "unknown",
|
|
commandIdentity: "unknown",
|
|
}),
|
|
]),
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: ["codex", "vscode"],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("existing REA integration maintenance", () => {
|
|
it("does not install a missing skill or overwrite an unrelated skill", async () => {
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: [],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
await writeSkill("---\nname: another-skill\n---\nUser-authored content\n");
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: [],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
});
|
|
|
|
it("includes an existing REA skill and leaves files untouched", async () => {
|
|
const path = await writeSkill(
|
|
`---\nname: ${PRODUCT_IDENTITY.skillName}\nmetadata:\n version: "1"\n---\n# REA\n`,
|
|
);
|
|
const original = await readFile(path, "utf8");
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: [],
|
|
skill: true,
|
|
skillDestinations: [
|
|
{
|
|
client: "shared",
|
|
path: join(home, ".agents", "skills", PRODUCT_IDENTITY.skillName),
|
|
},
|
|
],
|
|
});
|
|
expect(await readFile(path, "utf8")).toBe(original);
|
|
});
|
|
|
|
it("skips setup entirely when there is no existing integration", async () => {
|
|
let invoked = false;
|
|
const result = await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
async () => {
|
|
invoked = true;
|
|
return err("Unexpected setup");
|
|
},
|
|
);
|
|
expect(result).toEqual({ status: "current", plannedActions: [] });
|
|
expect(invoked).toBe(false);
|
|
});
|
|
|
|
it("returns exact backup and command evidence with a scoped unapplied setup command", async () => {
|
|
await writeClient("codex", staleCodex);
|
|
const recorded: string[][] = [];
|
|
const result = await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
async (command) => {
|
|
recorded.push([...command]);
|
|
return ok(
|
|
JSON.stringify({ status: "planned", plannedActions: [action] }),
|
|
);
|
|
},
|
|
);
|
|
expect(recorded).toEqual([
|
|
[
|
|
process.execPath,
|
|
entryPoint,
|
|
"setup",
|
|
"--client",
|
|
"codex",
|
|
"--skill=false",
|
|
"--dry-run",
|
|
"--json",
|
|
],
|
|
]);
|
|
expect(result).toEqual({
|
|
status: "planned",
|
|
scope: { clients: ["codex"], skill: false, skillDestinations: [] },
|
|
command: recorded[0]?.slice(0, -2),
|
|
plannedActions: [action],
|
|
});
|
|
});
|
|
|
|
it.each([
|
|
"{broken",
|
|
JSON.stringify({ status: "ready", plannedActions: [action] }),
|
|
JSON.stringify({
|
|
status: "planned",
|
|
plannedActions: [{ ...action, kind: "install_hopper", external: true }],
|
|
}),
|
|
JSON.stringify({
|
|
status: "planned",
|
|
plannedActions: [{ ...action, id: "configure_client:cursor" }],
|
|
}),
|
|
])("rejects malformed or out-of-scope subprocess plans", async (output) => {
|
|
await writeClient("codex", staleCodex);
|
|
expect(
|
|
await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
async () => ok(output),
|
|
),
|
|
).toMatchObject({ status: "unavailable" });
|
|
});
|
|
|
|
it("preserves actual setup failure diagnostics", async () => {
|
|
await writeClient("codex", staleCodex);
|
|
expect(
|
|
await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
async () => err("EACCES /test/.codex/config.toml"),
|
|
),
|
|
).toEqual({
|
|
status: "unavailable",
|
|
remediation: "EACCES /test/.codex/config.toml",
|
|
});
|
|
});
|
|
});
|
|
|
|
describe("shared registration maintenance", () => {
|
|
it("refreshes an owned shared registration without its product profile", async () => {
|
|
// FreeBuff's registration lives in the shared user agents file. The row is
|
|
// owned, so maintenance must refresh it even though no FreeBuff profile
|
|
// exists to establish product applicability.
|
|
await writeClient(
|
|
"freebuff",
|
|
JSON.stringify({
|
|
mcpServers: {
|
|
other: { command: "other-server" },
|
|
rea: { command: entryPoint, args: ["mcp"] },
|
|
},
|
|
}),
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: ["freebuff"],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
});
|
|
|
|
it("retains FreeBuff when ZCode reads the shared fallback", async () => {
|
|
// Both products load the one shared row, but their setup actions write
|
|
// different files: ZCode writes ~/.zcode/cli/config.json and deliberately
|
|
// leaves ~/.agents/mcp.json untouched (docs/client-configuration.md), so
|
|
// its fallback view cannot cover FreeBuff's registration. The shared row
|
|
// would stay pinned to the old version without FreeBuff's own action.
|
|
await writeClient("zcode", JSON.stringify({ mcp: { servers: {} } }));
|
|
await mkdir(join(home, ".config", "freebuff-desktop"), {
|
|
recursive: true,
|
|
});
|
|
await writeClient(
|
|
"freebuff",
|
|
JSON.stringify({
|
|
mcpServers: {
|
|
rea: { command: "npx", args: ["-y", "rea-agents@0.1.0", "mcp"] },
|
|
},
|
|
}),
|
|
);
|
|
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toMatchObject({ clients: ["freebuff", "zcode"] });
|
|
});
|
|
|
|
it("leaves a foreign shared registration out of maintenance", async () => {
|
|
await writeClient(
|
|
"freebuff",
|
|
JSON.stringify({
|
|
mcpServers: { rea: { command: "foreign-server", args: [] } },
|
|
}),
|
|
);
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: [],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
});
|
|
|
|
it("leaves a ZCode-disabled shared row out of maintenance", async () => {
|
|
// The shared file doubles as ZCode's fallback, where `enable: false`
|
|
// disables the registration. Ownership evidence must not let maintenance
|
|
// rewrite the row as a FreeBuff registration and drop that flag.
|
|
const configPath = await writeClient(
|
|
"freebuff",
|
|
JSON.stringify({
|
|
mcpServers: {
|
|
rea: { command: entryPoint, args: ["mcp"], enable: false },
|
|
},
|
|
}),
|
|
);
|
|
const original = await readFile(configPath, "utf8");
|
|
await expect(
|
|
existingMaintenanceScope(home, entryPoint, process.env),
|
|
).resolves.toEqual({
|
|
clients: [],
|
|
skill: false,
|
|
skillDestinations: [],
|
|
});
|
|
expect(await readFile(configPath, "utf8")).toBe(original);
|
|
});
|
|
});
|
|
|
|
describe("updated executable maintenance planning", () => {
|
|
it("runs real setup as a noninteractive dry run and creates no new integrations or backups", async () => {
|
|
const configPath = await writeClient("codex", staleCodex);
|
|
const untouched = await writeClient("claude_code", '{"mcpServers":{}}');
|
|
const skillContent = `---\nname: ${PRODUCT_IDENTITY.skillName}\nmetadata:\n version: "1"\n---\n# REA\n`;
|
|
const skillPath = await writeSkill(skillContent);
|
|
vi.stubEnv("npm_command", "exec");
|
|
const result = await planIntegrationMaintenance(
|
|
home,
|
|
entryPoint,
|
|
process.env,
|
|
(command) => runUpdateCommand(command, process.env),
|
|
);
|
|
expect(result).toMatchObject({
|
|
status: "planned",
|
|
scope: {
|
|
clients: ["codex"],
|
|
skill: true,
|
|
skillDestinations: [{ client: "shared", path: dirname(skillPath) }],
|
|
},
|
|
});
|
|
if (result.status !== "planned") throw new Error(JSON.stringify(result));
|
|
expect(result.plannedActions).toEqual([
|
|
expect.objectContaining({
|
|
id: "configure_client:codex",
|
|
kind: "configure_client",
|
|
}),
|
|
expect.objectContaining({
|
|
id: "install_skill",
|
|
kind: "install_skill",
|
|
target: dirname(skillPath),
|
|
}),
|
|
]);
|
|
expect(await readFile(configPath, "utf8")).toBe(staleCodex);
|
|
expect(await readFile(untouched, "utf8")).toBe('{"mcpServers":{}}');
|
|
expect(await readFile(skillPath, "utf8")).toBe(skillContent);
|
|
await expect(access(`${configPath}.rea.backup`)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
await expect(access(`${skillPath}.rea.backup`)).rejects.toMatchObject({
|
|
code: "ENOENT",
|
|
});
|
|
await expect(
|
|
access(join(home, ".claude", "skills", PRODUCT_IDENTITY.skillName)),
|
|
).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
});
|
|
|
|
describe("update subprocess boundaries", () => {
|
|
cliTest("exposes update in CLI help", async ({ cli }) => {
|
|
const help = await cli.run({
|
|
arguments: ["--help"],
|
|
environment: process.env,
|
|
});
|
|
expect(help.exitCode, help.stderr).toBe(0);
|
|
expect(help.stdout).toMatch(/^\s{2}update\s/mu);
|
|
expect(help.stdout).not.toMatch(/^\s{2}upgrade\s/mu);
|
|
});
|
|
|
|
cliTest("rejects the removed upgrade CLI command", async ({ cli }) => {
|
|
const removed = await cli.run({
|
|
arguments: ["upgrade", "--json"],
|
|
environment: process.env,
|
|
});
|
|
expect(removed.exitCode, removed.stderr).toBe(1);
|
|
expect(removed.json).toMatchObject({ code: "COMMAND_NOT_FOUND" });
|
|
});
|
|
it("captures output through stream closure and keeps arguments literal", async () => {
|
|
const literal = 'space and $(echo bad); & | "quotes"';
|
|
const result = await runUpdateCommand(
|
|
[
|
|
process.execPath,
|
|
"-e",
|
|
'process.stdout.write("x".repeat(1024 * 1024) + process.argv[1])',
|
|
literal,
|
|
],
|
|
process.env,
|
|
);
|
|
expect(result).toEqual(ok(`${"x".repeat(1024 * 1024)}${literal}`));
|
|
});
|
|
|
|
it("reports actual stderr and launch failures", async () => {
|
|
await expect(
|
|
runUpdateCommand(
|
|
[
|
|
process.execPath,
|
|
"-e",
|
|
'process.stderr.write("EACCES /test/install"); process.exitCode = 2',
|
|
],
|
|
process.env,
|
|
),
|
|
).resolves.toEqual(err("EACCES /test/install"));
|
|
const missing = await runUpdateCommand(
|
|
[join(home, "missing-executable")],
|
|
process.env,
|
|
);
|
|
expect(missing).toMatchObject({ ok: false });
|
|
if (!missing.ok) expect(missing.error).toContain("ENOENT");
|
|
});
|
|
|
|
it("verifies the requested package entry rather than PATH's rea", async () => {
|
|
const packageRoot = join(home, "package");
|
|
const script = join(packageRoot, "scripts", "rea.mjs");
|
|
await mkdir(dirname(script), { recursive: true });
|
|
await writeFile(script, 'process.stdout.write("3.3.0\\n")');
|
|
await expect(
|
|
systemUpdateHost(packageRoot, home).installedVersion({
|
|
manager: "npm",
|
|
prefix: home,
|
|
packageRoot,
|
|
}),
|
|
).resolves.toEqual(ok("3.3.0"));
|
|
});
|
|
});
|
|
|
|
const createBunUpdateFixture = async (
|
|
root: string,
|
|
bunVersion: string,
|
|
installOutputBytes: number,
|
|
installExitCode: number,
|
|
) => {
|
|
const globalDirectory = join(root, "bun", "install", "global");
|
|
const packageRoot = join(
|
|
globalDirectory,
|
|
"node_modules",
|
|
PRODUCT_IDENTITY.packageName,
|
|
);
|
|
const versionPath = join(root, "installed-version");
|
|
const logPath = join(root, "bun-invocations.jsonl");
|
|
await mkdir(join(packageRoot, "scripts"), { recursive: true });
|
|
await writeFile(
|
|
join(globalDirectory, "package.json"),
|
|
'{"dependencies":{"rea-agents":"3.2.1"}}\n',
|
|
);
|
|
await writeFile(versionPath, "3.2.1");
|
|
await writeFile(
|
|
join(packageRoot, "scripts", "rea.mjs"),
|
|
`import { readFileSync } from "node:fs";\nprocess.stdout.write(readFileSync(${JSON.stringify(versionPath)}, "utf8") + "\\n");\n`,
|
|
);
|
|
const binDirectory = join(root, "bin");
|
|
const recorder = join(binDirectory, "record-bun.mjs");
|
|
await mkdir(binDirectory);
|
|
await writeFile(
|
|
recorder,
|
|
[
|
|
'import { appendFileSync, writeFileSync } from "node:fs";',
|
|
"const args = process.argv.slice(2);",
|
|
`appendFileSync(${JSON.stringify(logPath)}, JSON.stringify({ args, cwd: process.cwd(), globalDirectory: process.env.BUN_INSTALL_GLOBAL_DIR }) + "\\n");`,
|
|
`if (JSON.stringify(args) === '["--version"]') console.log(${JSON.stringify(bunVersion)});`,
|
|
`else if (JSON.stringify(args) === ${JSON.stringify(JSON.stringify(["info", PRODUCT_IDENTITY.packageName, "dist-tags.latest", "--json"]))}) process.stdout.write('"3.3.0"\\n');`,
|
|
`else if (JSON.stringify(args) === ${JSON.stringify(JSON.stringify(["add", "--global", "--ignore-scripts", `${PRODUCT_IDENTITY.packageName}@3.3.0`]))}) process.stderr.write('x'.repeat(${installOutputBytes}), () => { ${installExitCode === 0 ? `writeFileSync(${JSON.stringify(versionPath)}, "3.3.0");` : "process.exitCode = 2;"} });`,
|
|
"else process.exitCode = 2;",
|
|
"",
|
|
].join("\n"),
|
|
);
|
|
if (process.platform === "win32") {
|
|
await writeFile(
|
|
join(binDirectory, "bun.cmd"),
|
|
`@"${process.execPath}" "${recorder}" %*\r\n`,
|
|
);
|
|
} else {
|
|
await writeFile(
|
|
join(binDirectory, "bun"),
|
|
`#!/bin/sh\nexec ${JSON.stringify(process.execPath)} ${JSON.stringify(recorder)} "$@"\n`,
|
|
{ mode: 0o755 },
|
|
);
|
|
}
|
|
return { globalDirectory, packageRoot, versionPath, logPath, binDirectory };
|
|
};
|
|
|
|
describe("Bun global installation update", () => {
|
|
it.each([
|
|
["1.4.2", "updated", "absolute", UPDATE_COMMAND_OUTPUT_BYTES + 1, 0],
|
|
["1.4.2", "install-failed", "absolute", UPDATE_COMMAND_OUTPUT_BYTES + 1, 2],
|
|
["1.2.17", "updated", "absolute", 0, 0],
|
|
["1.2.17", "updated", "relative", 0, 0],
|
|
["1.2.14", "failed", "absolute", 0, 0],
|
|
["1.2.17-canary.1", "failed", "absolute", 0, 0],
|
|
["unknown", "failed", "absolute", 0, 0],
|
|
] as const)(
|
|
"handles Bun %s with outcome %s using %s global-directory configuration",
|
|
async (
|
|
bunVersion,
|
|
status,
|
|
directoryMode,
|
|
installOutputBytes,
|
|
installExitCode,
|
|
) => {
|
|
// A recording `bun` on PATH crosses the real subprocess boundary without registry access.
|
|
const root = await createTestTempDirectory("rea-update-bun-");
|
|
const {
|
|
globalDirectory,
|
|
packageRoot,
|
|
versionPath,
|
|
logPath,
|
|
binDirectory,
|
|
} = await createBunUpdateFixture(
|
|
root,
|
|
bunVersion,
|
|
installOutputBytes,
|
|
installExitCode,
|
|
);
|
|
const pathKey =
|
|
Object.keys(process.env).find((key) => key.toUpperCase() === "PATH") ??
|
|
"PATH";
|
|
const environment: NodeJS.ProcessEnv = {
|
|
...process.env,
|
|
[pathKey]: `${binDirectory}${delimiter}${process.env[pathKey] ?? ""}`,
|
|
BUN_INSTALL: join(root, "bun"),
|
|
};
|
|
delete environment.BUN_INSTALL_GLOBAL_DIR;
|
|
if (directoryMode === "relative")
|
|
environment.BUN_INSTALL_GLOBAL_DIR = relative(root, globalDirectory);
|
|
|
|
const callerDirectory = process.cwd();
|
|
let result: UpdateResult;
|
|
try {
|
|
process.chdir(root);
|
|
result = await runUpdate(
|
|
"3.2.1",
|
|
systemUpdateHost(packageRoot, home, environment),
|
|
"structured",
|
|
);
|
|
} finally {
|
|
process.chdir(callerDirectory);
|
|
}
|
|
|
|
const invocations = (await readFile(logPath, "utf8"))
|
|
.trim()
|
|
.split("\n")
|
|
.map((line): unknown => JSON.parse(line));
|
|
const versionInvocation = {
|
|
args: ["--version"],
|
|
cwd: globalDirectory,
|
|
globalDirectory,
|
|
};
|
|
if (status === "failed") {
|
|
expect(result).toEqual({
|
|
status: "failed",
|
|
currentVersion: "3.2.1",
|
|
latestVersion: null,
|
|
reason: "version-check",
|
|
remediation: `REA updates for Bun global installations require Bun 1.2.17 or later; bun --version returned ${JSON.stringify(bunVersion)}. Upgrade Bun manually, then rerun rea update.`,
|
|
});
|
|
expect(invocations).toEqual([versionInvocation]);
|
|
expect(await readFile(versionPath, "utf8")).toBe("3.2.1");
|
|
return;
|
|
}
|
|
|
|
if (status === "install-failed") {
|
|
expect(result).toMatchObject({
|
|
status: "failed",
|
|
reason: "install",
|
|
remediation: expect.stringContaining("diagnostics truncated"),
|
|
});
|
|
expect(await readFile(versionPath, "utf8")).toBe("3.2.1");
|
|
} else
|
|
expect(result).toMatchObject({
|
|
status: "updated",
|
|
installMethod: "bun",
|
|
installedVersion: "3.3.0",
|
|
command: [
|
|
"bun",
|
|
"add",
|
|
"--global",
|
|
"--ignore-scripts",
|
|
`${PRODUCT_IDENTITY.packageName}@3.3.0`,
|
|
],
|
|
});
|
|
// `bun info` needs a project in its working directory, and the caller's
|
|
// directory must never be selected, so all commands run in the owner.
|
|
expect(invocations).toEqual([
|
|
versionInvocation,
|
|
{
|
|
args: [
|
|
"info",
|
|
PRODUCT_IDENTITY.packageName,
|
|
"dist-tags.latest",
|
|
"--json",
|
|
],
|
|
cwd: globalDirectory,
|
|
globalDirectory,
|
|
},
|
|
{
|
|
args: [
|
|
"add",
|
|
"--global",
|
|
"--ignore-scripts",
|
|
`${PRODUCT_IDENTITY.packageName}@3.3.0`,
|
|
],
|
|
cwd: globalDirectory,
|
|
globalDirectory,
|
|
},
|
|
]);
|
|
},
|
|
);
|
|
});
|