Files
elizaos--eliza/plugins/plugin-coding-tools/src/actions/write.test.ts
T
wehub-resource-sync 426e9eeabd
Voice Workbench / headless workbench (mocked backends) (push) Has been cancelled
Voice Workbench / real acoustic lane (nightly, provisioned only) (push) Has been cancelled
ci / test (push) Has been cancelled
ci / lint-and-format (push) Has been cancelled
ci / build (push) Has been cancelled
ci / dev-startup (push) Has been cancelled
gitleaks / gitleaks (push) Has been cancelled
Markdown Links / Relative Markdown Links (push) Has been cancelled
Quality (Extended) / Homepage Build (PR smoke) (push) Has been cancelled
Quality (Extended) / Comment-only diff guard (push) Has been cancelled
Quality (Extended) / Format + Type Safety Ratchet (push) Has been cancelled
Quality (Extended) / Develop Gate (secret scan + UI determinism) (push) Has been cancelled
Quality (Extended) / Develop Gate (lint) (push) Has been cancelled
Chat shell gestures / Chat shell gesture + parity e2e (push) Has been cancelled
Cloud Gateway Discord / Test (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx @biomejs/biome check packages/lifeops-bench/src, benchmark-lint) (push) Has been cancelled
Benchmark Bridge Tests / benchmark (bunx vitest run --config packages/lifeops-bench/vitest.config.ts --root packages/lifeops-bench --passWithNoTests, benchmark-tests) (push) Has been cancelled
Build Agent Image / build-and-push (push) Has been cancelled
Dev Smoke / bun run dev onboarding chat (push) Has been cancelled
Dev Smoke / Vite HMR dependency-level smoke (push) Has been cancelled
Electrobun Submodule Guard / electrobun gitlink is fetchable (push) Has been cancelled
Publish @elizaos/example-code / check_npm (push) Has been cancelled
Publish @elizaos/example-code / publish_npm (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / verify_version (push) Has been cancelled
Publish @elizaos/plugin-elizacloud / publish_npm (push) Has been cancelled
Sandbox Live Smoke / Sandbox live smoke (push) Has been cancelled
Snap Build & Test / Build Snap (amd64) (push) Has been cancelled
Snap Build & Test / Build Snap (arm64) (push) Has been cancelled
Test Packaging / elizaos CLI global-install smoke (node + bun) (push) Has been cancelled
Cloud Gateway Webhook / Test (push) Has been cancelled
Cloud Tests / lint-and-types (push) Has been cancelled
Cloud Tests / unit-tests (push) Has been cancelled
Cloud Tests / integration-tests (push) Has been cancelled
Cloud Tests / e2e-tests (push) Has been cancelled
CodeQL Advanced / Analyze (javascript-typescript) (push) Has been cancelled
Deploy Apps Worker (Product 2) / Determine environment (push) Has been cancelled
Deploy Apps Worker (Product 2) / Deploy apps worker to apps-control host (${{ needs.determine-env.outputs.environment }}) (push) Has been cancelled
Deploy Eliza Provisioning Worker / Determine environment (push) Has been cancelled
Deploy Eliza Provisioning Worker / Deploy worker to Hetzner host (${{ needs.determine-env.outputs.environment }} @ ${{ needs.determine-env.outputs.deployment_sha }}) (push) Has been cancelled
Dev Smoke / Classify changed paths (push) Has been cancelled
supply-chain / sbom (push) Has been cancelled
supply-chain / vulnerability-scan (push) Has been cancelled
Build, Push & Deploy to Phala Cloud / build-and-push (push) Has been cancelled
Test Packaging / Validate Packaging Configs (push) Has been cancelled
Test Packaging / Build & Test PyPI Package (push) Has been cancelled
Test Packaging / PyPI on Python ${{ matrix.python }} (push) Has been cancelled
Test Packaging / Pack & Test JS Tarballs (push) Has been cancelled
UI Fixture E2E / ui-fixture-e2e (push) Has been cancelled
UI Fixture E2E / fixture-e2e (push) Has been cancelled
UI Story Gate / story-gate (push) Has been cancelled
vault-ci / test (macos-latest) (push) Has been cancelled
vault-ci / test (ubuntu-latest) (push) Has been cancelled
vault-ci / test (windows-latest) (push) Has been cancelled
vault-ci / app-core wiring tests (push) Has been cancelled
verify-patches / verify patches/CHECKSUMS.sha256 (push) Has been cancelled
Voice Benchmark Smoke / voice-emotion fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voiceagentbench fixture smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench-quality unit smoke (push) Has been cancelled
Voice Benchmark Smoke / voicebench TypeScript unit (no audio) (push) Has been cancelled
Voice Benchmark Smoke / voice bench smoke summary (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/app-core test bun run --cwd packages/elizaos test bun run --cwd packages/cloud/shared test], app-and-cli) (push) Has been cancelled
Windows CI / windows ([bun run --cwd packages/scenario-runner test bun run --cwd packages/vault test bun run --cwd packages/security test bun run --cwd plugins/plugin-coding-tools test], framework-packages) (push) Has been cancelled
Windows CI / windows ([bun run --cwd plugins/plugin-elizacloud test bun run --cwd plugins/plugin-discord test bun run --cwd plugins/plugin-anthropic test bun run --cwd plugins/plugin-openai test bun run --cwd plugins/plugin-app-control test bun run --cwd plugins/pl… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run build --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/agent --concurrency=4 node packages/scripts/run-bash-linux-only.mjs scripts/verify-riscv64-buildpaths.sh node packages/scripts/run… (push) Has been cancelled
Windows CI / windows ([node packages/scripts/run-turbo.mjs run typecheck --filter=@elizaos/core --filter=@elizaos/shared --filter=@elizaos/cloud-shared --concurrency=4 bun run --cwd packages/core test bun run --cwd packages/shared test], core-runtime, 75) (push) Has been cancelled
chore: import upstream snapshot with attribution
2026-07-13 12:43:05 +08:00

226 lines
7.3 KiB
TypeScript

/** Tests for the FILE `write` handler over the real filesystem, including the writability guard and secret detection. */
import * as fs from "node:fs/promises";
import * as path from "node:path";
import {
CAPABILITY_ROUTER_SERVICE_TYPE,
CapabilityError,
type ElizaCapabilityRouter,
type FileWriteTextParams,
type IAgentRuntime,
UnavailableCapabilityRouter,
} from "@elizaos/core";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { setupEnv, type TestEnv } from "./_test-helpers.js";
import { writeFileHandler } from "./write.js";
function unavailableCapability(
capability: "fs" | "pty" | "git" | "model",
method: string,
): never {
throw new CapabilityError({
code: "CAPABILITY_UNAVAILABLE",
message: `${capability} unavailable`,
capability,
method,
});
}
function makeWriteRouter(
writeText: ElizaCapabilityRouter["fs"]["writeText"],
): ElizaCapabilityRouter {
return {
environment: "desktop",
availability: async () => ({
environment: "desktop",
available: true,
capabilities: {
fs: true,
pty: false,
git: false,
model: false,
plugin: false,
},
}),
fs: {
list: async () => unavailableCapability("fs", "fs.list"),
readText: async () => unavailableCapability("fs", "fs.readText"),
writeText,
},
pty: {
runCommand: async () => unavailableCapability("pty", "pty.command.run"),
},
git: {
status: async () => unavailableCapability("git", "git.status"),
diff: async () => unavailableCapability("git", "git.diff"),
commandRun: async () => unavailableCapability("git", "git.command.run"),
},
model: {
status: async () => unavailableCapability("model", "model.status"),
},
plugin: new UnavailableCapabilityRouter("desktop").plugin,
};
}
function runtimeWithRouter(
runtime: IAgentRuntime,
router: ElizaCapabilityRouter,
): IAgentRuntime {
return {
...runtime,
getService: <T>(serviceType: string): T | null =>
serviceType === CAPABILITY_ROUTER_SERVICE_TYPE
? (router as T)
: runtime.getService<T>(serviceType),
} as IAgentRuntime;
}
describe("WRITE", () => {
let env: TestEnv;
beforeEach(async () => {
env = await setupEnv("write-test");
});
afterEach(async () => {
await env.cleanup();
});
it("creates a new file and its parent directory", async () => {
const file = path.join(env.tmpDir, "nested", "deeper", "out.txt");
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: file, content: "hello world" },
});
expect(result.success).toBe(true);
const onDisk = await fs.readFile(file, "utf8");
expect(onDisk).toBe("hello world");
const data = result.data as Record<string, unknown> | undefined;
expect(data?.bytes).toBe(11);
// The write confirmation is user-facing so the planner-loop relays it
// verbatim when the post-tool evaluator model call fails (no regression on
// the elizaOS Cloud 400 incident).
expect(result.userFacingText).toBe(result.text);
expect(result.userFacingText).toContain("Wrote 11 bytes to ");
});
it("prefers capability router for file writes when available", async () => {
const file = path.join(env.tmpDir, "nested", "routed.txt");
const calls: FileWriteTextParams[] = [];
const router = makeWriteRouter(async (params) => {
calls.push(params);
await fs.mkdir(path.dirname(params.path), { recursive: true });
await fs.writeFile(params.path, params.text, "utf8");
return {
path: params.path,
bytesWritten: Buffer.byteLength(params.text, "utf8"),
};
});
const result = await writeFileHandler(
runtimeWithRouter(env.runtime, router),
env.message,
undefined,
{ parameters: { file_path: file, content: "routed write" } },
);
expect(result.success).toBe(true);
expect(await fs.readFile(file, "utf8")).toBe("routed write");
expect(calls).toEqual([
{
path: file,
text: "routed write",
createDirectories: true,
overwrite: true,
},
]);
const meta = env.fileState.get("test-room", file);
expect(meta).toBeDefined();
});
it("rejects writes to existing files that were not READ first (must_read_first)", async () => {
const file = path.join(env.tmpDir, "preexisting.txt");
await fs.writeFile(file, "original", "utf8");
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: file, content: "overwrite" },
});
expect(result.success).toBe(false);
expect(result.text).toContain("not read in this session");
const onDisk = await fs.readFile(file, "utf8");
expect(onDisk).toBe("original");
});
it("allows overwriting after a previous recordRead with matching mtime", async () => {
const file = path.join(env.tmpDir, "tracked.txt");
await fs.writeFile(file, "original", "utf8");
await env.fileState.recordRead("test-room", file);
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: file, content: "fresh" },
});
expect(result.success).toBe(true);
const onDisk = await fs.readFile(file, "utf8");
expect(onDisk).toBe("fresh");
});
it("rejects stale reads when the file was modified externally", async () => {
const file = path.join(env.tmpDir, "stale.txt");
await fs.writeFile(file, "original", "utf8");
await env.fileState.recordRead("test-room", file);
// bump mtime
await new Promise((r) => setTimeout(r, 20));
await fs.writeFile(file, "external edit", "utf8");
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: file, content: "agent overwrite" },
});
expect(result.success).toBe(false);
expect(result.text).toContain("stale_read");
});
it("refuses to write content containing detected secret patterns", async () => {
const file = path.join(env.tmpDir, "secret.txt");
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: {
file_path: file,
content: "AKIAABCDEFGHIJKLMNOP",
},
});
expect(result.success).toBe(false);
expect(result.text).toContain("invalid_param");
expect(result.text).toContain("aws_access_key");
await expect(fs.access(file)).rejects.toBeDefined();
});
it("rejects relative paths", async () => {
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: "rel/path.txt", content: "x" },
});
expect(result.success).toBe(false);
expect(result.text).toContain("invalid_param");
});
it("rejects paths under the blocklist", async () => {
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: {
file_path: path.join(env.blockedPath, "x.txt"),
content: "x",
},
});
expect(result.success).toBe(false);
expect(result.text).toContain("path_blocked");
});
it("fails when content param is missing", async () => {
const result = await writeFileHandler(env.runtime, env.message, undefined, {
parameters: { file_path: path.join(env.tmpDir, "x.txt") },
});
expect(result.success).toBe(false);
expect(result.text).toContain("missing_param");
});
});