mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-30 09:05:15 +01:00
feat(agents): persist agent files across tasks without revision history (#14420)
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work. > - An agent needs personal files across tasks and sessions. > - AGENTS.md is one file in that directory. Supporting files need the same persistence. > - The Instructions Editor and agent runs must share one current directory. > - Concurrent runs should apply only the files they change. The last sync of the same file wins. > - This pull request uses existing file transport and removes temporary copies after sync. > - Old instruction-only sessions keep their restore contract. New saves do not create revision history. ## Linked Issues or Issue Description Refs #14325. This replaces its revision-oriented design with persistent agent files. Keep #14325 unmerged. Transport prerequisite #14416 merged first at `d172197117a14b80a1eb2d2835a0e7cce2679656`. This PR now targets master and remains below 100 changed files. Related work: #4513 and #8798 cover instruction tooling. This change handles run synchronization, cross-task personal files, browser editing, and old-session restoration. ## What Changed - Keep one current directory per company and agent. Point AGENT_HOME at a temporary working copy for each active run. Keep task files and provider HOME separate. - Restore text, binary files, and nested folders through workspace transport. Exclude remote agent files from task Git snapshots with a self-ignoring file inside the reserved runtime directory; never write through repository-controlled Git metadata. - Collect after the provider and child processes have stopped. Keep resumable conversation state. - Apply changed and deleted files under the agent lock. The last sync wins for the same file. Unrelated concurrent changes survive. - Remove temporary copies after successful sync, rejected sync, and staging failure. Register ownership before copying so restart recovery can remove interrupted preparation. Retry transient synchronization up to three times. Preserve the original remote lease reference until deletion succeeds; restart cleanup never acquires a replacement sandbox. Do not create captured directories or a conflict-review queue for new runs. - Keep browser editing, stale-draft protection, and streaming binary downloads. Keep the instruction entry and text editor limited to 1 MiB. - Keep historical agent-folder sync failures on their affected runs instead of repeating them above current saved instructions. Preserve legacy candidate review and current browser-save errors. Avoid duplicate quota warnings while retaining separate sync failures when they describe a different problem. - Require target-scoped caller grants for peer instruction access, while preserving self edits, responsible-user checks, and protected-change consent. - Treat full storage as a nonblocking run warning, never an agent pause or run-admission failure. Restore already-over-quota saved folders so ordinary agent cleanup can recover; warn on each run until cleanup. The run detail view shows the warning. - Allow 256 MiB per file, 2 GiB per directory, and 100,000 entries. Hash large files as streams. Check editor-save quotas with metadata instead of hashing unrelated files. - Preserve old native inputs, instruction-only copies, paths, digests, and pending legacy candidates. Adopt old revision heads once. New writes do not append history rows. - Add idempotent migration 0287 and verify upgrades from the preview tables and receipts. - Add nine interactive stories under **Agents / Persistent files**, including automatic incoming edits, stale browser drafts, and storage-limit diagnostics. ## Verification - Merge candidate: `4f5390107ec6ffd80a76d1d2e85530e66f21d079`, after merging current master and the landed transport prerequisite. Integration required no manual conflict resolution; the feature remains 99 changed files. Full workspace typecheck, production build, token gates, and 715 focused tests passed on this merge candidate. Fresh Greptile review is 5/5 with no unresolved findings. All 55 checks passed, with four conditional skips, including the build, typecheck, browser E2E, and canary dry run. A single retry recovered four jobs interrupted by runner shutdowns; no source changes were required. - Historical-warning UI fix: all 6,834 UI tests across 640 files passed, including regression coverage for three old failures, legacy preserved edits, and warnings scoped to the affected run. Full workspace typecheck, production build, Storybook build, and token gates passed. Browser-verified Storybook playtests passed for Historical Failures After Successful Save, Storage Limit, and Full Storage Run Warning. - Review follow-ups at `4e20c9fb2`: all 18 focused tests passed, including external Git directories, linked worktrees, symlinks, hardlinks, and distinct I/O failures alongside storage warnings. Server and UI typechecks, token gates, and the production build passed. - Storage warning regressions at `0724f3012`: all 33 directory tests and all five heartbeat-list tests passed, with no skips in their successful runs. They cover repeated runs while full, an already-over-quota saved folder, cleanup, warnings retained after unrelated save failures, and bounded warnings in large result JSON. Server typecheck passed after the final warning fixes. - Full workspace typecheck, production build, and token gates passed during this follow-up. Product E2E harness: 631 tests passed across 52 files; harness typecheck passed. Earlier native session/context and directory/legacy collection suites passed 537 tests; Runner unit/transport suites passed 329 tests. - **Real E2E at `0724f3012` (before this follow-up):** legacy local Codex and native Daytona Codex each passed six tasks, one server restart, seven independent assertions, and cleanup verification. Both prove browser-to-agent edits, agent-to-browser edits, nested/binary restoration, per-file last-sync-wins, a successful run after an oversized save rejection, and cleanup clearing the warning. - Native local Codex also passed the six-task quota flow before the final warning-retention fixes. That pass began at `918d1ed02` while the bounded-result warning fix was being edited, so it is not claimed as exact-final-head evidence. Its final-head rerun failed during embedded PostgreSQL bootstrap before any provider run: the macOS host had 87,365 of 87,381 SysV semaphores occupied. No unrelated services or kernel limits were changed. - The final-source report intentionally records **2/3 cells passed**, preserving the blocked native-local attempt: `tests/runner-e2e/results/agent-files-quota-final-20260928-report/`. Earlier failed attempts and provenance notes remain under `tests/runner-e2e/results/agent-files-quota-final-20260928-input/` and the original campaign directories. - Daytona used immutable image `ghcr.io/paperclipai/paperclip-daytona-runner@sha256:5643f0d801417cae3581833a1a3bc6715b325e028602738d2652c44cac5dc6bf` and its exact Linux runner binary. Controller source is `0724f3012`; image source is recorded separately. - Legacy-session compatibility and all three ACP Stop/resume browser regressions passed on the prior validated feature head `169fab46d5af21caa2269b4c1b29b69c933a6951`. They assert the same provider session is retained and interrupted writes are not replayed. Migration upgrade tests also passed earlier. - Nine interactive stories are under **Agents / Persistent files**, including **Full Storage Run Warning**. Its playtest and visual browser inspection passed; the warning states that runs continue and the editor remains available. - Prior-head checks on `4e20c9fb2`: 55 passed, two conditional jobs skipped, no failures or pending checks. All eight browser E2E shards and their aggregate passed. Fresh Greptile review is 5/5 with no findings; all review threads are resolved, the security scan passed, and GitHub reports no merge conflicts. - The broad local follow-up test run was interrupted after host semaphore exhaustion affected isolated PostgreSQL instances. It also encountered the existing macOS long-path fixture failure and two timeout failures. This is not a claim that the full local suite passed. Logs are retained; focused storage/warning tests passed. ## Risks - A later sync can overwrite an earlier edit to the same file, including a saved browser edit. There is no text merge or retained version. This is the intended last-sync-wins policy. - A save that exceeds a storage limit is rejected and its temporary copy is discarded. The run itself continues normally, and later runs restore the last saved files with a warning until cleanup. Transient sync failures get bounded retries. An I/O failure partway through a sync can leave some files updated; a failed receipt does not claim whole-folder success. - Larger folders increase copy time, network traffic, and temporary disk usage. Active runs still need working copies. Terminal runs do not accumulate archives. Operators must provision disk for agents and configured concurrency; these limits are not company-wide quotas. - A restored old native session remains instruction-only until a fresh session starts. Its original conflict fence and existing pending candidates remain compatible. - Provider processes close at the collection boundary. Conversation resume remains available, but warm process reuse is lost. - Backups must include the instance filesystem and database. External bundles keep their existing behavior until explicitly moved to managed storage. ## Model Used OpenAI Codex, GPT-6 family. The session does not expose a more specific model ID or context-window size. Reasoning, code execution, and browser tools assisted this change. Real provider E2E uses `gpt-5.6-sol`. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Fry (Paperclip) <noreply@paperclip.ing>
This commit is contained in:
1 parent
d172197117
commit
3ca196b0a6
99 files changed
+7948
-261
No files matched your search
@@ -0,0 +1,539 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import * as executionTargetTools from "@paperclipai/adapter-utils/execution-target";
|
||||
import * as ssh from "@paperclipai/adapter-utils/ssh";
|
||||
const execFile = promisify(execFileCallback);
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createHash, randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agentFileStore, fileHash, inspectAgentFile, snapshotAgentFiles, MAX_AGENT_FILE_BYTES, MAX_AGENT_DIRECTORY_BYTES, MAX_AGENT_DIRECTORY_ENTRIES } from "../services/agent-file-store.js";
|
||||
import { agents, companies, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns, environmentLeases, environments, agentInstructionWorkingCopies, agentInstructionRevisions, agentInstructionHeads, createDb } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionWorkingCopyService, instructionWorkingCopyGuidance } from "../services/agent-instruction-working-copies.js";
|
||||
import { resolveManagedInstructionsRoot } from "../services/agent-instructions.js";
|
||||
import { buildNativeRuntimeContext } from "../services/native-runtime/runtime-context.js";
|
||||
import type { EnvironmentRuntimeService } from "../services/environment-runtime.js";
|
||||
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
||||
|
||||
describe("persistent agent directories", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let copies: ReturnType<typeof agentInstructionWorkingCopyService>;
|
||||
let revisions: ReturnType<typeof agentInstructionRevisionService>;
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
let home: string;
|
||||
let companyId: string, agentId: string, userId: string, root: string;
|
||||
const entryFile = "policy/INSTRUCTIONS.txt";
|
||||
const initial = "\uFEFF# Original\r\n☃\n";
|
||||
const target = () => ({ companyId, agentId });
|
||||
const board = () => ({ type: "board" as const, userId, source: "session" as const });
|
||||
async function run() {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
return (await copies.prepare({ ...target(), runId, cwd: home }))!;
|
||||
}
|
||||
beforeAll(async () => {
|
||||
home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-working-copies-")));
|
||||
process.env.PAPERCLIP_HOME = home;
|
||||
database = await startEmbeddedPostgresTestDatabase("instruction-copies-db-");
|
||||
db = createDb(database.connectionString);
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
revisions = agentInstructionRevisionService(db);
|
||||
}, 90_000);
|
||||
afterAll(async () => {
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
||||
await database?.cleanup();
|
||||
if (home) {
|
||||
const writable = async (dir: string) => {
|
||||
await fs.chmod(dir, 0o700);
|
||||
for (const entry of await fs.readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) await writable(path.join(dir, entry.name));
|
||||
};
|
||||
await writable(home);
|
||||
await fs.rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
beforeEach(async () => {
|
||||
companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Instruction tests", issuePrefix: randomUUID().slice(0, 8) });
|
||||
await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
root = resolveManagedInstructionsRoot({ ...target(), id: agentId, name: "Target", adapterConfig: {} });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } });
|
||||
await db.insert(companyMemberships).values([
|
||||
{ companyId, principalType: "user", principalId: userId, membershipRole: "operator" },
|
||||
{ companyId, principalType: "agent", principalId: agentId, membershipRole: "member" },
|
||||
]);
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: userId, permissionKey: "agents:configure", scope: { agentIds: [agentId] } });
|
||||
await fs.mkdir(path.dirname(path.join(root, entryFile)), { recursive: true });
|
||||
await fs.writeFile(path.join(root, entryFile), initial);
|
||||
});
|
||||
|
||||
it.each([".paperclip-runtime/state", "notes/.paperclip-runtime/state", "promptTemplate.legacy.md"])("rejects reserved board path %s before mutation", async (reserved) => {
|
||||
await expect(agentFileStore(db).write({ ...target(), path: reserved, bytes: Buffer.from("reserved"), baseHash: null }, board())).rejects.toMatchObject({ status: 422 });
|
||||
await expect(fs.stat(path.join(root, reserved))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await run()).toBeTruthy();
|
||||
});
|
||||
|
||||
it("round trips nested text, empty directories and binary bytes independently of task files", async () => {
|
||||
const first = await run();
|
||||
expect(first.localRoot.startsWith(path.join(home, ".paperclip-runtime"))).toBe(false);
|
||||
await fs.mkdir(path.join(first.localRoot, "notes", "empty"), { recursive: true });
|
||||
await fs.writeFile(path.join(first.localRoot, "notes", "fact.txt"), "remember me");
|
||||
const bytes = Buffer.from([0, 255, 17, 128, 9]);
|
||||
await fs.writeFile(path.join(first.localRoot, "image.bin"), bytes);
|
||||
await fs.writeFile(path.join(home, "task-only.txt"), "not personal");
|
||||
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.state).toBe("saved");
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
const next = await run();
|
||||
expect(await fs.readFile(path.join(next.localRoot, "notes", "fact.txt"), "utf8")).toBe("remember me");
|
||||
expect(await fs.readFile(path.join(next.localRoot, "image.bin"))).toEqual(bytes);
|
||||
expect((await fs.stat(path.join(next.localRoot, "notes", "empty"))).isDirectory()).toBe(true);
|
||||
await expect(fs.stat(path.join(next.localRoot, "task-only.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId))).toHaveLength(0);
|
||||
});
|
||||
|
||||
async function sparseFile(filename: string, size: number) {
|
||||
const handle = await fs.open(filename, "w");
|
||||
try { await handle.truncate(size); } finally { await handle.close(); }
|
||||
}
|
||||
|
||||
it("saves and restores files beyond the former file and folder limits, with streaming inspection and download", async () => {
|
||||
const first = await run();
|
||||
const size = 66 * 1024 * 1024;
|
||||
await sparseFile(path.join(first.localRoot, "large.bin"), size);
|
||||
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.state).toBe("saved");
|
||||
await copies.release(companyId, first.runId);
|
||||
const next = await run();
|
||||
const restored = await inspectAgentFile(next.localRoot, "large.bin");
|
||||
expect(restored).toMatchObject({ size, bytes: null });
|
||||
const store = agentFileStore(db);
|
||||
const download = (await store.download(companyId, agentId, "large.bin", board()))!;
|
||||
expect(download.size).toBe(size);
|
||||
// The lock is released before consuming the stream. An editor replacement
|
||||
// must not change the already opened download's bytes.
|
||||
await store.write({ ...target(), path: "large.bin", bytes: Buffer.from("replacement"), baseHash: restored!.hash }, board());
|
||||
const hash = createHash("sha256");
|
||||
let downloaded = 0;
|
||||
for await (const chunk of download.stream) { downloaded += chunk.length; hash.update(chunk); }
|
||||
expect(downloaded).toBe(size);
|
||||
expect(hash.digest("hex")).toBe(restored!.hash);
|
||||
expect(await fs.readFile(path.join(root, "large.bin"), "utf8")).toBe("replacement");
|
||||
await store.write({ ...target(), path: "empty.bin", bytes: Buffer.alloc(0), baseHash: null }, board());
|
||||
const empty = (await store.download(companyId, agentId, "empty.bin", board()))!;
|
||||
expect(empty.size).toBe(0);
|
||||
for await (const _chunk of empty.stream) throw new Error("Empty download must have no chunks");
|
||||
}, 30_000);
|
||||
|
||||
it("accepts the exact 256 MiB file boundary without retaining a text buffer", async () => {
|
||||
expect(MAX_AGENT_FILE_BYTES).toBe(256 * 1024 * 1024);
|
||||
await sparseFile(path.join(root, "boundary.bin"), MAX_AGENT_FILE_BYTES);
|
||||
expect(await inspectAgentFile(root, "boundary.bin")).toMatchObject({ size: MAX_AGENT_FILE_BYTES, bytes: null });
|
||||
});
|
||||
|
||||
it("checks quota for a small editor save without reading unrelated file bytes", async () => {
|
||||
const asset = path.join(root, "large.bin");
|
||||
await sparseFile(asset, MAX_AGENT_FILE_BYTES);
|
||||
const open = vi.spyOn(fs, "open");
|
||||
try {
|
||||
await agentFileStore(db).write({ ...target(), path: "note.txt", bytes: Buffer.from("small edit"), baseHash: null }, board());
|
||||
expect(open.mock.calls.some(([filename]) => filename === asset)).toBe(false);
|
||||
expect(await fs.readFile(path.join(root, "note.txt"), "utf8")).toBe("small edit");
|
||||
} finally { open.mockRestore(); }
|
||||
});
|
||||
|
||||
it("reports an oversized run file without a partial save and removes its temporary copy", async () => {
|
||||
const copy = await run();
|
||||
await sparseFile(path.join(copy.localRoot, "too-large.bin"), MAX_AGENT_FILE_BYTES + 1);
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "changed instructions");
|
||||
const failed = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(failed).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED", candidateHash: null, nextAttemptAt: null, attempts: 1 });
|
||||
expect(failed?.receipt?.storageWarning).toContain("Runs can continue");
|
||||
expect(failed?.errorMessage).toContain('"too-large.bin" exceeds the 256 MiB');
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
||||
await expect(fs.stat(path.join(root, "too-large.bin"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await copies.reportUnavailable(companyId, copy.runId))?.errorCode).toBe("AGENT_FILES_LIMIT_EXCEEDED");
|
||||
await copies.release(companyId, copy.runId);
|
||||
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await copies.get(companyId, copy.runId))?.receipt?.baseline).toBeUndefined();
|
||||
const next = await run();
|
||||
expect(await fs.readFile(path.join(next.localRoot, entryFile), "utf8")).toBe(initial);
|
||||
await fs.writeFile(path.join(next.localRoot, "next-task.txt"), "still working");
|
||||
expect((await copies.collectStopped({ companyId, runId: next.runId }))?.state).toBe("saved");
|
||||
expect(await fs.readFile(path.join(root, "next-task.txt"), "utf8")).toBe("still working");
|
||||
});
|
||||
|
||||
it("warns on each run at the file limit and clears the warning after ordinary agent cleanup", async () => {
|
||||
await sparseFile(path.join(root, "full.bin"), MAX_AGENT_FILE_BYTES);
|
||||
const first = await run();
|
||||
expect(first.receipt?.storageWarning).toContain("256 MiB");
|
||||
expect(instructionWorkingCopyGuidance(first)).toContain("Runs can continue");
|
||||
const unchanged = await copies.collectStopped({ companyId, runId: first.runId });
|
||||
expect(unchanged).toMatchObject({ state: "unchanged", errorCode: null });
|
||||
expect(unchanged?.receipt?.storageWarning).toContain("Agent storage is full");
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
const second = await run();
|
||||
expect(second.receipt?.storageWarning).toContain("Agent storage is full");
|
||||
await fs.unlink(path.join(second.localRoot, "full.bin"));
|
||||
await fs.writeFile(path.join(second.localRoot, "task-output.txt"), "work continues");
|
||||
expect(await copies.collectStopped({ companyId, runId: second.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
||||
const next = await run();
|
||||
expect(next.receipt?.storageWarning).toBeNull();
|
||||
expect(await fs.readFile(path.join(next.localRoot, "task-output.txt"), "utf8")).toBe("work continues");
|
||||
}, 30_000);
|
||||
|
||||
it("starts successive runs with an already oversized saved file and lets the agent remove it", async () => {
|
||||
await sparseFile(path.join(root, "old-large.bin"), MAX_AGENT_FILE_BYTES + 1);
|
||||
const first = await run();
|
||||
expect(first.state).toBe("prepared");
|
||||
expect(first.receipt?.storageWarning).toContain("256 MiB");
|
||||
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
||||
const stopped = await copies.collectStopped({ companyId, runId: first.runId });
|
||||
expect(stopped).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED" });
|
||||
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
const cleanup = await run();
|
||||
expect(cleanup.state).toBe("prepared");
|
||||
await fs.unlink(path.join(cleanup.localRoot, "old-large.bin"));
|
||||
expect(await copies.collectStopped({ companyId, runId: cleanup.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
||||
expect((await run()).receipt?.storageWarning).toBeNull();
|
||||
}, 30_000);
|
||||
|
||||
it("starts when the existing folder exceeds its total quota and accepts agent cleanup", async () => {
|
||||
for (let index = 0; index < 8; index++) await fs.writeFile(path.join(root, `quota-part-${index}.bin`), "fixture");
|
||||
const lstat = fs.lstat.bind(fs);
|
||||
// Keep this regression small on disk while exercising the real filesystem,
|
||||
// snapshots, database receipts, restore, and merge with 2 GiB of metadata.
|
||||
const sizes = vi.spyOn(fs, "lstat").mockImplementation(async (...args: Parameters<typeof fs.lstat>) => {
|
||||
const stat = await lstat(...args);
|
||||
if (path.basename(String(args[0])).startsWith("quota-part-")) Object.assign(stat, { size: MAX_AGENT_FILE_BYTES });
|
||||
return stat;
|
||||
});
|
||||
try {
|
||||
const first = await run();
|
||||
expect(first.receipt?.storageWarning).toContain("2 GiB");
|
||||
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.errorCode).toBe("AGENT_FILES_LIMIT_EXCEEDED");
|
||||
const cleanup = await run();
|
||||
for (let index = 0; index < 8; index++) await fs.unlink(path.join(cleanup.localRoot, `quota-part-${index}.bin`));
|
||||
await fs.writeFile(path.join(cleanup.localRoot, "small.txt"), "recovered");
|
||||
expect(await copies.collectStopped({ companyId, runId: cleanup.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
||||
expect((await run()).receipt?.storageWarning).toBeNull();
|
||||
} finally { sizes.mockRestore(); }
|
||||
});
|
||||
|
||||
it("rejects more than 2 GiB in aggregate before hashing or saving any file", async () => {
|
||||
expect(MAX_AGENT_DIRECTORY_BYTES).toBe(2 * 1024 * 1024 * 1024);
|
||||
const copy = await run();
|
||||
for (let index = 0; index < 8; index++) await sparseFile(path.join(copy.localRoot, `part-${index}.bin`), MAX_AGENT_FILE_BYTES);
|
||||
// The eight allowed files exactly fill the quota; the entry is additional.
|
||||
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(result).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED" });
|
||||
expect(result?.errorMessage).toContain("2 GiB total storage limit");
|
||||
expect(await fs.readdir(root)).toEqual(["policy"]);
|
||||
});
|
||||
|
||||
it("rejects excessive entry count before snapshotting", async () => {
|
||||
const directory = path.join(home, "many-entries");
|
||||
await fs.mkdir(directory);
|
||||
await fs.writeFile(path.join(directory, "empty"), "");
|
||||
const entries = await fs.readdir(directory, { withFileTypes: true });
|
||||
// Exercise the walker bound without creating 100,001 physical files.
|
||||
const readdir = vi.spyOn(fs, "readdir").mockResolvedValue(Array(MAX_AGENT_DIRECTORY_ENTRIES + 1).fill(entries[0]));
|
||||
try {
|
||||
await expect(snapshotAgentFiles(directory)).rejects.toMatchObject({ status: 422, message: expect.stringContaining("100,000-entry limit") });
|
||||
} finally { readdir.mockRestore(); }
|
||||
}, 30_000);
|
||||
|
||||
it("keeps the entry's 1 MiB limit and cleans up failed synchronization", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "a".repeat(1024 * 1024 + 1));
|
||||
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(result?.state).toBe("unavailable");
|
||||
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(result?.errorMessage).toContain("at most 1 MiB");
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
||||
});
|
||||
|
||||
it("merges independent changes and uses the last synchronization for same-file edits", async () => {
|
||||
const a = await run(), b = await run();
|
||||
await fs.writeFile(path.join(a.localRoot, "a.txt"), "A");
|
||||
await fs.writeFile(path.join(b.localRoot, "b.txt"), "B");
|
||||
await Promise.all([a, b].map(copy => copies.collectStopped({ companyId, runId: copy.runId })));
|
||||
expect(await fs.readFile(path.join(root, "a.txt"), "utf8")).toBe("A");
|
||||
expect(await fs.readFile(path.join(root, "b.txt"), "utf8")).toBe("B");
|
||||
const c = await run(), d = await run();
|
||||
await fs.writeFile(path.join(c.localRoot, "a.txt"), "C");
|
||||
await fs.writeFile(path.join(d.localRoot, "a.txt"), "D");
|
||||
await fs.writeFile(path.join(c.localRoot, "b.txt"), "new B");
|
||||
expect((await copies.collectStopped({ companyId, runId: c.runId }))?.state).toBe("saved");
|
||||
expect((await copies.collectStopped({ companyId, runId: d.runId }))?.state).toBe("saved");
|
||||
expect(await fs.readFile(path.join(root, "a.txt"), "utf8")).toBe("D");
|
||||
expect(await fs.readFile(path.join(root, "b.txt"), "utf8")).toBe("new B");
|
||||
expect(await copies.list(companyId, agentId, board())).toEqual([]);
|
||||
for (const copy of [a, b, c, d]) await expect(fs.stat(path.dirname(copy.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await fs.readdir(path.join(path.dirname(root), "file-sync", "runs"))).toEqual([]);
|
||||
});
|
||||
|
||||
it("makes concurrent edit/delete races last-sync-wins and preserves unrelated new files", async () => {
|
||||
await fs.mkdir(path.join(root, "notes"));
|
||||
await fs.writeFile(path.join(root, "notes", "old.txt"), "old");
|
||||
const deleting = await run(), editing = await run();
|
||||
await fs.rm(path.join(deleting.localRoot, "notes"), { recursive: true });
|
||||
await fs.writeFile(path.join(editing.localRoot, "notes", "old.txt"), "edited");
|
||||
await fs.writeFile(path.join(editing.localRoot, "notes", "new.txt"), "unrelated");
|
||||
await copies.collectStopped({ companyId, runId: editing.runId });
|
||||
expect((await copies.collectStopped({ companyId, runId: deleting.runId }))?.state).toBe("saved");
|
||||
await expect(fs.stat(path.join(root, "notes", "old.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(await fs.readFile(path.join(root, "notes", "new.txt"), "utf8")).toBe("unrelated");
|
||||
const remove = await run(), change = await run();
|
||||
await fs.unlink(path.join(remove.localRoot, "notes", "new.txt"));
|
||||
await fs.writeFile(path.join(change.localRoot, "notes", "new.txt"), "restored by later edit");
|
||||
await copies.collectStopped({ companyId, runId: remove.runId });
|
||||
await copies.collectStopped({ companyId, runId: change.runId });
|
||||
expect(await fs.readFile(path.join(root, "notes", "new.txt"), "utf8")).toBe("restored by later edit");
|
||||
});
|
||||
|
||||
it("handles a concurrently replaced parent and keeps the later file change", async () => {
|
||||
await fs.mkdir(path.join(root, "notes"));
|
||||
await fs.writeFile(path.join(root, "notes", "fact.txt"), "old");
|
||||
const replacing = await run(), editing = await run();
|
||||
await fs.rm(path.join(replacing.localRoot, "notes"), { recursive: true });
|
||||
await fs.writeFile(path.join(replacing.localRoot, "notes"), "now a file");
|
||||
await fs.writeFile(path.join(editing.localRoot, "notes", "fact.txt"), "new fact");
|
||||
await copies.collectStopped({ companyId, runId: replacing.runId });
|
||||
expect(await fs.readFile(path.join(root, "notes"), "utf8")).toBe("now a file");
|
||||
expect((await copies.collectStopped({ companyId, runId: editing.runId }))?.state).toBe("saved");
|
||||
expect(await fs.readFile(path.join(root, "notes", "fact.txt"), "utf8")).toBe("new fact");
|
||||
});
|
||||
|
||||
it("cleans stopped copies after a crash during cleanup without touching active copies", async () => {
|
||||
const finished = await run(), active = await run();
|
||||
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date() }).where(eq(agentInstructionWorkingCopies.runId, finished.runId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverCaptured();
|
||||
await expect(fs.stat(finished.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await fs.stat(active.localRoot)).isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
it("cleans up a staging failure before any provider starts", async () => {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "fixture failure" });
|
||||
try {
|
||||
await expect(copies.prepare({ ...target(), runId, cwd: home, target: { kind: "remote", transport: "ssh", environmentId: randomUUID(), remoteCwd: "/fixture/task",
|
||||
spec: { host: "unused.invalid", port: 22, username: "test", remoteCwd: "/fixture/task" } } })).rejects.toThrow("Could not exclude");
|
||||
const row = (await copies.get(companyId, runId))!;
|
||||
expect(row.state).toBe("unavailable");
|
||||
expect(row.receipt?.baseline).toBeUndefined();
|
||||
await expect(fs.stat(path.dirname(row.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
} finally { shell.mockRestore(); }
|
||||
});
|
||||
|
||||
it.each(["succeeded", "failed", "cancelled", "timed_out", "interrupted"])("registers staging ownership before copying and cleans preparation for a %s run after restart", async (status) => {
|
||||
const original = fs.cp.bind(fs);
|
||||
const copy = vi.spyOn(fs, "cp").mockImplementationOnce(async (source, destination, options) => {
|
||||
const rows = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.agentId, agentId));
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ state: "preparing", localRoot: destination });
|
||||
return original(source, destination, options);
|
||||
});
|
||||
const interrupted = await run();
|
||||
copy.mockRestore();
|
||||
const active = await run();
|
||||
for (const row of [interrupted, active]) {
|
||||
await db.update(agentInstructionWorkingCopies).set({ state: "preparing", baseHash: "preparing", receipt: { schema: "paperclip.agent-files.v1" } }).where(eq(agentInstructionWorkingCopies.runId, row.runId));
|
||||
}
|
||||
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, interrupted.runId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverStopped();
|
||||
expect((await copies.get(companyId, interrupted.runId))?.state).toBe("unavailable");
|
||||
await expect(fs.stat(path.dirname(interrupted.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect((await fs.stat(active.localRoot)).isDirectory()).toBe(true);
|
||||
});
|
||||
|
||||
it("retains remote cleanup across restart and failed retries until the original lease is cleaned", async () => {
|
||||
const copy = await run();
|
||||
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
||||
const executionRoot = path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId);
|
||||
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
||||
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "original-sandbox" });
|
||||
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(), location: `remote:${environmentId}`, executionRoot,
|
||||
receipt: { ...copy.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverCaptured();
|
||||
const pending = (await copies.get(companyId, copy.runId))!;
|
||||
expect(pending.receipt).toMatchObject({ cleanupPending: true, cleanup: { leaseId, remoteCwd } });
|
||||
expect(pending.receipt?.baseline).toBeUndefined();
|
||||
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
const execute = vi.fn().mockRejectedValueOnce(new Error("provider temporarily unavailable")).mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" });
|
||||
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
||||
for (const expectedPending of [true, false]) {
|
||||
await db.update(agentInstructionWorkingCopies).set({ nextAttemptAt: null }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
||||
await copies.recoverCaptured();
|
||||
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(expectedPending);
|
||||
}
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
expect(execute).toHaveBeenLastCalledWith(expect.objectContaining({ lease: expect.objectContaining({ id: leaseId, providerLeaseId: "original-sandbox" }),
|
||||
command: "rm", args: ["-rf", "--", executionRoot], bypassSession: true }));
|
||||
await copies.recoverCaptured();
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
await copies.release(companyId, copy.runId);
|
||||
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(false);
|
||||
expect(execute).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
it("finishes remote cleanup from a destruction receipt after the environment is deleted", async () => {
|
||||
const copy = await run();
|
||||
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
||||
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "destroyed-sandbox" };
|
||||
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
||||
await db.insert(environmentLeases).values({ ...lease, status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
||||
metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }) } });
|
||||
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(), location: `remote:${environmentId}`,
|
||||
executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
||||
receipt: { ...copy.receipt, cleanupPending: true, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
||||
await db.delete(environments).where(eq(environments.id, environmentId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverCaptured();
|
||||
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(false);
|
||||
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
});
|
||||
|
||||
it.each([false, true])("rejects symlinks without saving any part of the tree, preserving an existing full-storage warning: %s", async (full) => {
|
||||
if (full) await sparseFile(path.join(root, "full.bin"), MAX_AGENT_FILE_BYTES);
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, "innocent.txt"), "changed");
|
||||
await fs.symlink(path.join(home, "outside"), path.join(copy.localRoot, "escape"));
|
||||
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(result?.state).toBe("unavailable");
|
||||
expect(result?.errorCode).toBe("AGENT_FILES_SAVE_FAILED");
|
||||
expect(result?.receipt?.storageWarning).toBe(copy.receipt?.storageWarning);
|
||||
if (full) expect(result?.receipt?.storageWarning).toContain("Agent storage is full");
|
||||
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await expect(fs.stat(path.join(root, "innocent.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
}, 30_000);
|
||||
|
||||
it("adopts the last deployed head once and bridges an old collector without appending history", async () => {
|
||||
const id = randomUUID();
|
||||
const content = "last deployed revision";
|
||||
await db.insert(agentInstructionRevisions).values({ id, ...target(), entryFile, contentBase64: Buffer.from(content).toString("base64"), contentHash: fileHash(Buffer.from(content)), byteLength: content.length, source: "board" });
|
||||
await db.insert(agentInstructionHeads).values({ ...target(), entryFile, revisionId: id });
|
||||
const current = await revisions.readCurrent(target(), board());
|
||||
expect(current?.content).toBe(content);
|
||||
await revisions.commit({ ...target(), entryFile, content: "new directory contents", baseRevisionId: id, source: "cleanup" }, board());
|
||||
await revisions.materializeCurrent(target());
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe("new directory contents");
|
||||
await expect(revisions.commit({ ...target(), entryFile, content: "stale legacy run", baseRevisionId: id, source: "cleanup" }, board())).rejects.toMatchObject({ status: 409 });
|
||||
expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId))).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("ordinary file edits leave the loaded instruction digest unchanged", async () => {
|
||||
const make = async () => {
|
||||
const copy = await run();
|
||||
const context = await buildNativeRuntimeContext({ db, agent: { id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } },
|
||||
runId: copy.runId, runtimeConfig: {}, runtimeSkillEntries: [], instructionWorkingCopy: { rootPath: copy.executionRoot, entryPath: entryFile, kind: "agent_files" } });
|
||||
return { copy, context };
|
||||
};
|
||||
const before = await make();
|
||||
await fs.writeFile(path.join(before.copy.localRoot, "notes.txt"), "new personal knowledge");
|
||||
await copies.collectStopped({ companyId, runId: before.copy.runId });
|
||||
const after = await make();
|
||||
expect(after.context.aggregateDigest).toBe(before.context.aggregateDigest);
|
||||
expect(after.context.instructions.bundle.fileCount).toBe(1);
|
||||
});
|
||||
it("uses the workspace transport to restore after destruction of the remote filesystem", async () => {
|
||||
const remoteCwd = path.join(home, "remote-task");
|
||||
await fs.mkdir(remoteCwd, { recursive: true });
|
||||
await execFile("git", ["init", remoteCwd]);
|
||||
const runner: import("@paperclipai/adapter-utils/command-managed-runtime").CommandManagedRuntimeRunner = {
|
||||
execute: async input => {
|
||||
const startedAt = new Date().toISOString();
|
||||
const env = { ...process.env, ...input.env };
|
||||
const args = [...(input.args ?? [])];
|
||||
if (input.stdin != null && (args[0] === "-c" || args[0] === "-lc")) {
|
||||
env.PAPERCLIP_TEST_STDIN = input.stdin;
|
||||
args[1] = `printf '%s' "$PAPERCLIP_TEST_STDIN" | (${args[1]})`;
|
||||
}
|
||||
try {
|
||||
const result = await execFile(input.command, args, { cwd: input.cwd, env, timeout: input.timeoutMs, maxBuffer: 32 * 1024 * 1024 });
|
||||
return { exitCode: 0, signal: null, timedOut: false, stdout: result.stdout, stderr: result.stderr, pid: null, startedAt };
|
||||
} catch (error) {
|
||||
const e = error as { code?: number; signal?: NodeJS.Signals; stdout?: string; stderr?: string };
|
||||
return { exitCode: typeof e.code === "number" ? e.code : 1, signal: e.signal ?? null, timedOut: false, stdout: e.stdout ?? "", stderr: e.stderr ?? "", pid: null, startedAt };
|
||||
}
|
||||
},
|
||||
};
|
||||
const executionTarget = { kind: "remote" as const, transport: "sandbox" as const, environmentId: randomUUID(), remoteCwd, runner };
|
||||
const prepare = async () => {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
return (await copies.prepare({ ...target(), runId, cwd: home, target: executionTarget }))!;
|
||||
};
|
||||
await fs.mkdir(path.join(root, "build"));
|
||||
await fs.writeFile(path.join(root, "build", "personal.txt"), "cache-like names are still agent files");
|
||||
const first = await prepare();
|
||||
expect(await fs.readFile(path.join(first.executionRoot, "build", "personal.txt"), "utf8")).toBe("cache-like names are still agent files");
|
||||
await fs.mkdir(path.join(first.executionRoot, "notes"));
|
||||
await fs.writeFile(path.join(first.executionRoot, "notes", "bytes.bin"), Buffer.from([0, 128, 255]));
|
||||
await fs.mkdir(path.join(first.executionRoot, "node_modules"));
|
||||
await fs.writeFile(path.join(first.executionRoot, "node_modules", "personal.txt"), "retain this too");
|
||||
await fs.writeFile(path.join(remoteCwd, "task-only.txt"), "task");
|
||||
expect((await execFile("git", ["-C", remoteCwd, "status", "--porcelain", "--untracked-files=all"])).stdout).toBe("?? task-only.txt\n");
|
||||
expect((await copies.collectStopped({ companyId, runId: first.runId, target: executionTarget }))?.state).toBe("saved");
|
||||
await copies.release(companyId, first.runId);
|
||||
expect((await copies.get(companyId, first.runId))?.receipt?.baseline).toBeUndefined();
|
||||
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await fs.rm(remoteCwd, { recursive: true });
|
||||
await fs.mkdir(remoteCwd);
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
const second = await prepare();
|
||||
expect(await fs.readFile(path.join(second.executionRoot, "notes", "bytes.bin"))).toEqual(Buffer.from([0,128,255]));
|
||||
expect(await fs.readFile(path.join(second.executionRoot, "node_modules", "personal.txt"), "utf8")).toBe("retain this too");
|
||||
await expect(fs.stat(path.join(second.executionRoot, "task-only.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
await copies.collectStopped({ companyId, runId: second.runId, target: executionTarget });
|
||||
await copies.release(companyId, second.runId);
|
||||
});
|
||||
|
||||
it("stages SSH agent files at the registered root without a nested task workspace", async () => {
|
||||
const remoteCwd = path.join(home, "ssh-task");
|
||||
const exclude = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "" });
|
||||
const stage = vi.spyOn(ssh, "syncDirectoryToSsh").mockImplementation(async input => {
|
||||
await fs.mkdir(path.dirname(input.remoteDir), { recursive: true });
|
||||
await fs.cp(input.localDir, input.remoteDir, { recursive: true });
|
||||
});
|
||||
const restore = vi.spyOn(ssh, "restoreWorkspaceFromSshExecution").mockImplementation(async input => {
|
||||
await fs.cp(input.remoteDir!, input.localDir, { recursive: true });
|
||||
});
|
||||
try {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
const target = { kind: "remote" as const, transport: "ssh" as const, environmentId: randomUUID(), remoteCwd,
|
||||
spec: { host: "unused.invalid", port: 22, username: "test", remoteCwd } };
|
||||
const copy = (await copies.prepare({ companyId, agentId, runId, cwd: home, target }))!;
|
||||
expect(stage).toHaveBeenCalledWith(expect.objectContaining({ remoteDir: copy.executionRoot }));
|
||||
expect(await fs.readFile(path.join(copy.executionRoot, entryFile), "utf8")).toBe(initial);
|
||||
await fs.writeFile(path.join(copy.executionRoot, "ssh-note.txt"), "persistent SSH file");
|
||||
expect((await copies.collectStopped({ companyId, runId, target }))?.state).toBe("saved");
|
||||
expect(restore).toHaveBeenCalledWith(expect.objectContaining({ remoteDir: copy.executionRoot, restoreGitHistory: false }));
|
||||
expect(await fs.readFile(path.join(root, "ssh-note.txt"), "utf8")).toBe("persistent SSH file");
|
||||
} finally { stage.mockRestore(); restore.mockRestore(); exclude.mockRestore(); }
|
||||
});
|
||||
|
||||
it("deduplicates concurrent stopped callbacks and discards completed operational snapshots", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, "note.txt"), "one write");
|
||||
const results = await Promise.all([copies.collectStopped({ companyId, runId: copy.runId }), copies.collectStopped({ companyId, runId: copy.runId })]);
|
||||
expect(results.every(result => result?.state === "saved")).toBe(true);
|
||||
// Simulate a crash after save but before release. The restart sweeper must
|
||||
// reclaim operational baselines without touching canonical files.
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverCaptured();
|
||||
const row = await copies.get(companyId, copy.runId);
|
||||
expect(row?.receipt?.schema).toBe("paperclip.agent-files.v1");
|
||||
expect(row?.receipt?.baseline).toBeUndefined();
|
||||
expect(await fs.readFile(path.join(root, "note.txt"), "utf8")).toBe("one write");
|
||||
});
|
||||
|
||||
});
|
||||
@@ -0,0 +1,87 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { instructionGitExcludeProgram } from "../services/agent-instruction-files.js";
|
||||
|
||||
const execFile = promisify(execFileCallback);
|
||||
let root: string;
|
||||
beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), "agent-git-exclusion-")); });
|
||||
afterEach(async () => { await fs.rm(root, { recursive: true, force: true }); });
|
||||
const git = (cwd: string, ...args: string[]) => execFile("git", ["-C", cwd, ...args]);
|
||||
const exclude = (cwd: string) => execFile(process.execPath, ["-e", instructionGitExcludeProgram, cwd]);
|
||||
|
||||
async function assertPrivateFilesIgnored(cwd: string) {
|
||||
const runtime = path.join(cwd, ".paperclip-runtime");
|
||||
await fs.writeFile(path.join(runtime, "private.md"), "agent instructions");
|
||||
await git(cwd, "add", "-A");
|
||||
expect((await git(cwd, "diff", "--cached", "--name-only")).stdout).not.toContain(".paperclip-runtime");
|
||||
expect((await git(cwd, "check-ignore", "--", ".paperclip-runtime/private.md", ".paperclip-runtime/.gitignore")).stdout.trim().split("\n")).toHaveLength(2);
|
||||
}
|
||||
|
||||
it("excludes runtime files without changing tracked ignore rules or Git metadata", async () => {
|
||||
await git(root, "init");
|
||||
await fs.writeFile(path.join(root, ".gitignore"), "keep-me\n");
|
||||
const metadata = path.join(root, ".git", "info", "exclude");
|
||||
const before = await fs.readFile(metadata, "utf8");
|
||||
await exclude(root);
|
||||
await exclude(root);
|
||||
await assertPrivateFilesIgnored(root);
|
||||
expect(await fs.readFile(path.join(root, ".gitignore"), "utf8")).toBe("keep-me\n");
|
||||
expect(await fs.readFile(metadata, "utf8")).toBe(before);
|
||||
});
|
||||
|
||||
it("never writes to an external gitdir selected by task-controlled metadata", async () => {
|
||||
const workspace = path.join(root, "workspace"), outside = path.join(root, "outside.git");
|
||||
await fs.mkdir(workspace);
|
||||
await git(workspace, "init", `--separate-git-dir=${outside}`);
|
||||
const metadata = path.join(outside, "info", "exclude");
|
||||
const before = await fs.readFile(metadata, "utf8");
|
||||
await exclude(workspace);
|
||||
await assertPrivateFilesIgnored(workspace);
|
||||
expect(await fs.readFile(metadata, "utf8")).toBe(before);
|
||||
});
|
||||
|
||||
it("supports linked worktrees and nested task directories without changing the common gitdir", async () => {
|
||||
const repository = path.join(root, "repository"), worktree = path.join(root, "worktree");
|
||||
await fs.mkdir(repository);
|
||||
await git(repository, "init");
|
||||
await git(repository, "-c", "user.name=Test", "-c", "user.email=test@example.test", "commit", "--allow-empty", "-m", "initial");
|
||||
await git(repository, "worktree", "add", "--detach", worktree);
|
||||
const nested = path.join(worktree, "nested");
|
||||
await fs.mkdir(nested);
|
||||
const metadata = path.join(repository, ".git", "info", "exclude");
|
||||
const before = await fs.readFile(metadata, "utf8");
|
||||
await exclude(nested);
|
||||
await assertPrivateFilesIgnored(nested);
|
||||
expect(await fs.readFile(metadata, "utf8")).toBe(before);
|
||||
});
|
||||
|
||||
it.each(["directory", "file"])("rejects a symlink at the runtime exclusion %s", async (kind) => {
|
||||
const workspace = path.join(root, "workspace"), outside = path.join(root, "outside");
|
||||
await fs.mkdir(workspace);
|
||||
await fs.mkdir(outside);
|
||||
const externalFile = path.join(outside, ".gitignore");
|
||||
await fs.writeFile(externalFile, "untouched\n");
|
||||
const runtime = path.join(workspace, ".paperclip-runtime");
|
||||
if (kind === "directory") await fs.symlink(outside, runtime);
|
||||
else {
|
||||
await fs.mkdir(runtime);
|
||||
await fs.symlink(externalFile, path.join(runtime, ".gitignore"));
|
||||
}
|
||||
await expect(exclude(workspace)).rejects.toThrow("Unsafe runtime exclusion");
|
||||
expect(await fs.readFile(externalFile, "utf8")).toBe("untouched\n");
|
||||
});
|
||||
|
||||
it("replaces a linked ignore file without writing through its external inode", async () => {
|
||||
const externalFile = path.join(root, "outside-ignore"), workspace = path.join(root, "workspace");
|
||||
const runtime = path.join(workspace, ".paperclip-runtime");
|
||||
await fs.mkdir(runtime, { recursive: true });
|
||||
await fs.writeFile(externalFile, "untouched\n");
|
||||
await fs.link(externalFile, path.join(runtime, ".gitignore"));
|
||||
await exclude(workspace);
|
||||
expect(await fs.readFile(externalFile, "utf8")).toBe("untouched\n");
|
||||
expect(await fs.readFile(path.join(runtime, ".gitignore"), "utf8")).toBe("*\n");
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { beforeAll, afterAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { and, eq, sql } from "drizzle-orm";
|
||||
import { agents, agentApiKeys, companies, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns,
|
||||
agentInstructionRevisions, agentInstructionHeads, issueThreadInteractions, issues, createDb } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionWorkingCopyService } from "../services/agent-instruction-working-copies.js";
|
||||
import { instructionBytes, instructionPath, materializeInstructionBytes, readInstructionBytes } from "../services/agent-instruction-files.js";
|
||||
import { agentInstructionsService, resolveManagedInstructionsRoot } from "../services/agent-instructions.js";
|
||||
import type { AuthorizationActor } from "../services/authorization.js";
|
||||
import { upsertAgentInstructionsFileSchema } from "@paperclipai/shared";
|
||||
|
||||
describe("canonical instruction revisions", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let service: ReturnType<typeof agentInstructionRevisionService>;
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
let home: string;
|
||||
let companyId: string, agentId: string, userId: string, actorId: string, runId: string, root: string;
|
||||
let actor: AuthorizationActor;
|
||||
const entryFile = "policy/INSTRUCTIONS.txt";
|
||||
const initial = "\uFEFF# Original\r\n☃\0\n";
|
||||
beforeAll(async () => {
|
||||
home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-revisions-")));
|
||||
process.env.PAPERCLIP_HOME = home;
|
||||
database = await startEmbeddedPostgresTestDatabase("instruction-revisions-db-");
|
||||
db = createDb(database.connectionString);
|
||||
service = agentInstructionRevisionService(db);
|
||||
}, 90_000);
|
||||
afterAll(async () => {
|
||||
vi.restoreAllMocks();
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
||||
await database?.cleanup();
|
||||
if (home) await fs.rm(home, { recursive: true, force: true });
|
||||
});
|
||||
beforeEach(async () => {
|
||||
companyId = randomUUID(); agentId = randomUUID(); actorId = randomUUID(); userId = randomUUID(); runId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Instruction tests", issuePrefix: randomUUID().slice(0, 8) });
|
||||
await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
root = resolveManagedInstructionsRoot({ id: agentId, companyId, name: "Target", adapterConfig: {} });
|
||||
await db.insert(agents).values([
|
||||
{ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } },
|
||||
{ id: actorId, companyId, name: "Writer" },
|
||||
]);
|
||||
await db.insert(companyMemberships).values([
|
||||
{ companyId, principalType: "user", principalId: userId, membershipRole: "operator" },
|
||||
{ companyId, principalType: "agent", principalId: actorId, membershipRole: "member" },
|
||||
]);
|
||||
await db.insert(principalPermissionGrants).values([
|
||||
{ companyId, principalType: "user", principalId: userId, permissionKey: "agents:configure", scope: { agentIds: [agentId] } },
|
||||
{ companyId, principalType: "agent", principalId: actorId, permissionKey: "agents:configure", scope: { agentIds: [agentId] } },
|
||||
]);
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId: actorId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
actor = { type: "agent", companyId, agentId: actorId, runId, source: "agent_jwt" };
|
||||
await fs.mkdir(path.dirname(path.join(root, entryFile)), { recursive: true });
|
||||
await fs.writeFile(path.join(root, entryFile), initial);
|
||||
});
|
||||
const target = () => ({ companyId, agentId });
|
||||
async function base() { return (await service.readCurrent(target(), actor))!; }
|
||||
async function save(content: string, baseRevisionId: string | null) {
|
||||
return service.commit({ ...target(), entryFile, content, baseRevisionId, source: "cleanup" }, actor);
|
||||
}
|
||||
it.each(["current", "history", "revision", "diff", "candidates"])("denies peer %s reads without a configuration grant or responsible-user target access", async (operation) => {
|
||||
const first = await base();
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, userId));
|
||||
const read = () => {
|
||||
if (operation === "current") return service.readCurrent(target(), actor);
|
||||
if (operation === "history") return service.history({ ...target(), entryFile }, actor);
|
||||
if (operation === "revision") return service.readRevision({ ...target(), entryFile, revisionId: first.revision.id }, actor);
|
||||
if (operation === "diff") return service.diff({ ...target(), entryFile, fromRevisionId: first.revision.id, toRevisionId: first.revision.id }, actor);
|
||||
return agentInstructionWorkingCopyService(db).list(companyId, agentId, actor);
|
||||
};
|
||||
await expect(read()).rejects.toMatchObject({ status: 403 });
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: userId, permissionKey: "agents:configure", scope: { agentIds: [actorId] } });
|
||||
await expect(read()).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
it.each(["current", "history", "revision", "diff", "candidates", "write"])("requires the caller's own target-scoped grant for peer %s access", async (operation) => {
|
||||
const first = await base();
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, actorId));
|
||||
const access = () => {
|
||||
if (operation === "current") return service.readCurrent(target(), actor);
|
||||
if (operation === "history") return service.history({ ...target(), entryFile }, actor);
|
||||
if (operation === "revision") return service.readRevision({ ...target(), entryFile, revisionId: first.revision.id }, actor);
|
||||
if (operation === "diff") return service.diff({ ...target(), entryFile, fromRevisionId: first.revision.id, toRevisionId: first.revision.id }, actor);
|
||||
if (operation === "write") return save("authorized peer edit", first.revision.id);
|
||||
return agentInstructionWorkingCopyService(db).list(companyId, agentId, actor);
|
||||
};
|
||||
// The responsible user retains permission on the target throughout.
|
||||
await expect(access()).rejects.toMatchObject({ status: 403 });
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "agent", principalId: actorId, permissionKey: "agents:configure", scope: { agentIds: [actorId] } });
|
||||
await expect(access()).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(principalPermissionGrants).set({ scope: { agentIds: [agentId] } }).where(eq(principalPermissionGrants.principalId, actorId));
|
||||
// New saves have no historical revision row; authorized history lookups
|
||||
// reach the normal not-found response rather than an authorization denial.
|
||||
if (operation === "revision" || operation === "diff") await expect(access()).rejects.toMatchObject({ status: 404 });
|
||||
else await expect(access()).resolves.toBeDefined();
|
||||
});
|
||||
it("allows self and board reads without requiring instruction edit permission", async () => {
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, userId));
|
||||
const selfRoot = resolveManagedInstructionsRoot({ id: actorId, companyId, name: "Writer", adapterConfig: {} });
|
||||
await fs.mkdir(selfRoot, { recursive: true });
|
||||
await fs.writeFile(path.join(selfRoot, "AGENTS.md"), "Self instructions");
|
||||
expect((await service.readCurrent({ companyId, agentId: actorId }, actor))?.content).toBe("Self instructions");
|
||||
expect((await service.readCurrent(target(), { type: "board", userId, source: "session" }))?.content).toBe(initial);
|
||||
});
|
||||
it("reads and replaces current bytes using content tokens without storing revisions", async () => {
|
||||
const first = await base();
|
||||
expect(first.content).toBe(initial);
|
||||
const saved = await save("# Changed\r\n", first.revision.id);
|
||||
expect(saved).toMatchObject({ changed: true, materialization: "current" });
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(saved.content);
|
||||
expect((await save(saved.content, first.revision.id)).changed).toBe(false);
|
||||
expect((await service.history({ ...target(), entryFile }, actor)).revisions).toHaveLength(0);
|
||||
expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId))).toHaveLength(0);
|
||||
});
|
||||
it("requires a matching initial content token and serializes competing saves", async () => {
|
||||
await expect(save("without reading", null)).rejects.toMatchObject({ status: 409 });
|
||||
const first = await base();
|
||||
const results = await Promise.allSettled([save("one", first.revision.id), save("two", first.revision.id)]);
|
||||
expect(results.filter(result => result.status === "fulfilled")).toHaveLength(1);
|
||||
expect(results.find(result => result.status === "rejected")).toMatchObject({ reason: { status: 409 } });
|
||||
});
|
||||
it("does not claim a save when atomic file replacement fails", async () => {
|
||||
const first = await base();
|
||||
const rename = vi.spyOn(fs, "rename").mockRejectedValueOnce(new Error("interrupted replacement"));
|
||||
await expect(save("new content", first.revision.id)).rejects.toThrow("interrupted replacement");
|
||||
rename.mockRestore();
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
||||
service = agentInstructionRevisionService(db);
|
||||
await service.materializeCurrent(target());
|
||||
expect((await base()).content).toBe(initial);
|
||||
expect((await save("new content", first.revision.id)).content).toBe("new content");
|
||||
});
|
||||
it("allows authorized peer edits but rejects missing, forged and revoked responsible identity", async () => {
|
||||
const first = await base();
|
||||
await save("peer save", first.revision.id);
|
||||
await expect(service.commit({ ...target(), entryFile, content: "forged", baseRevisionId: first.revision.id, source: "tool" }, { ...actor, onBehalfOfUserId: "forged" })).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, runId));
|
||||
await expect(save("missing", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(heartbeatRuns).set({ responsibleUserId: userId }).where(eq(heartbeatRuns.id, runId));
|
||||
await db.update(companyMemberships).set({ status: "suspended" }).where(and(eq(companyMemberships.principalId, userId), eq(companyMemberships.companyId, companyId)));
|
||||
await expect(save("revoked", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
it("rechecks user target scope and agent containment, even with shadow authorization enabled", async () => {
|
||||
const first = await base();
|
||||
const previousShadow = process.env.PAPERCLIP_RESPONSIBLE_USER_AUTHZ_SHADOW;
|
||||
process.env.PAPERCLIP_RESPONSIBLE_USER_AUTHZ_SHADOW = "true";
|
||||
await db.update(principalPermissionGrants).set({ scope: { agentIds: [actorId] } }).where(eq(principalPermissionGrants.principalId, userId));
|
||||
await expect(save("denied", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(principalPermissionGrants).set({ scope: null }).where(eq(principalPermissionGrants.principalId, userId));
|
||||
await db.update(agents).set({ permissions: { trustPreset: "low_trust_review" } }).where(eq(agents.id, actorId));
|
||||
await expect(save("restricted", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
if (previousShadow === undefined) delete process.env.PAPERCLIP_RESPONSIBLE_USER_AUTHZ_SHADOW; else process.env.PAPERCLIP_RESPONSIBLE_USER_AUTHZ_SHADOW = previousShadow;
|
||||
});
|
||||
it("keeps suggest-only protected-change consent and explicit configure scope restrictions", async () => {
|
||||
const first = await base();
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, actorId));
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "agent", principalId: actorId, permissionKey: "agents:suggest-changes" });
|
||||
await expect(save("needs approval", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, actorId));
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "agent", principalId: actorId, permissionKey: "agents:configure", scope: { agentIds: [actorId] } });
|
||||
await expect(save("out of scope", first.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
it("consumes accepted protected-change approval only with a successful CAS commit", async () => {
|
||||
const first = await base();
|
||||
const sourceRunId = randomUUID(), issueId = randomUUID(), interactionId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId, agentId: actorId, status: "succeeded" });
|
||||
await db.insert(issues).values({ id: issueId, companyId, title: "Review instructions" });
|
||||
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.principalId, actorId));
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "agent", principalId: actorId, permissionKey: "agents:suggest-changes" });
|
||||
await db.insert(issueThreadInteractions).values({ id: interactionId, companyId, issueId, kind: "request_confirmation", status: "accepted", sourceRunId, createdByAgentId: actorId,
|
||||
payload: { version: 1, prompt: "Apply the instruction change?", detailsMarkdown: "```diff\n+approved\n```", target: { type: "custom", key: `agent:${agentId}:instructions`, revisionId: "proposal" } },
|
||||
result: { version: 1, outcome: "accepted" }, resolvedByUserId: userId, resolvedAt: new Date(),
|
||||
});
|
||||
expect((await service.readCurrent(target(), actor))?.revision.id).toBe(first.revision.id);
|
||||
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId)))[0].result).not.toHaveProperty("consumedAt");
|
||||
await expect(save("approved", randomUUID())).rejects.toMatchObject({ status: 409 });
|
||||
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId)))[0].result).not.toHaveProperty("consumedAt");
|
||||
const receipt = await save("approved", first.revision.id);
|
||||
expect(receipt.changed).toBe(true);
|
||||
expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interactionId)))[0].result).toMatchObject({ consumedByRunId: runId });
|
||||
await expect(save("another unapproved change", receipt.revision.id)).rejects.toMatchObject({ status: 403 });
|
||||
});
|
||||
it("shares head/CAS and attribution between board and agent writers", async () => {
|
||||
const first = await base();
|
||||
const board = { type: "board", userId, source: "session" } as const;
|
||||
const saved = await service.commit({ ...target(), entryFile, content: "board edit", baseRevisionId: first.revision.id, source: "board" }, board);
|
||||
expect(saved.revision).toMatchObject({ actorUserId: userId, responsibleUserId: userId, actorAgentId: null, sourceRunId: null, source: "api" });
|
||||
await expect(save("stale agent edit", first.revision.id)).rejects.toMatchObject({ status: 409 });
|
||||
});
|
||||
it("seeds a nested legacy managed entry and never imports a different AGENTS.md", async () => {
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "unrelated");
|
||||
await db.update(agents).set({ adapterConfig: { instructionsFilePath: path.join(root, entryFile) } }).where(eq(agents.id, agentId));
|
||||
const first = await base();
|
||||
expect(first.content).toBe(initial);
|
||||
expect(first.revision.entryFile).toBe(entryFile);
|
||||
await db.update(agents).set({ adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: "missing.md" } }).where(eq(agents.id, agentId));
|
||||
expect(await service.readCurrent(target(), actor)).toBeNull();
|
||||
await expect(save("wrong entry", first.revision.id)).rejects.toMatchObject({ status: 409, details: { code: "INSTRUCTION_ENTRY_CHANGED" } });
|
||||
});
|
||||
it("rejects cross-company targets, foreign revisions, and revoked API keys", async () => {
|
||||
const first = await base();
|
||||
await expect(service.readRevision({ ...target(), entryFile, revisionId: randomUUID() }, actor)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(service.readCurrent({ companyId: randomUUID(), agentId }, actor)).rejects.toMatchObject({ status: 404 });
|
||||
const keyId = randomUUID();
|
||||
await db.insert(agentApiKeys).values({ id: keyId, companyId, agentId: actorId, name: "test", keyHash: randomUUID(), responsibleUserId: userId, revokedAt: new Date() });
|
||||
await expect(service.commit({ ...target(), entryFile, content: "key", baseRevisionId: first.revision.id, source: "api" }, { ...actor, keyId })).rejects.toMatchObject({ status: 403 });
|
||||
await expect(db.insert(agentInstructionHeads).values({ companyId: randomUUID(), agentId, entryFile, revisionId: first.revision.id })).rejects.toThrow();
|
||||
});
|
||||
it("rejects invalid content, symlinks, traversal and external bundles without changing canonical bytes", async () => {
|
||||
const first = await base();
|
||||
expect(() => instructionBytes("\ud800")).toThrow("UTF-8");
|
||||
expect(() => instructionBytes(new Uint8Array([0xff]))).toThrow("UTF-8");
|
||||
expect(() => instructionBytes("a".repeat(1024 * 1024 + 1))).toThrow("1 MiB");
|
||||
for (const value of ["../AGENTS.md", "/etc/passwd", "a/../AGENTS.md", "a\\b", "a//b"]) expect(() => instructionPath(value)).toThrow();
|
||||
await fs.unlink(path.join(root, entryFile));
|
||||
await fs.symlink(path.join(home, "outside"), path.join(root, entryFile));
|
||||
await expect(save("symlink", first.revision.id)).rejects.toMatchObject({ status: 422 });
|
||||
await fs.unlink(path.join(root, entryFile));
|
||||
await fs.rm(path.dirname(path.join(root, entryFile)), { recursive: true });
|
||||
await fs.symlink(home, path.dirname(path.join(root, entryFile)));
|
||||
await expect(readInstructionBytes(root, entryFile)).rejects.toMatchObject({ status: 422 });
|
||||
await db.update(agents).set({ adapterConfig: { instructionsBundleMode: "external", instructionsRootPath: home } }).where(eq(agents.id, agentId));
|
||||
await expect(save("external", first.revision.id)).rejects.toMatchObject({ details: { code: "INSTRUCTION_MANAGED_BUNDLE_REQUIRED" } });
|
||||
expect((await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId)))).toHaveLength(0);
|
||||
});
|
||||
it.skipIf(process.platform !== "darwin")("accepts macOS temporary directory aliases while rejecting links within storage", async () => {
|
||||
const aliasRoot = home.replace(/^\/private\/(var|tmp)\//, "/$1/");
|
||||
expect(aliasRoot).not.toBe(home);
|
||||
await materializeInstructionBytes(aliasRoot, "alias/AGENTS.md", Buffer.from("persisted"));
|
||||
expect(await readInstructionBytes(aliasRoot, "alias/AGENTS.md")).toEqual(Buffer.from("persisted"));
|
||||
await fs.symlink(path.join(home, "alias"), path.join(home, "linked-agent"));
|
||||
await expect(readInstructionBytes(path.join(aliasRoot, "linked-agent"), "AGENTS.md"))
|
||||
.rejects.toMatchObject({ status: 422 });
|
||||
});
|
||||
it("requires the content API for the configured entry and rejects forged fields", async () => {
|
||||
await base();
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
|
||||
await expect(agentInstructionsService(db).writeFile(agent, entryFile, "bypass")).rejects.toMatchObject({ details: { code: "INSTRUCTION_REVISION_REQUIRED" } });
|
||||
await expect(agentInstructionsService(db).deleteFile(agent, entryFile)).rejects.toMatchObject({ status: 422 });
|
||||
expect(upsertAgentInstructionsFileSchema.safeParse({ path: entryFile, content: "bad", responsibleUserId: userId }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,345 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { execFile as execFileCallback } from "node:child_process";
|
||||
import { promisify } from "node:util";
|
||||
import * as gitWorkspaceSync from "@paperclipai/adapter-utils/git-workspace-sync";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { captureDirectorySnapshot } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
||||
const execFile = promisify(execFileCallback);
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { agents, companies, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns, agentInstructionWorkingCopies, createDb } from "@paperclipai/db";
|
||||
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionWorkingCopyService } from "../services/agent-instruction-working-copies.js";
|
||||
import { appendHeartbeatRunEvent } from "../services/heartbeat-run-events.js";
|
||||
import { resolveManagedInstructionsRoot } from "../services/agent-instructions.js";
|
||||
import { buildNativeRuntimeContext } from "../services/native-runtime/runtime-context.js";
|
||||
|
||||
describe("registered run instruction copies", () => {
|
||||
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
||||
let db: ReturnType<typeof createDb>;
|
||||
let copies: ReturnType<typeof agentInstructionWorkingCopyService>;
|
||||
let revisions: ReturnType<typeof agentInstructionRevisionService>;
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
let home: string;
|
||||
let companyId: string, agentId: string, userId: string, root: string;
|
||||
const entryFile = "policy/INSTRUCTIONS.txt";
|
||||
const initial = "\uFEFF# Original\r\n☃\n";
|
||||
const target = () => ({ companyId, agentId });
|
||||
const board = () => ({ type: "board" as const, userId, source: "session" as const });
|
||||
async function run() {
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
return (await copies.prepare({ legacy: true, ...target(), runId, cwd: home }))!;
|
||||
}
|
||||
beforeAll(async () => {
|
||||
home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-working-copies-")));
|
||||
process.env.PAPERCLIP_HOME = home;
|
||||
database = await startEmbeddedPostgresTestDatabase("instruction-copies-db-");
|
||||
db = createDb(database.connectionString);
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
revisions = agentInstructionRevisionService(db);
|
||||
}, 90_000);
|
||||
afterAll(async () => {
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
||||
await database?.cleanup();
|
||||
if (home) {
|
||||
const writable = async (dir: string) => {
|
||||
await fs.chmod(dir, 0o700);
|
||||
for (const entry of await fs.readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) await writable(path.join(dir, entry.name));
|
||||
};
|
||||
await writable(home);
|
||||
await fs.rm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
beforeEach(async () => {
|
||||
companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID();
|
||||
await db.insert(companies).values({ id: companyId, name: "Instruction tests", issuePrefix: randomUUID().slice(0, 8) });
|
||||
await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
||||
root = resolveManagedInstructionsRoot({ ...target(), id: agentId, name: "Target", adapterConfig: {} });
|
||||
await db.insert(agents).values({ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } });
|
||||
await db.insert(companyMemberships).values([
|
||||
{ companyId, principalType: "user", principalId: userId, membershipRole: "operator" },
|
||||
{ companyId, principalType: "agent", principalId: agentId, membershipRole: "member" },
|
||||
]);
|
||||
await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: userId, permissionKey: "agents:configure", scope: { agentIds: [agentId] } });
|
||||
await fs.mkdir(path.dirname(path.join(root, entryFile)), { recursive: true });
|
||||
await fs.writeFile(path.join(root, entryFile), initial);
|
||||
});
|
||||
|
||||
it("persists an atomic editor replacement, ignores repository instructions, and gives the next run exact bytes", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(home, "AGENTS.md"), "Repository text must not become agent instructions");
|
||||
const edited = "\uFEFF# Updated\r\nKeep this persistent. ☃\n";
|
||||
const replacement = path.join(copy.localRoot, "edited.tmp");
|
||||
await fs.writeFile(replacement, edited);
|
||||
await fs.rename(replacement, path.join(copy.localRoot, entryFile));
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
||||
const saved = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(saved).toMatchObject({ state: "saved", candidateHash: expect.any(String), processStoppedAt: expect.any(Date) });
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(edited);
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.receipt).toEqual(saved?.receipt);
|
||||
expect((await revisions.history({ ...target(), entryFile }, board())).revisions).toHaveLength(0);
|
||||
const next = await run();
|
||||
expect(await fs.readFile(path.join(next.localRoot, entryFile), "utf8")).toBe(edited);
|
||||
});
|
||||
|
||||
it.each(["failed", "cancelled", "timed_out"])("retains edits from stopped %s runs without restarting execution", async (status) => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), status);
|
||||
await db.update(heartbeatRuns).set({ status, finishedAt: new Date() }).where(eq(heartbeatRuns.id, copy.runId));
|
||||
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("saved");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe(status);
|
||||
const [unchangedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, copy.runId));
|
||||
expect(unchangedRun.status).toBe(status);
|
||||
});
|
||||
|
||||
it.each(["saved", "unchanged"])("refreshes a stopped %s copy from the current canonical revision before retry", async (state) => {
|
||||
const copy = await run();
|
||||
if (state === "saved") await fs.writeFile(path.join(copy.localRoot, entryFile), "previous saved turn");
|
||||
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe(state);
|
||||
const before = (await revisions.readCurrent(target(), board()))!;
|
||||
const current = await revisions.commit({ ...target(), entryFile, baseRevisionId: before.revision.id, content: "new board instructions", source: "api" }, board());
|
||||
const retried = (await copies.prepare({ legacy: true, ...target(), runId: copy.runId, cwd: home }))!;
|
||||
expect(retried).toMatchObject({ state: "prepared", baseRevisionId: current.revision.id, baseHash: current.revision.contentHash, processStoppedAt: null });
|
||||
expect(await fs.readFile(path.join(retried.localRoot, entryFile), "utf8")).toBe("new board instructions");
|
||||
await fs.writeFile(path.join(retried.localRoot, entryFile), "retry adds a change");
|
||||
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("saved");
|
||||
});
|
||||
|
||||
it("never rebases uncollected private bytes or a live warm copy onto a newer head", async () => {
|
||||
const stopped = await run();
|
||||
await copies.collectStopped({ companyId, runId: stopped.runId });
|
||||
await fs.writeFile(path.join(stopped.localRoot, entryFile), "uncollected private edit");
|
||||
const warm = await run();
|
||||
expect(await copies.hasChanges({ companyId, runId: warm.runId })).toBe(false);
|
||||
const prior = (await revisions.readCurrent(target(), board()))!;
|
||||
await revisions.commit({ ...target(), entryFile, baseRevisionId: prior.revision.id, content: "board change", source: "api" }, board());
|
||||
for (const copy of [stopped, warm]) {
|
||||
const retried = (await copies.prepare({ legacy: true, ...target(), runId: copy.runId, cwd: home }))!;
|
||||
expect(retried.baseRevisionId).toBe(copy.baseRevisionId);
|
||||
}
|
||||
expect(await fs.readFile(path.join(stopped.localRoot, entryFile), "utf8")).toBe("uncollected private edit");
|
||||
expect(await fs.readFile(path.join(warm.localRoot, entryFile), "utf8")).toBe(initial);
|
||||
expect((await copies.collectStopped({ companyId, runId: stopped.runId }))?.state).toBe("conflict");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("board change");
|
||||
});
|
||||
|
||||
it.each(["before replacement", "after replacement"])("preserves the completed receipt when retry staging fails %s", async (point) => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "completed turn");
|
||||
const saved = (await copies.collectStopped({ companyId, runId: copy.runId }))!;
|
||||
expect(saved.state).toBe("saved");
|
||||
const prior = (await revisions.readCurrent(target(), board()))!;
|
||||
const current = await revisions.commit({ ...target(), entryFile, baseRevisionId: prior.revision.id, content: "new board instructions", source: "api" }, board());
|
||||
const originalMkdir = fs.mkdir.bind(fs);
|
||||
const originalChmod = fs.chmod.bind(fs);
|
||||
const mkdir = vi.spyOn(fs, "mkdir").mockImplementation(async (...args: Parameters<typeof fs.mkdir>) => {
|
||||
if (point === "before replacement" && args[0] === copy.localRoot) throw new Error("retry staging failed");
|
||||
return originalMkdir(...args);
|
||||
});
|
||||
const chmod = vi.spyOn(fs, "chmod").mockImplementation(async (...args) => {
|
||||
if (point === "after replacement" && args[0] === path.join(copy.localRoot, entryFile)) throw new Error("retry staging failed");
|
||||
return originalChmod(...args);
|
||||
});
|
||||
try {
|
||||
await expect(copies.prepare({ legacy: true, ...target(), runId: copy.runId, cwd: home })).rejects.toThrow("retry staging failed");
|
||||
} finally { mkdir.mockRestore(); chmod.mockRestore(); }
|
||||
expect(await copies.get(companyId, copy.runId)).toEqual(saved);
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverStopped();
|
||||
expect(await copies.get(companyId, copy.runId)).toEqual(saved);
|
||||
expect((await revisions.readCurrent(target(), board()))?.revision.id).toBe(current.revision.id);
|
||||
const retried = (await copies.prepare({ legacy: true, ...target(), runId: copy.runId, cwd: home }))!;
|
||||
expect(retried).toMatchObject({ state: "prepared", baseRevisionId: current.revision.id, processStoppedAt: null });
|
||||
expect(await fs.readFile(path.join(retried.localRoot, entryFile), "utf8")).toBe(current.content);
|
||||
});
|
||||
|
||||
it("reads an existing canonical runtime snapshot without seeding or changing instruction bytes", async () => {
|
||||
expect((await revisions.readCommittedForRuntime(target()))?.content).toBe(initial);
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "saved runtime content");
|
||||
await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
const current = (await revisions.readCurrent(target(), board()))!;
|
||||
await fs.writeFile(path.join(root, entryFile), "current filesystem contents");
|
||||
expect((await revisions.readCommittedForRuntime(target()))?.content).toBe("current filesystem contents");
|
||||
const [agent] = await db.select().from(agents).where(eq(agents.id, agentId));
|
||||
const context = await buildNativeRuntimeContext({ db, agent, runId: copy.runId, runtimeConfig: {}, runtimeSkillEntries: [] });
|
||||
try {
|
||||
expect(context.instructions.entryPath).toBe(entryFile);
|
||||
expect(await fs.readFile(path.join(context.instructions.bundle.rootPath, entryFile), "utf8"))
|
||||
.toBe("current filesystem contents");
|
||||
} finally {
|
||||
// Runtime assets are immutable, so make only this fixture's directories
|
||||
// removable before the ordinary temporary-home cleanup.
|
||||
const makeRemovable = async (directory: string): Promise<void> => {
|
||||
await fs.chmod(directory, 0o700);
|
||||
for (const child of await fs.readdir(directory, { withFileTypes: true })) {
|
||||
if (child.isDirectory()) await makeRemovable(path.join(directory, child.name));
|
||||
}
|
||||
};
|
||||
await makeRemovable(context.instructions.bundle.rootPath);
|
||||
}
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe("current filesystem contents");
|
||||
expect((await revisions.history({ ...target(), entryFile }, board())).revisions).toHaveLength(0);
|
||||
await expect(revisions.readCommittedForRuntime({ companyId: randomUUID(), agentId })).rejects.toThrow("Agent not found");
|
||||
});
|
||||
|
||||
it("preserves a competing stale candidate and requires explicit resolution against the new head", async () => {
|
||||
const first = await run();
|
||||
const second = await run();
|
||||
await fs.writeFile(path.join(first.localRoot, entryFile), "first run");
|
||||
await fs.writeFile(path.join(second.localRoot, entryFile), "second run");
|
||||
await copies.collectStopped({ companyId, runId: first.runId });
|
||||
const conflict = await copies.collectStopped({ companyId, runId: second.runId });
|
||||
expect(conflict).toMatchObject({ state: "conflict", errorCode: "INSTRUCTION_REVISION_CONFLICT" });
|
||||
expect(Buffer.from(conflict!.candidateBase64!, "base64").toString("utf8")).toBe("second run");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("first run");
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
expect(await copies.list(companyId, agentId, board())).toHaveLength(1);
|
||||
const current = (await revisions.readCurrent(target(), board()))!;
|
||||
await copies.resolve({ ...target(), runId: second.runId, baseRevisionId: current.revision.id, content: "explicitly combined" }, board());
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("explicitly combined");
|
||||
expect((await copies.collectStopped({ companyId, runId: second.runId }))?.state).toBe("resolved");
|
||||
const resumed = (await copies.prepare({ legacy: true, ...target(), runId: second.runId, cwd: home }))!;
|
||||
const resolved = (await revisions.readCurrent(target(), board()))!;
|
||||
expect(resumed.baseRevisionId).toBe(resolved.revision.id);
|
||||
expect(await fs.readFile(path.join(resumed.localRoot, entryFile), "utf8")).toBe("explicitly combined");
|
||||
});
|
||||
|
||||
it("rechecks responsible-user permission at collection and preserves denied edits", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "candidate after revocation");
|
||||
await db.update(companyMemberships).set({ status: "suspended" }).where(eq(companyMemberships.principalId, userId));
|
||||
const denied = await copies.collectStopped({ companyId, runId: copy.runId });
|
||||
expect(denied).toMatchObject({ state: "conflict", errorCode: "RESPONSIBLE_USER_UNAVAILABLE" });
|
||||
expect(denied?.candidateBase64).not.toBeNull();
|
||||
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
||||
});
|
||||
|
||||
it("does not import a symlink or confuse a removed entry with an empty file", async () => {
|
||||
const linked = await run();
|
||||
await fs.unlink(path.join(linked.localRoot, entryFile));
|
||||
await fs.symlink(path.join(home, "AGENTS.md"), path.join(linked.localRoot, entryFile));
|
||||
expect((await copies.collectStopped({ companyId, runId: linked.runId }))?.state).toBe("pending_collection");
|
||||
const missing = await run();
|
||||
await fs.unlink(path.join(missing.localRoot, entryFile));
|
||||
expect((await copies.collectStopped({ companyId, runId: missing.runId }))?.state).toBe("unavailable");
|
||||
const empty = await run();
|
||||
await fs.writeFile(path.join(empty.localRoot, entryFile), "");
|
||||
expect((await copies.collectStopped({ companyId, runId: empty.runId }))?.state).toBe("saved");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("");
|
||||
});
|
||||
|
||||
it("keeps unchanged warm copies reusable without a content revision", async () => {
|
||||
const copy = await run();
|
||||
expect(await copies.hasChanges({ companyId, runId: copy.runId })).toBe(false);
|
||||
expect((await copies.get(companyId, copy.runId))?.processStoppedAt).toBeNull();
|
||||
expect((await revisions.history({ ...target(), entryFile }, board())).revisions).toHaveLength(0);
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "changed after turn");
|
||||
expect(await copies.hasChanges({ companyId, runId: copy.runId })).toBe(true);
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe(initial);
|
||||
});
|
||||
|
||||
it("advances an explicit save baseline only when the private copy matches that revision", async () => {
|
||||
const copy = await run();
|
||||
const local = path.join(copy.localRoot, entryFile);
|
||||
await fs.writeFile(local, "explicit self-save");
|
||||
const first = await revisions.commit({ ...target(), entryFile, baseRevisionId: copy.baseRevisionId, content: "explicit self-save", source: "tool" }, board());
|
||||
await copies.acknowledgeExplicitSave({ ...target(), runId: copy.runId, entryFile, revisionId: first.revision.id, contentHash: first.revision.contentHash });
|
||||
await fs.writeFile(local, "local edit after explicit save");
|
||||
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("saved");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("local edit after explicit save");
|
||||
|
||||
const competing = await run();
|
||||
await fs.writeFile(path.join(competing.localRoot, entryFile), "older local draft");
|
||||
const separate = await revisions.commit({ ...target(), entryFile, baseRevisionId: competing.baseRevisionId, content: "different explicit content", source: "tool" }, board());
|
||||
await copies.acknowledgeExplicitSave({ ...target(), runId: competing.runId, entryFile, revisionId: separate.revision.id, contentHash: separate.revision.contentHash });
|
||||
expect((await copies.collectStopped({ companyId, runId: competing.runId }))?.state).toBe("conflict");
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("different explicit content");
|
||||
expect((await copies.list(companyId, agentId, board()))[0]).not.toHaveProperty("localRoot");
|
||||
});
|
||||
|
||||
it("recovers captured bytes after restart and deduplicates concurrent cleanup callbacks", async () => {
|
||||
const copy = await run();
|
||||
await db.update(agentInstructionWorkingCopies).set({ state: "pending_commit", candidateBase64: Buffer.from("captured before restart").toString("base64"), processStoppedAt: new Date() })
|
||||
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverCaptured();
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("captured before restart");
|
||||
const duplicate = await run();
|
||||
await fs.writeFile(path.join(duplicate.localRoot, entryFile), "one final edit");
|
||||
await Promise.all([copies.collectStopped({ companyId, runId: duplicate.runId }), copies.collectStopped({ companyId, runId: duplicate.runId })]);
|
||||
expect((await copies.get(companyId, duplicate.runId))?.state).toBe("saved");
|
||||
expect((await revisions.history({ ...target(), entryFile }, board())).revisions).toHaveLength(0);
|
||||
});
|
||||
it("requires durable stop evidence before recovering an uncaptured copy", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "edit before controller restart");
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "native", status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, copy.runId));
|
||||
copies = agentInstructionWorkingCopyService(db);
|
||||
await copies.recoverStopped();
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe(initial);
|
||||
expect((await copies.list(companyId, agentId, board()))[0]).toMatchObject({ state: "pending_collection", content: null });
|
||||
await appendHeartbeatRunEvent(db, { ...target(), runId: copy.runId, eventType: "native.local_process_stopped", stream: "system" });
|
||||
await copies.recoverStopped();
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe("edit before controller restart");
|
||||
});
|
||||
|
||||
it("never treats a superseded stop receipt or unavailable environment as a save", async () => {
|
||||
const copy = await run();
|
||||
await fs.writeFile(path.join(copy.localRoot, entryFile), "unverified live edit");
|
||||
await db.update(heartbeatRuns).set({ runtimeMode: "native", status: "failed", finishedAt: new Date() }).where(eq(heartbeatRuns.id, copy.runId));
|
||||
await appendHeartbeatRunEvent(db, { ...target(), runId: copy.runId, eventType: "native.local_process_stopped", stream: "system" });
|
||||
await appendHeartbeatRunEvent(db, { ...target(), runId: copy.runId, eventType: "native.process_start_requested", stream: "system" });
|
||||
await copies.recoverStopped();
|
||||
expect((await revisions.readCurrent(target(), board()))?.content).toBe(initial);
|
||||
const lost = await copies.reportUnavailable(companyId, copy.runId);
|
||||
expect(lost).toMatchObject({ state: "unavailable", candidateBase64: null, processStoppedAt: null });
|
||||
expect(lost?.errorMessage).not.toContain(copy.localRoot);
|
||||
});
|
||||
|
||||
it("keeps private run copies out of normal Git staging and workspace snapshots", async () => {
|
||||
const workspace = path.join(home, `workspace-${randomUUID()}`);
|
||||
await fs.mkdir(workspace);
|
||||
await execFile("git", ["init", workspace]);
|
||||
await execFile("git", ["-C", workspace, "-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "--allow-empty", "-m", "fixture"]);
|
||||
const runId = randomUUID();
|
||||
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
||||
const copy = (await copies.prepare({ legacy: true, ...target(), runId, cwd: workspace }))!;
|
||||
expect(copy.localRoot).toBe(path.join(workspace, ".paperclip-runtime", `instruction-edits-${runId}`, "instructions"));
|
||||
await fs.writeFile(path.join(workspace, "deliverable.txt"), "public work");
|
||||
await execFile("git", ["-C", workspace, "add", "."]);
|
||||
const staged = await execFile("git", ["-C", workspace, "diff", "--cached", "--name-only"]);
|
||||
expect(staged.stdout).toBe("deliverable.txt\n");
|
||||
const snapshot = await gitWorkspaceSync.readGitWorkspaceSnapshot(workspace);
|
||||
try {
|
||||
const paths: unknown = snapshot?.overlayPaths;
|
||||
if (Array.isArray(paths)) {
|
||||
expect(paths).toEqual(["deliverable.txt"]);
|
||||
} else {
|
||||
// The streaming Git snapshot stores the same path set in a private
|
||||
// manifest. Inspect its actual records, not only the reported count.
|
||||
expect(paths).toMatchObject({ kind: "path_manifest", version: 1, category: "overlay", count: 1 });
|
||||
const manifest = paths as { filePath: string; category: string };
|
||||
const manifestDb = new DatabaseSync(manifest.filePath, { readOnly: true, allowExtension: false });
|
||||
try {
|
||||
const rows = manifestDb.prepare("SELECT path FROM records WHERE category = ? ORDER BY path").all(manifest.category);
|
||||
expect(rows.map((row) => row.path)).toEqual(["deliverable.txt"]);
|
||||
} finally { manifestDb.close(); }
|
||||
}
|
||||
} finally {
|
||||
if ("disposeGitWorkspaceSnapshot" in gitWorkspaceSync && typeof gitWorkspaceSync.disposeGitWorkspaceSnapshot === "function") {
|
||||
await gitWorkspaceSync.disposeGitWorkspaceSnapshot(snapshot);
|
||||
}
|
||||
}
|
||||
const files = await captureDirectorySnapshot(workspace, { exclude: [".git", ".paperclip-runtime"] });
|
||||
expect([...files.entries].map(([relative]) => relative)).toEqual(["deliverable.txt"]);
|
||||
await expect(copies.prepare({ legacy: true, ...target(), runId, cwd: home })).rejects.toThrow("different run workspace");
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { Readable } from "node:stream";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mockAgentService = vi.hoisted(() => ({
|
||||
@@ -24,6 +25,21 @@ const mockAgentInstructionsService = vi.hoisted(() => ({
|
||||
materializeManagedBundle: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockInstructionWorkingCopies = vi.hoisted(() => ({ list: vi.fn(), resolve: vi.fn(), acknowledgeExplicitSave: vi.fn() }));
|
||||
vi.mock("../services/agent-instruction-working-copies.js", () => ({ agentInstructionWorkingCopyService: () => mockInstructionWorkingCopies }));
|
||||
|
||||
const mockDownloadAgentFile = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/agent-file-store.js", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("../services/agent-file-store.js")>();
|
||||
return { ...actual, agentFileStore: (...args: Parameters<typeof actual.agentFileStore>) => ({ ...actual.agentFileStore(...args), download: mockDownloadAgentFile }) };
|
||||
});
|
||||
|
||||
const mockInstructionRevisions = vi.hoisted(() => ({ readCurrent: vi.fn(), commit: vi.fn(), restore: vi.fn(), history: vi.fn(), readRevision: vi.fn(), diff: vi.fn(), materializeCurrent: vi.fn() }));
|
||||
vi.mock("../services/agent-instruction-revisions.js", () => ({ agentInstructionRevisionService: () => mockInstructionRevisions }));
|
||||
|
||||
const mockAuthorizeInstructionRead = vi.hoisted(() => vi.fn());
|
||||
vi.mock("../services/agent-instruction-authorization.js", () => ({ authorizeInstructionRead: mockAuthorizeInstructionRead }));
|
||||
|
||||
const mockAccessService = vi.hoisted(() => ({
|
||||
canUser: vi.fn(),
|
||||
decide: vi.fn(),
|
||||
@@ -202,6 +218,9 @@ describe("agent instructions bundle routes", () => {
|
||||
vi.doUnmock("../middleware/index.js");
|
||||
registerModuleMocks();
|
||||
vi.clearAllMocks();
|
||||
mockAuthorizeInstructionRead.mockImplementation(async (_db, actor) => actor);
|
||||
mockInstructionRevisions.readCurrent.mockResolvedValue(null);
|
||||
mockInstructionRevisions.commit.mockResolvedValue({ revision: { id: "33333333-3333-4333-8333-333333333333", entryFile: "AGENTS.md", byteLength: 18 }, content: "# Updated Agent\n", changed: true, materialization: "current" });
|
||||
mockBuiltInAgentService.ensureCompanyDefaultAgentGrants.mockResolvedValue(0);
|
||||
mockSyncInstructionsBundleConfigFromFilePath.mockImplementation((_agent, config) => config);
|
||||
mockFindServerAdapter.mockImplementation((_type: string) => ({ type: _type }));
|
||||
@@ -286,6 +305,8 @@ describe("agent instructions bundle routes", () => {
|
||||
entryFile: "AGENTS.md",
|
||||
});
|
||||
expect(mockAgentInstructionsService.getBundle).toHaveBeenCalled();
|
||||
expect(mockAuthorizeInstructionRead).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({ type: "board" }),
|
||||
expect.objectContaining({ companyId: "company-1", id: "11111111-1111-4111-8111-111111111111" }));
|
||||
});
|
||||
|
||||
it("requires instance-admin access for every external instruction entry point", async () => {
|
||||
@@ -331,6 +352,7 @@ describe("agent instructions bundle routes", () => {
|
||||
expect(mockAgentInstructionsService.updateBundle).not.toHaveBeenCalled();
|
||||
expect(mockAgentInstructionsService.writeFile).not.toHaveBeenCalled();
|
||||
expect(mockAgentInstructionsService.deleteFile).not.toHaveBeenCalled();
|
||||
expect(mockAuthorizeInstructionRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("treats a host root mislabeled as managed as external", async () => {
|
||||
@@ -383,6 +405,7 @@ describe("agent instructions bundle routes", () => {
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockAgentInstructionsService.getBundle).toHaveBeenCalled();
|
||||
expect(mockAuthorizeInstructionRead).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("rejects a company admin that requests a new external instruction root", async () => {
|
||||
@@ -484,7 +507,8 @@ describe("agent instructions bundle routes", () => {
|
||||
expect(mockAgentService.create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("denies non-privileged agents from reading peer instructions bundles", async () => {
|
||||
it.each(["", "/file?path=AGENTS.md", "/file?path=private-support.md"])(
|
||||
"denies peer instruction reads before any data dispatch: %s", async (suffix) => {
|
||||
mockAgentService.getById.mockImplementation(async (id: string) => {
|
||||
if (id === "agent-reader") {
|
||||
return {
|
||||
@@ -496,11 +520,10 @@ describe("agent instructions bundle routes", () => {
|
||||
}
|
||||
return makeAgent();
|
||||
});
|
||||
mockAccessService.decide.mockResolvedValue({
|
||||
allowed: false,
|
||||
reason: "deny_no_grant",
|
||||
explanation: "Missing permission: agents:configure or agents:suggest-changes.",
|
||||
});
|
||||
// General agent visibility is allowed. It must not authorize instruction
|
||||
// metadata, canonical entry bytes, or supporting files from a peer.
|
||||
const { forbidden } = await vi.importActual<typeof import("../errors.js")>("../errors.js");
|
||||
mockAuthorizeInstructionRead.mockRejectedValue(forbidden("Missing permission to read peer instructions"));
|
||||
|
||||
const res = await requestApp(
|
||||
await createApp({
|
||||
@@ -510,20 +533,18 @@ describe("agent instructions bundle routes", () => {
|
||||
source: "agent_key",
|
||||
}),
|
||||
(baseUrl) => request(baseUrl)
|
||||
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle"),
|
||||
.get(`/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle${suffix}`),
|
||||
);
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(403);
|
||||
expect(res.body.error).toContain("Missing permission");
|
||||
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
|
||||
action: "agent_config:read",
|
||||
resource: {
|
||||
type: "agent",
|
||||
companyId: "company-1",
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
},
|
||||
}));
|
||||
expect(mockAuthorizeInstructionRead).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
type: "agent", agentId: "agent-reader",
|
||||
}), { companyId: "company-1", id: "11111111-1111-4111-8111-111111111111" });
|
||||
expect(mockAgentInstructionsService.getBundle).not.toHaveBeenCalled();
|
||||
expect(mockAgentInstructionsService.readFile).not.toHaveBeenCalled();
|
||||
expect(mockInstructionRevisions.readCurrent).not.toHaveBeenCalled();
|
||||
expect(mockInstructionRevisions.materializeCurrent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows agents to read their own instructions bundles", async () => {
|
||||
@@ -540,9 +561,12 @@ describe("agent instructions bundle routes", () => {
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockAgentInstructionsService.getBundle).toHaveBeenCalled();
|
||||
expect(mockAuthorizeInstructionRead).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
type: "agent", agentId: "11111111-1111-4111-8111-111111111111",
|
||||
}), { companyId: "company-1", id: "11111111-1111-4111-8111-111111111111" });
|
||||
});
|
||||
|
||||
it("allows agents with suggest grants to read peer instructions bundles", async () => {
|
||||
it.each(["AGENTS.md", "private-support.md"])("allows an authorized peer to read instruction file %s", async (filePath) => {
|
||||
mockAccessService.decide.mockResolvedValue({
|
||||
allowed: true,
|
||||
reason: "allow_explicit_grant",
|
||||
@@ -570,52 +594,100 @@ describe("agent instructions bundle routes", () => {
|
||||
}),
|
||||
(baseUrl) => request(baseUrl)
|
||||
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file")
|
||||
.query({ path: "AGENTS.md" }),
|
||||
.query({ path: filePath }),
|
||||
);
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockAccessService.decide).toHaveBeenCalledWith(expect.objectContaining({
|
||||
action: "agent_config:read",
|
||||
resource: {
|
||||
type: "agent",
|
||||
companyId: "company-1",
|
||||
agentId: "11111111-1111-4111-8111-111111111111",
|
||||
},
|
||||
}));
|
||||
expect(mockAuthorizeInstructionRead).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
type: "agent", agentId: "coach-agent",
|
||||
}), { companyId: "company-1", id: "11111111-1111-4111-8111-111111111111" });
|
||||
expect(mockAgentInstructionsService.readFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }),
|
||||
"AGENTS.md",
|
||||
filePath,
|
||||
);
|
||||
});
|
||||
|
||||
it("writes a bundle file and persists compatibility config", async () => {
|
||||
it("commits entry bytes through the canonical service with the authenticated actor", async () => {
|
||||
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
||||
.put("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file?companyId=company-1")
|
||||
.send({
|
||||
path: "AGENTS.md",
|
||||
content: "# Updated Agent\n",
|
||||
clearLegacyPromptTemplate: true,
|
||||
}));
|
||||
|
||||
.send({ path: "AGENTS.md", content: "# Updated Agent\n", baseRevisionId: null }));
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockAgentInstructionsService.writeFile).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ id: "11111111-1111-4111-8111-111111111111" }),
|
||||
"AGENTS.md",
|
||||
"# Updated Agent\n",
|
||||
{ clearLegacyPromptTemplate: true },
|
||||
);
|
||||
expect(mockAgentService.update).toHaveBeenCalledWith(
|
||||
"11111111-1111-4111-8111-111111111111",
|
||||
expect.objectContaining({
|
||||
adapterConfig: expect.objectContaining({
|
||||
instructionsBundleMode: "managed",
|
||||
instructionsRootPath: "/tmp/agent-1",
|
||||
instructionsEntryFile: "AGENTS.md",
|
||||
instructionsFilePath: "/tmp/agent-1/AGENTS.md",
|
||||
}),
|
||||
}),
|
||||
expect.any(Object),
|
||||
);
|
||||
expect(mockInstructionRevisions.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
agentId: "11111111-1111-4111-8111-111111111111", entryFile: "AGENTS.md", content: "# Updated Agent\n", baseRevisionId: null, source: "board",
|
||||
}), expect.objectContaining({ type: "board" }));
|
||||
expect(mockAgentInstructionsService.writeFile).not.toHaveBeenCalled();
|
||||
expect(res.body.receipt.revision.id).toBe("33333333-3333-4333-8333-333333333333");
|
||||
});
|
||||
|
||||
it("returns committed entry content independently of its disk copy", async () => {
|
||||
mockInstructionRevisions.readCurrent.mockResolvedValue({ revision: { id: "33333333-3333-4333-8333-333333333333", entryFile: "AGENTS.md", byteLength: 9 }, content: "committed" });
|
||||
const res = await requestApp(await createApp(), (baseUrl) => request(baseUrl)
|
||||
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file?path=AGENTS.md"));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.content).toBe("committed");
|
||||
expect(res.body.revision.id).toBe("33333333-3333-4333-8333-333333333333");
|
||||
expect(mockAgentInstructionsService.readFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it.each([Buffer.from([0, 255, 128, 17]), Buffer.alloc(0)])("streams an authorized binary download without text conversion (%j)", async bytes => {
|
||||
mockAgentService.getById.mockResolvedValue({ ...makeAgent(), adapterConfig: { instructionsBundleMode: "managed" } });
|
||||
mockDownloadAgentFile.mockResolvedValue({ size: bytes.length, stream: Readable.from(bytes.length ? [bytes] : []) });
|
||||
const res = await requestApp(await createApp(), url => request(url)
|
||||
.get("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file")
|
||||
.query({ path: "notes/data.bin", download: "true" }));
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(res.body).toEqual(bytes);
|
||||
expect(res.headers["content-length"]).toBe(String(bytes.length));
|
||||
expect(res.headers["content-disposition"]).toContain('filename="data.bin"');
|
||||
expect(mockDownloadAgentFile).toHaveBeenCalledWith("company-1", "11111111-1111-4111-8111-111111111111", "notes/data.bin", expect.objectContaining({ type: "board" }));
|
||||
expect(mockAgentInstructionsService.readFile).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("lists and resolves preserved edits with server scope, actor, and explicit revision", async () => {
|
||||
const app = await createApp();
|
||||
const runId = "55555555-5555-4555-8555-555555555555";
|
||||
const baseRevisionId = "44444444-4444-4444-8444-444444444444";
|
||||
const prefix = "/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/candidates";
|
||||
mockInstructionWorkingCopies.list.mockResolvedValue([{ runId, entryFile: "AGENTS.md", state: "conflict", content: "preserved" }]);
|
||||
mockInstructionWorkingCopies.resolve.mockResolvedValue({ revision: { id: baseRevisionId, entryFile: "AGENTS.md", byteLength: 8 }, content: "resolved", changed: true, materialization: "current" });
|
||||
const listed = await requestApp(app, (url) => request(url).get(prefix));
|
||||
expect(listed.status).toBe(200);
|
||||
expect(listed.body).toEqual([{ runId, entryFile: "AGENTS.md", state: "conflict", content: "preserved" }]);
|
||||
expect(mockInstructionWorkingCopies.list).toHaveBeenCalledWith("company-1", "11111111-1111-4111-8111-111111111111", expect.objectContaining({ type: "board", userId: "local-board" }));
|
||||
const resolved = await requestApp(app, (url) => request(url).post(`${prefix}/${runId}/resolve`).send({ baseRevisionId, content: "resolved" }));
|
||||
expect(resolved.status).toBe(200);
|
||||
expect(resolved.body).toMatchObject({ content: "resolved", receipt: { changed: true } });
|
||||
expect(mockInstructionWorkingCopies.resolve).toHaveBeenCalledWith({ companyId: "company-1", agentId: "11111111-1111-4111-8111-111111111111", runId, baseRevisionId, content: "resolved" }, expect.objectContaining({ type: "board", userId: "local-board" }));
|
||||
for (const body of [{ content: "missing base" }, { baseRevisionId, content: "forged", responsibleUserId: "other" }, { baseRevisionId, content: "forged", entryFile: "other.md" }]) {
|
||||
expect((await requestApp(app, (url) => request(url).post(`${prefix}/${runId}/resolve`).send(body))).status).toBe(400);
|
||||
}
|
||||
expect(mockInstructionWorkingCopies.resolve).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
it("exposes scoped history, diff and restore with the server actor", async () => {
|
||||
const app = await createApp();
|
||||
const revisionId = "33333333-3333-4333-8333-333333333333";
|
||||
const baseRevisionId = "44444444-4444-4444-8444-444444444444";
|
||||
const prefix = "/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle";
|
||||
mockInstructionRevisions.history.mockResolvedValue({ revisions: [], nextCursor: null });
|
||||
mockInstructionRevisions.diff.mockResolvedValue({ removed: "old", added: "new" });
|
||||
mockInstructionRevisions.restore.mockResolvedValue({ revision: { id: revisionId, entryFile: "AGENTS.md", byteLength: 3 }, content: "old", changed: true, materialization: "current" });
|
||||
expect((await requestApp(app, (url) => request(url).get(`${prefix}/history?path=AGENTS.md`))).status).toBe(200);
|
||||
expect((await requestApp(app, (url) => request(url).get(`${prefix}/diff?path=AGENTS.md&from=${revisionId}&to=${baseRevisionId}`))).status).toBe(200);
|
||||
const restored = await requestApp(app, (url) => request(url).post(`${prefix}/restore`).send({ path: "AGENTS.md", revisionId, baseRevisionId }));
|
||||
expect(restored.status).toBe(200);
|
||||
expect(restored.body.receipt.changed).toBe(true);
|
||||
expect(mockInstructionRevisions.restore).toHaveBeenCalledWith({ companyId: "company-1", agentId: "11111111-1111-4111-8111-111111111111", entryFile: "AGENTS.md", revisionId, baseRevisionId }, expect.objectContaining({ type: "board", userId: "local-board" }));
|
||||
});
|
||||
|
||||
it("requires a base revision and rejects client-supplied responsible identity", async () => {
|
||||
const app = await createApp();
|
||||
for (const body of [ { path: "AGENTS.md", content: "stale" }, { path: "AGENTS.md", content: "forged", baseRevisionId: null, responsibleUserId: "forged" } ]) {
|
||||
const res = await requestApp(app, (baseUrl) => request(baseUrl)
|
||||
.put("/api/agents/11111111-1111-4111-8111-111111111111/instructions-bundle/file").send(body));
|
||||
expect([400, 422]).toContain(res.status);
|
||||
}
|
||||
expect(mockInstructionRevisions.commit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("preserves managed instructions config when switching adapters", async () => {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import fs from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
||||
import { agentInstructionsService } from "../services/agent-instructions.js";
|
||||
|
||||
type TestAgent = {
|
||||
@@ -12,7 +12,7 @@ type TestAgent = {
|
||||
};
|
||||
|
||||
async function makeTempDir(prefix: string) {
|
||||
return fs.mkdtemp(path.join(os.tmpdir(), prefix));
|
||||
return fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), prefix)));
|
||||
}
|
||||
|
||||
function makeAgent(adapterConfig: Record<string, unknown>): TestAgent {
|
||||
@@ -29,6 +29,13 @@ describe("agent instructions service", () => {
|
||||
const originalPaperclipInstanceId = process.env.PAPERCLIP_INSTANCE_ID;
|
||||
const cleanupDirs = new Set<string>();
|
||||
|
||||
beforeEach(async () => {
|
||||
const home = await makeTempDir("agent-instructions-test-home-");
|
||||
cleanupDirs.add(home);
|
||||
process.env.PAPERCLIP_HOME = home;
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "instructions-service-test";
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (originalPaperclipHome === undefined) delete process.env.PAPERCLIP_HOME;
|
||||
else process.env.PAPERCLIP_HOME = originalPaperclipHome;
|
||||
@@ -41,6 +48,37 @@ describe("agent instructions service", () => {
|
||||
}));
|
||||
});
|
||||
|
||||
it.each(["./AGENTS.md", "notes/../AGENTS.md", "notes\\..\\AGENTS.md", "../invalid"])("reads legacy entry configuration %s without breaking the bundle", async (entry) => {
|
||||
const root = await makeTempDir("legacy-entry-"); cleanupDirs.add(root);
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "legacy instructions");
|
||||
const agent = makeAgent({ instructionsBundleMode: "external", instructionsRootPath: root, instructionsEntryFile: entry });
|
||||
const svc = agentInstructionsService();
|
||||
const bundle = await svc.getBundle(agent);
|
||||
expect(bundle.entryFile).toBe("AGENTS.md");
|
||||
expect((await svc.readFile(agent, bundle.entryFile)).content).toBe("legacy instructions");
|
||||
if (entry === "../invalid") expect(bundle.warnings.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("lists external bundles containing large binary assets", async () => {
|
||||
const root = await makeTempDir("external-large-assets-"); cleanupDirs.add(root);
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "external instructions");
|
||||
const asset = await fs.open(path.join(root, "large.bin"), "w");
|
||||
try { await asset.truncate(17 * 1024 * 1024); } finally { await asset.close(); }
|
||||
const agent = makeAgent({ instructionsBundleMode: "external", instructionsRootPath: root });
|
||||
const svc = agentInstructionsService();
|
||||
const bundle = await svc.getBundle(agent);
|
||||
expect(bundle.files).toContainEqual(expect.objectContaining({ path: "large.bin", binary: true, editable: false }));
|
||||
expect((await svc.readFile(agent, "AGENTS.md")).content).toBe("external instructions");
|
||||
});
|
||||
|
||||
it("rejects reserved paths while initializing an unconfigured managed bundle", async () => {
|
||||
const root = await makeTempDir("unconfigured-reserved-path-"); cleanupDirs.add(root);
|
||||
process.env.PAPERCLIP_HOME = root;
|
||||
const svc = agentInstructionsService();
|
||||
await expect(svc.writeFile(makeAgent({}), ".paperclip-runtime/state", "invalid")).rejects.toMatchObject({ status: 422 });
|
||||
expect(await fs.readdir(root)).toEqual([]);
|
||||
});
|
||||
|
||||
it("copies the existing bundle into the managed root when switching to managed mode", async () => {
|
||||
const paperclipHome = await makeTempDir("paperclip-agent-instructions-home-");
|
||||
const externalRoot = await makeTempDir("paperclip-agent-instructions-external-");
|
||||
@@ -53,7 +91,7 @@ describe("agent instructions service", () => {
|
||||
await fs.mkdir(path.join(externalRoot, "docs"), { recursive: true });
|
||||
await fs.writeFile(path.join(externalRoot, "docs", "TOOLS.md"), "## Tools\n", "utf8");
|
||||
|
||||
const svc = agentInstructionsService();
|
||||
const svc = agentInstructionsService({ select: () => ({ from: () => ({ where: async () => [] }) }) } as never);
|
||||
const agent = makeAgent({
|
||||
instructionsBundleMode: "external",
|
||||
instructionsRootPath: externalRoot,
|
||||
@@ -250,11 +288,10 @@ describe("agent instructions service", () => {
|
||||
|
||||
expect(bundle.mode).toBe("managed");
|
||||
expect(bundle.rootPath).toBe(managedRoot);
|
||||
expect(bundle.entryFile).toBe("AGENTS.md");
|
||||
expect(bundle.entryFile).toBe("docs/MISSING.md");
|
||||
expect(bundle.files.map((file) => file.path)).toEqual(["AGENTS.md"]);
|
||||
expect(bundle.warnings).toEqual([
|
||||
`Recovered managed instructions from disk at ${managedRoot}; ignoring stale configured root ${staleRoot}.`,
|
||||
"Recovered managed instructions entry file from disk as AGENTS.md; previous entry docs/MISSING.md was missing.",
|
||||
]);
|
||||
expect(exported.files).toEqual({ "AGENTS.md": "# Managed Agent\n" });
|
||||
});
|
||||
@@ -293,8 +330,8 @@ describe("agent instructions service", () => {
|
||||
expect(result.adapterConfig).toMatchObject({
|
||||
instructionsBundleMode: "managed",
|
||||
instructionsRootPath: managedRoot,
|
||||
instructionsEntryFile: "AGENTS.md",
|
||||
instructionsFilePath: path.join(managedRoot, "AGENTS.md"),
|
||||
instructionsEntryFile: "docs/MISSING.md",
|
||||
instructionsFilePath: path.join(managedRoot, "docs/MISSING.md"),
|
||||
});
|
||||
await expect(fs.readFile(path.join(managedRoot, "docs", "TOOLS.md"), "utf8")).resolves.toBe("## Tools\n");
|
||||
});
|
||||
@@ -334,8 +371,8 @@ describe("agent instructions service", () => {
|
||||
expect(result.adapterConfig).toMatchObject({
|
||||
instructionsBundleMode: "managed",
|
||||
instructionsRootPath: managedRoot,
|
||||
instructionsEntryFile: "AGENTS.md",
|
||||
instructionsFilePath: path.join(managedRoot, "AGENTS.md"),
|
||||
instructionsEntryFile: "docs/MISSING.md",
|
||||
instructionsFilePath: path.join(managedRoot, "docs/MISSING.md"),
|
||||
});
|
||||
await expect(fs.stat(path.join(managedRoot, "docs", "TOOLS.md"))).rejects.toThrow();
|
||||
expect(result.bundle.files.map((file) => file.path)).toEqual(["AGENTS.md"]);
|
||||
@@ -373,11 +410,10 @@ describe("agent instructions service", () => {
|
||||
|
||||
expect(bundle.mode).toBe("managed");
|
||||
expect(bundle.rootPath).toBe(managedRoot);
|
||||
expect(bundle.entryFile).toBe("AGENTS.md");
|
||||
expect(bundle.entryFile).toBe("docs/MISSING.md");
|
||||
expect(bundle.files.map((file) => file.path)).toEqual(["AGENTS.md"]);
|
||||
expect(bundle.warnings).toEqual([
|
||||
`Recovered managed instructions from disk at ${managedRoot}; ignoring stale configured root ${staleRoot}.`,
|
||||
"Recovered managed instructions entry file from disk as AGENTS.md; previous entry docs/MISSING.md was missing.",
|
||||
]);
|
||||
expect(exported.files).toEqual({ "AGENTS.md": "# Managed Agent\n" });
|
||||
});
|
||||
|
||||
@@ -412,7 +412,7 @@ describe("built-in agent routes", () => {
|
||||
.send({});
|
||||
|
||||
expect(res.status, JSON.stringify(res.body)).toBe(200);
|
||||
expect(mockBuiltInAgentService.reset).toHaveBeenCalledWith(companyId, "briefs", {});
|
||||
expect(mockBuiltInAgentService.reset).toHaveBeenCalledWith(companyId, "briefs", {}, expect.objectContaining({ type: "agent", agentId: "manager-agent" }));
|
||||
expect(mockLogActivity).toHaveBeenCalledWith(expect.anything(), expect.objectContaining({
|
||||
companyId,
|
||||
actorType: "agent",
|
||||
|
||||
@@ -1,3 +1,6 @@
|
||||
import fs from "node:fs/promises";
|
||||
import { fileHash } from "../services/agent-file-store.js";
|
||||
import { stockHash } from "../services/managed-resource-drift.js";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
@@ -27,6 +30,7 @@ import {
|
||||
getEmbeddedPostgresTestSupport,
|
||||
startEmbeddedPostgresTestDatabase,
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionsService } from "../services/agent-instructions.ts";
|
||||
import { agentService } from "../services/agents.ts";
|
||||
import { approvalService } from "../services/approvals.ts";
|
||||
@@ -116,6 +120,16 @@ describe("built-in agent asset loading", () => {
|
||||
describeEmbeddedPostgres("built-in agents", () => {
|
||||
let db!: ReturnType<typeof createDb>;
|
||||
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
|
||||
const instructionOperator = { type: "board", userId: "local-board", source: "local_implicit" } as const;
|
||||
async function writeInstructionEntry(agent: { id: string; companyId: string }, entryFile: string, content: string) {
|
||||
const service = agentInstructionRevisionService(db);
|
||||
const target = { companyId: agent.companyId, agentId: agent.id };
|
||||
const baseline = await service.readCurrent(target, instructionOperator);
|
||||
await service.commit({ ...target, entryFile, content, baseRevisionId: baseline?.revision.id ?? null, source: "board" }, instructionOperator);
|
||||
const refreshed = await agentService(db).getById(agent.id);
|
||||
return { adapterConfig: refreshed!.adapterConfig };
|
||||
}
|
||||
|
||||
|
||||
beforeAll(async () => {
|
||||
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-built-in-agents-");
|
||||
@@ -553,7 +567,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
capabilities: "Custom purpose",
|
||||
});
|
||||
|
||||
const reset = await builtIns.reset(companyId, "briefs");
|
||||
const reset = await builtIns.reset(companyId, "briefs", {}, instructionOperator);
|
||||
|
||||
expect(reset).toMatchObject({
|
||||
status: "ready",
|
||||
@@ -795,13 +809,111 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
expect(approvalRows).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("automatically upgrades untouched stock instructions while preserving personal files", async () => {
|
||||
const companyId = await seedCompany({ requireApproval: false });
|
||||
const svc = builtInAgentService(db);
|
||||
const created = await svc.ensure(companyId, "reflection-coach");
|
||||
const agent = created.agent!;
|
||||
const oldFiles = { "AGENTS.md": "# Previous stock instructions\n", "obsolete.txt": "old stock support" };
|
||||
await writeInstructionEntry(agent, "AGENTS.md", oldFiles["AGENTS.md"]);
|
||||
await agentInstructionsService(db).writeFile(agent, "obsolete.txt", oldFiles["obsolete.txt"]);
|
||||
await agentInstructionsService(db).writeFile(agent, "personal.txt", "keep my notes");
|
||||
await db.update(builtInManagedResources).set({ stockHash: stockHash(oldFiles), stockVersion: "previous",
|
||||
defaultsJson: { entryFile: "AGENTS.md", files: Object.keys(oldFiles) },
|
||||
}).where(and(eq(builtInManagedResources.companyId, companyId), eq(builtInManagedResources.resourceKind, "instructions")));
|
||||
const updated = await svc.ensure(companyId, "reflection-coach");
|
||||
expect(updated.resources.find(resource => resource.resourceKind === "instructions")).toMatchObject({ stockStatus: "stock_current" });
|
||||
expect((await agentInstructionsService().readFile(updated.agent!, "AGENTS.md")).content).toContain("You are Reflection Coach");
|
||||
expect((await agentInstructionsService().readFile(updated.agent!, "personal.txt")).content).toBe("keep my notes");
|
||||
await expect(agentInstructionsService().readFile(updated.agent!, "obsolete.txt")).rejects.toMatchObject({ status: 404 });
|
||||
const [event] = await db.select().from(activityLog).where(and(eq(activityLog.companyId, companyId), eq(activityLog.actorId, "built-in-reconcile")));
|
||||
expect(event).toMatchObject({ actorType: "system", action: "agent.files_updated" });
|
||||
});
|
||||
|
||||
it.each(["file", "database"])("retries a stock update after a %s failure without overwriting intervening edits", async (failure) => {
|
||||
const companyId = await seedCompany({ requireApproval: false });
|
||||
const svc = builtInAgentService(db);
|
||||
const created = await svc.ensure(companyId, "reflection-coach");
|
||||
const agent = created.agent!;
|
||||
const oldFiles = { "AGENTS.md": "# Old stock\n", "obsolete.txt": "old supporting file" };
|
||||
await writeInstructionEntry(agent, "AGENTS.md", oldFiles["AGENTS.md"]);
|
||||
await agentInstructionsService(db).writeFile(agent, "obsolete.txt", oldFiles["obsolete.txt"]);
|
||||
await db.update(builtInManagedResources).set({ stockHash: stockHash(oldFiles), stockVersion: "old",
|
||||
defaultsJson: { entryFile: "AGENTS.md", files: Object.keys(oldFiles) },
|
||||
}).where(and(eq(builtInManagedResources.companyId, companyId), eq(builtInManagedResources.resourceKind, "instructions")));
|
||||
const trigger = `stock_failure_${companyId.replaceAll("-", "")}`;
|
||||
const remove = fs.rm.bind(fs);
|
||||
const fault = failure === "file" ? vi.spyOn(fs, "rm").mockImplementation(async (file, options) => {
|
||||
if (String(file).endsWith("/obsolete.txt")) throw new Error("injected stock file failure");
|
||||
return remove(file, options);
|
||||
}) : null;
|
||||
if (failure === "database") {
|
||||
await db.execute(sql.raw(`CREATE FUNCTION ${trigger}() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
|
||||
IF NEW.company_id = '${companyId}' AND NEW.resource_kind = 'instructions' AND NEW.stock_hash <> OLD.stock_hash THEN
|
||||
RAISE EXCEPTION 'injected stock binding failure'; END IF; RETURN NEW; END $$`));
|
||||
await db.execute(sql.raw(`CREATE TRIGGER ${trigger} BEFORE UPDATE ON built_in_managed_resources FOR EACH ROW EXECUTE FUNCTION ${trigger}()`));
|
||||
}
|
||||
try { await expect(svc.ensure(companyId, "reflection-coach")).rejects.toThrow(); }
|
||||
finally {
|
||||
fault?.mockRestore();
|
||||
if (failure === "database") {
|
||||
await db.execute(sql.raw(`DROP TRIGGER ${trigger} ON built_in_managed_resources`));
|
||||
await db.execute(sql.raw(`DROP FUNCTION ${trigger}()`));
|
||||
}
|
||||
}
|
||||
const [pending] = await db.select().from(builtInManagedResources).where(and(eq(builtInManagedResources.companyId, companyId), eq(builtInManagedResources.resourceKind, "instructions")));
|
||||
expect(pending.defaultsJson.pendingInstructionsUpdate).toBeTruthy();
|
||||
expect(pending.stockHash).toBe(stockHash(oldFiles));
|
||||
const partial = (await agentInstructionsService().readFile(agent, "AGENTS.md")).content;
|
||||
expect(partial).toContain("You are Reflection Coach");
|
||||
// A real operator edit after the failed attempt must stop the retry.
|
||||
await writeInstructionEntry(agent, "AGENTS.md", "operator edit after failure");
|
||||
await svc.ensure(companyId, "reflection-coach");
|
||||
expect((await agentInstructionsService().readFile(agent, "AGENTS.md")).content).toBe("operator edit after failure");
|
||||
await writeInstructionEntry(agent, "AGENTS.md", partial);
|
||||
const retried = await svc.ensure(companyId, "reflection-coach");
|
||||
expect(retried.resources.find(resource => resource.resourceKind === "instructions")).toMatchObject({ stockStatus: "stock_current" });
|
||||
await expect(agentInstructionsService().readFile(agent, "obsolete.txt")).rejects.toMatchObject({ status: 404 });
|
||||
const [complete] = await db.select().from(builtInManagedResources).where(eq(builtInManagedResources.id, pending.id));
|
||||
expect(complete.defaultsJson.pendingInstructionsUpdate).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([false, true])("supersedes an interrupted stock version, including rollback=%s", async (rollback) => {
|
||||
const companyId = await seedCompany({ requireApproval: false });
|
||||
const svc = builtInAgentService(db);
|
||||
const created = await svc.ensure(companyId, "reflection-coach");
|
||||
const agent = created.agent!;
|
||||
const currentStock = (await agentInstructionsService().readFile(agent, "AGENTS.md")).content;
|
||||
const oldFiles = { "AGENTS.md": rollback ? currentStock : "# Original stock" };
|
||||
const interruptedFiles = { "AGENTS.md": "# Intermediate stock", "intermediate-only.txt": "intermediate support" };
|
||||
await writeInstructionEntry(agent, "AGENTS.md", interruptedFiles["AGENTS.md"]);
|
||||
await agentInstructionsService(db).writeFile(agent, "intermediate-only.txt", interruptedFiles["intermediate-only.txt"]);
|
||||
await agentInstructionsService(db).writeFile(agent, "personal.txt", "personal notes");
|
||||
await db.update(builtInManagedResources).set({ stockHash: stockHash(oldFiles), stockVersion: "old",
|
||||
defaultsJson: { entryFile: "AGENTS.md", files: Object.keys(oldFiles), pendingInstructionsUpdate: {
|
||||
stockHash: stockHash(interruptedFiles),
|
||||
baseHashes: { "AGENTS.md": fileHash(Buffer.from(oldFiles["AGENTS.md"])), "intermediate-only.txt": null },
|
||||
nextHashes: Object.fromEntries(Object.entries(interruptedFiles).map(([file, text]) => [file, fileHash(Buffer.from(text))])),
|
||||
} },
|
||||
}).where(and(eq(builtInManagedResources.companyId, companyId), eq(builtInManagedResources.resourceKind, "instructions")));
|
||||
await writeInstructionEntry(agent, "AGENTS.md", "intervening operator edit");
|
||||
await svc.ensure(companyId, "reflection-coach");
|
||||
expect((await agentInstructionsService().readFile(agent, "AGENTS.md")).content).toBe("intervening operator edit");
|
||||
await writeInstructionEntry(agent, "AGENTS.md", interruptedFiles["AGENTS.md"]);
|
||||
const updated = await svc.ensure(companyId, "reflection-coach");
|
||||
expect(updated.resources.find(resource => resource.resourceKind === "instructions")).toMatchObject({ stockStatus: "stock_current" });
|
||||
expect((await agentInstructionsService().readFile(agent, "AGENTS.md")).content).toBe(currentStock);
|
||||
await expect(agentInstructionsService().readFile(agent, "intermediate-only.txt")).rejects.toMatchObject({ status: 404 });
|
||||
expect((await agentInstructionsService().readFile(agent, "personal.txt")).content).toBe("personal notes");
|
||||
});
|
||||
|
||||
it("preserves Reflection Coach instruction drift on reconcile and restores it on reset", async () => {
|
||||
const companyId = await seedCompany();
|
||||
const builtIns = builtInAgentService(db);
|
||||
const created = await builtIns.ensure(companyId, "reflection-coach");
|
||||
const instructions = agentInstructionsService();
|
||||
|
||||
await instructions.writeFile(created.agent!, "AGENTS.md", "# Custom Reflection Coach\n\nOperator edit.\n");
|
||||
await writeInstructionEntry(created.agent!, "AGENTS.md", "# Custom Reflection Coach\n\nOperator edit.\n");
|
||||
|
||||
const reconciled = await builtIns.ensure(companyId, "reflection-coach");
|
||||
const drift = reconciled.resources.find((resource) => resource.resourceKind === "instructions");
|
||||
@@ -815,7 +927,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
content: "# Custom Reflection Coach\n\nOperator edit.\n",
|
||||
});
|
||||
|
||||
const reset = await builtIns.reset(companyId, "reflection-coach");
|
||||
const reset = await builtIns.reset(companyId, "reflection-coach", {}, instructionOperator);
|
||||
expect(reset.resources.find((resource) => resource.resourceKind === "instructions")).toMatchObject({
|
||||
stockStatus: "stock_current",
|
||||
resetAvailable: false,
|
||||
@@ -823,6 +935,12 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
const resetFile = await instructions.readFile(reset.agent!, "AGENTS.md");
|
||||
expect(resetFile.content).toContain("Reflection Coach");
|
||||
expect(resetFile.content).not.toContain("Operator edit.");
|
||||
const revisions = agentInstructionRevisionService(db);
|
||||
const target = { companyId, agentId: created.agent!.id, entryFile: "AGENTS.md" };
|
||||
const history = await revisions.history(target, instructionOperator);
|
||||
expect(history.revisions).toHaveLength(0);
|
||||
const current = await revisions.readCurrent(target, instructionOperator);
|
||||
expect(current?.content).toBe(resetFile.content);
|
||||
});
|
||||
|
||||
it("blocks deleting a built-in agent", async () => {
|
||||
@@ -1270,7 +1388,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
const created = await builtIns.ensure(companyId, "summarizer");
|
||||
const instructions = agentInstructionsService();
|
||||
|
||||
await instructions.writeFile(created.agent!, "AGENTS.md", "# Custom Summarizer\n\nOperator edit.\n");
|
||||
await writeInstructionEntry(created.agent!, "AGENTS.md", "# Custom Summarizer\n\nOperator edit.\n");
|
||||
|
||||
const reconciled = await builtIns.ensure(companyId, "summarizer");
|
||||
expect(reconciled.resources.find((resource) => resource.resourceKind === "instructions")).toMatchObject({
|
||||
@@ -1279,7 +1397,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
changedFiles: ["AGENTS.md"],
|
||||
});
|
||||
|
||||
const reset = await builtIns.reset(companyId, "summarizer");
|
||||
const reset = await builtIns.reset(companyId, "summarizer", {}, instructionOperator);
|
||||
expect(reset.resources.find((resource) => resource.resourceKind === "instructions")).toMatchObject({
|
||||
stockStatus: "stock_current",
|
||||
resetAvailable: false,
|
||||
@@ -1419,7 +1537,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
const coach = created.agent!;
|
||||
const instructionsSvc = agentInstructionsService();
|
||||
const originalInstructions = "# Target Coder\n\nWork from the assigned issue.\n";
|
||||
const prepared = await instructionsSvc.writeFile(target, "AGENTS.md", originalInstructions);
|
||||
const prepared = await writeInstructionEntry(target, "AGENTS.md", originalInstructions);
|
||||
let persistedTarget = (await agentsSvc.update(target.id, { adapterConfig: prepared.adapterConfig }))!;
|
||||
|
||||
const interactionsSvc = issueThreadInteractionService(db);
|
||||
@@ -1431,7 +1549,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
if (interaction?.kind !== "request_confirmation" || interaction.status !== "accepted") {
|
||||
return false;
|
||||
}
|
||||
const written = await instructionsSvc.writeFile(persistedTarget, "AGENTS.md", input.nextInstructions);
|
||||
const written = await writeInstructionEntry(persistedTarget, "AGENTS.md", input.nextInstructions);
|
||||
persistedTarget = (await agentsSvc.update(persistedTarget.id, { adapterConfig: written.adapterConfig }))!;
|
||||
return true;
|
||||
};
|
||||
@@ -1568,7 +1686,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
const agent = created.agent!;
|
||||
|
||||
const instructionsSvc = agentInstructionsService();
|
||||
await instructionsSvc.writeFile(agent, "AGENTS.md", "# Custom Reflection Coach\n\nDo not overwrite me.\n");
|
||||
await writeInstructionEntry(agent, "AGENTS.md", "# Custom Reflection Coach\n\nDo not overwrite me.\n");
|
||||
await db
|
||||
.update(companySkills)
|
||||
.set({ markdown: "---\nname: reflection-coach\n---\n\n# Custom skill\n" })
|
||||
@@ -1597,7 +1715,7 @@ describeEmbeddedPostgres("built-in agents", () => {
|
||||
|
||||
const reset = await builtInAgentService(db).reset(companyId, "reflection-coach", {
|
||||
resources: ["instructions", "routine"],
|
||||
});
|
||||
}, instructionOperator);
|
||||
expect(reset.resources.find((resource) => resource.resourceKind === "instructions")).toMatchObject({
|
||||
stockStatus: "stock_current",
|
||||
resetAvailable: false,
|
||||
|
||||
@@ -264,6 +264,12 @@ describeEmbeddedPostgres("heartbeat list", () => {
|
||||
summary: "completed",
|
||||
stdout: oversizedStdout,
|
||||
nestedHuge: { payload: oversizedNestedPayload },
|
||||
instructionSave: {
|
||||
state: "unavailable", contract: "agent_files", entryFile: "AGENTS.md",
|
||||
errorCode: "AGENT_FILES_LIMIT_EXCEEDED",
|
||||
storageWarning: "Agent storage is full. Runs can continue.".repeat(50),
|
||||
privateSyncMetadata: oversizedNestedPayload,
|
||||
},
|
||||
workspaceRestoreFailure: "restore_unsafe_archive",
|
||||
finalResponseRecorded: true,
|
||||
executionBeforeRestore: { errorCode: "model_error", exitCode: 2, timedOut: false },
|
||||
@@ -278,6 +284,11 @@ describeEmbeddedPostgres("heartbeat list", () => {
|
||||
truncated: true,
|
||||
truncationReason: "oversized_result_json",
|
||||
stdoutTruncated: true,
|
||||
instructionSave: {
|
||||
state: "unavailable", contract: "agent_files", entryFile: "AGENTS.md",
|
||||
errorCode: "AGENT_FILES_LIMIT_EXCEEDED",
|
||||
storageWarning: "Agent storage is full. Runs can continue.".repeat(50).slice(0, 1024),
|
||||
},
|
||||
workspaceRestoreFailure: "restore_unsafe_archive",
|
||||
finalResponseRecorded: true,
|
||||
executionBeforeRestore: { errorCode: "model_error", exitCode: 2, timedOut: false },
|
||||
@@ -285,6 +296,7 @@ describeEmbeddedPostgres("heartbeat list", () => {
|
||||
expect(typeof result?.stdout).toBe("string");
|
||||
expect((result?.stdout as string).length).toBeLessThan(oversizedStdout.length);
|
||||
expect(result).not.toHaveProperty("nestedHuge");
|
||||
expect(result?.instructionSave).not.toHaveProperty("privateSyncMetadata");
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
|
||||
import {
|
||||
activityLog,
|
||||
agentConfigRevisions,
|
||||
agentInstructionRevisions,
|
||||
agentInstructionHeads,
|
||||
agents,
|
||||
approvals,
|
||||
companies,
|
||||
@@ -23,6 +25,9 @@ import {
|
||||
} from "./helpers/embedded-postgres.js";
|
||||
import { buildHostServices } from "../services/plugin-host-services.js";
|
||||
import { agentService } from "../services/agents.js";
|
||||
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
||||
import { agentInstructionsService } from "../services/agent-instructions.js";
|
||||
import { pluginRegistryService } from "../services/plugin-registry.js";
|
||||
|
||||
const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport();
|
||||
const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
|
||||
@@ -312,7 +317,7 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
|
||||
it("materializes declared managed agent instructions with local folder paths", async () => {
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
const previousInstance = process.env.PAPERCLIP_INSTANCE_ID;
|
||||
const tempHome = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-managed-agent-home-"));
|
||||
const tempHome = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-managed-agent-home-")));
|
||||
const wikiRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-managed-agent-wiki-")));
|
||||
process.env.PAPERCLIP_HOME = tempHome;
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "test";
|
||||
@@ -369,6 +374,39 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
|
||||
expect(content).toContain("You are the LLM Wiki Maintainer.");
|
||||
expect(content).toContain(`Wiki root: \`${wikiRoot}\``);
|
||||
expect(content).toContain(`Wiki schema: \`${path.join(wikiRoot, "AGENTS.md")}\``);
|
||||
|
||||
// A managed plugin reset must preserve the previous entry in canonical
|
||||
// history instead of deleting a shared bundle or bypassing its write guard.
|
||||
const edited = "# User-customized wiki instructions\n";
|
||||
await fs.writeFile(instructionsFilePath as string, edited);
|
||||
const reset = await services.agents.managedReset({ companyId, agentKey: "wiki-maintainer" });
|
||||
expect(reset.status).toBe("reset");
|
||||
expect(await fs.readFile(instructionsFilePath as string, "utf8")).toBe(content);
|
||||
const history = await db.select().from(agentInstructionRevisions)
|
||||
.where(eq(agentInstructionRevisions.agentId, created.agentId!));
|
||||
expect(history).toHaveLength(0);
|
||||
expect(await db.select().from(agentInstructionHeads)
|
||||
.where(eq(agentInstructionHeads.agentId, created.agentId!))).toHaveLength(0);
|
||||
const repeated = await services.agents.managedReset({ companyId, agentKey: "wiki-maintainer" });
|
||||
expect(repeated.status).toBe("reset");
|
||||
expect(await db.select().from(agentInstructionRevisions)
|
||||
.where(eq(agentInstructionRevisions.agentId, created.agentId!))).toHaveLength(0);
|
||||
const audit = await db.select().from(activityLog).where(eq(activityLog.action, "agent.files_updated"));
|
||||
expect(audit).toHaveLength(1);
|
||||
expect(audit.every((row) => row.actorType === "plugin" && row.actorId === pluginId)).toBe(true);
|
||||
const bundles = agentInstructionsService(db);
|
||||
await bundles.writeFile(repeated.agent!, "CUSTOM.md", "# Alternate configured entry\n");
|
||||
const switched = await bundles.updateBundle(repeated.agent!, { entryFile: "CUSTOM.md" });
|
||||
await agentService(db).update(created.agentId!, { adapterConfig: switched.adapterConfig });
|
||||
const resetEntry = await services.agents.managedReset({ companyId, agentKey: "wiki-maintainer" });
|
||||
expect(resetEntry.agent?.adapterConfig.instructionsEntryFile).toBe("AGENTS.md");
|
||||
expect(resetEntry.defaultDrift).toBeNull();
|
||||
expect(await fs.readFile(instructionsFilePath as string, "utf8")).toBe(content);
|
||||
const preserved = await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, created.agentId!));
|
||||
expect(preserved).toHaveLength(0);
|
||||
expect(await fs.readFile(path.join(path.dirname(instructionsFilePath as string), "CUSTOM.md"), "utf8")).toBe("# Alternate configured entry\n");
|
||||
|
||||
|
||||
} finally {
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME;
|
||||
else process.env.PAPERCLIP_HOME = previousHome;
|
||||
@@ -379,6 +417,60 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("fences plugin instruction reset by exact ownership, current capability and canonical CAS", async () => {
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
const tempHome = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "plugin-reset-cas-")));
|
||||
process.env.PAPERCLIP_HOME = tempHome;
|
||||
try {
|
||||
const pluginManifest = manifest();
|
||||
pluginManifest.agents![0]!.instructions = { content: "# Default\n" };
|
||||
const { companyId, pluginId, services } = await seedCompanyAndPlugin({ manifest: pluginManifest });
|
||||
const created = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
|
||||
const target = { companyId, agentId: created.agentId! };
|
||||
const actor = { type: "plugin" as const, pluginId, pluginKey: pluginManifest.id, agentKey: "wiki-maintainer" };
|
||||
const revisions = agentInstructionRevisionService(db);
|
||||
const baselineRead = await revisions.readForPluginReset(target, actor);
|
||||
const baseline = baselineRead.snapshot!;
|
||||
const input = { ...target, entryFile: "AGENTS.md", baseRevisionId: baseline.revision.id,
|
||||
configuredEntryFile: baselineRead.configuredEntryFile, content: "# Reset\n" };
|
||||
await expect(revisions.commitPluginReset(input, { ...actor, pluginId: randomUUID() })).rejects.toMatchObject({ status: 403 });
|
||||
await expect(revisions.commitPluginReset({ ...input, companyId: randomUUID() }, actor)).rejects.toMatchObject({ status: 404 });
|
||||
await expect(revisions.commitPluginReset(input, { ...actor, agentKey: "foreign-agent" })).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(plugins).set({ manifestJson: { ...pluginManifest, capabilities: [] } }).where(eq(plugins.id, pluginId));
|
||||
await expect(revisions.commitPluginReset(input, actor)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(plugins).set({ manifestJson: pluginManifest }).where(eq(plugins.id, pluginId));
|
||||
const originalMetadata = created.agent!.metadata;
|
||||
await db.update(agents).set({ metadata: {} }).where(eq(agents.id, target.agentId));
|
||||
await expect(revisions.commitPluginReset(input, actor)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(agents).set({ metadata: originalMetadata }).where(eq(agents.id, target.agentId));
|
||||
const [binding] = await db.select().from(pluginManagedResources).where(eq(pluginManagedResources.resourceId, target.agentId));
|
||||
await db.update(pluginManagedResources).set({ resourceId: randomUUID() }).where(eq(pluginManagedResources.id, binding.id));
|
||||
await expect(revisions.commitPluginReset(input, actor)).rejects.toMatchObject({ status: 403 });
|
||||
await db.update(pluginManagedResources).set({ resourceId: target.agentId }).where(eq(pluginManagedResources.id, binding.id));
|
||||
await expect(revisions.commitPluginReset({ ...input, entryFile: "OTHER.md" }, actor)).rejects.toMatchObject({ status: 403 });
|
||||
const bundles = agentInstructionsService(db);
|
||||
await bundles.writeFile(created.agent!, "OTHER.md", "# Other entry\n");
|
||||
const switched = await bundles.updateBundle(created.agent!, { entryFile: "OTHER.md" });
|
||||
await agentService(db).update(target.agentId, { adapterConfig: switched.adapterConfig });
|
||||
await expect(revisions.commitPluginReset(input, actor)).rejects.toMatchObject({ status: 409, details: { code: "INSTRUCTION_ENTRY_CHANGED" } });
|
||||
await agentService(db).update(target.agentId, { adapterConfig: created.agent!.adapterConfig });
|
||||
const results = await Promise.allSettled([
|
||||
revisions.commitPluginReset(input, actor),
|
||||
revisions.commitPluginReset({ ...input, content: "# Concurrent reset\n" }, actor),
|
||||
]);
|
||||
expect(results.filter((result) => result.status === "fulfilled")).toHaveLength(1);
|
||||
const loser = results.find((result) => result.status === "rejected") as PromiseRejectedResult;
|
||||
expect(loser.reason).toMatchObject({ status: 409, details: { code: "INSTRUCTION_REVISION_CONFLICT" } });
|
||||
const winner = results.find((result) => result.status === "fulfilled") as PromiseFulfilledResult<Awaited<ReturnType<typeof revisions.commitPluginReset>>>;
|
||||
expect(await fs.readFile(created.agent!.adapterConfig.instructionsFilePath as string, "utf8")).toBe(winner.value.content);
|
||||
const history = await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, target.agentId));
|
||||
expect(history).toHaveLength(0);
|
||||
} finally {
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
||||
await fs.rm(tempHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("repairs a missing binding by relinking a same-company managed agent marker", async () => {
|
||||
const { companyId, pluginId, pluginManifest, services } = await seedCompanyAndPlugin();
|
||||
const agentId = randomUUID();
|
||||
@@ -410,6 +502,76 @@ describeEmbeddedPostgres("plugin-managed agents", () => {
|
||||
expect(binding?.data).toMatchObject({ agentId });
|
||||
});
|
||||
|
||||
it("preserves current-file authority when relinking after a hard uninstall and reinstall", async () => {
|
||||
const previousHome = process.env.PAPERCLIP_HOME;
|
||||
const tempHome = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "plugin-reinstall-reset-")));
|
||||
process.env.PAPERCLIP_HOME = tempHome;
|
||||
try {
|
||||
const pluginManifest = manifest();
|
||||
pluginManifest.agents![0]!.instructions = { content: "# Original stock\n" };
|
||||
const { companyId, pluginId, services } = await seedCompanyAndPlugin({ manifest: pluginManifest });
|
||||
const created = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
|
||||
const target = { companyId, agentId: created.agentId! };
|
||||
const revisions = agentInstructionRevisionService(db);
|
||||
const original = await revisions.readForPluginReset(target, {
|
||||
type: "plugin", pluginId, pluginKey: pluginManifest.id, agentKey: "wiki-maintainer",
|
||||
});
|
||||
const registry = pluginRegistryService(db);
|
||||
await registry.uninstall(pluginId, true);
|
||||
expect(await db.select().from(pluginManagedResources)).toHaveLength(0);
|
||||
expect(await db.select().from(pluginEntities)).toHaveLength(0);
|
||||
const nextManifest = structuredClone(pluginManifest);
|
||||
nextManifest.agents![0]!.instructions = { content: "# Reinstalled stock\n" };
|
||||
const installed = await registry.install({ packageName: "@paperclipai/plugin-managed-agents-test" }, nextManifest);
|
||||
expect(installed!.id).not.toBe(pluginId);
|
||||
await registry.updateStatus(installed!.id, { status: "ready" });
|
||||
const reinstalledServices = buildHostServices(db, installed!.id, nextManifest.id, createEventBusStub(), undefined, {
|
||||
manifest: nextManifest,
|
||||
});
|
||||
const relinked = await reinstalledServices.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
|
||||
expect(relinked.status).toBe("relinked");
|
||||
expect(relinked.agentId).toBe(created.agentId);
|
||||
const reset = await reinstalledServices.agents.managedReset({ companyId, agentKey: "wiki-maintainer" });
|
||||
expect(reset.agentId).toBe(created.agentId);
|
||||
expect(reset.agent!.metadata).toMatchObject({ paperclipManagedResource: { pluginId: installed!.id }, pluginManagedAgent: { pluginId: installed!.id } });
|
||||
expect(await fs.readFile(reset.agent!.adapterConfig.instructionsFilePath as string, "utf8")).toBe("# Reinstalled stock\n");
|
||||
const history = await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, created.agentId!));
|
||||
expect(history).toHaveLength(0);
|
||||
} finally {
|
||||
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
||||
await fs.rm(tempHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it.each(["not-ready", "capability-removed", "declaration-removed", "other-plugin-owner"])(
|
||||
"does not relink a managed agent when its authority is %s", async (reason) => {
|
||||
const { companyId, pluginId, pluginManifest, services } = await seedCompanyAndPlugin();
|
||||
const created = await services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" });
|
||||
await db.delete(pluginEntities);
|
||||
await db.delete(pluginManagedResources);
|
||||
if (reason === "not-ready") {
|
||||
await db.update(plugins).set({ status: "disabled" }).where(eq(plugins.id, pluginId));
|
||||
} else if (reason === "capability-removed") {
|
||||
await db.update(plugins).set({ manifestJson: { ...pluginManifest, capabilities: [] } }).where(eq(plugins.id, pluginId));
|
||||
} else if (reason === "declaration-removed") {
|
||||
await db.update(plugins).set({ manifestJson: { ...pluginManifest, agents: [] } }).where(eq(plugins.id, pluginId));
|
||||
} else {
|
||||
const otherId = randomUUID();
|
||||
await db.insert(plugins).values({ id: otherId, pluginKey: "paperclip.other-owner", packageName: "other",
|
||||
version: "0.1.0", apiVersion: 1, categories: [], manifestJson: { ...pluginManifest, id: "paperclip.other-owner" }, status: "ready", installOrder: 2 });
|
||||
await db.update(agents).set({ metadata: { ...created.agent!.metadata,
|
||||
paperclipManagedResource: { pluginId: otherId, pluginKey: pluginManifest.id, resourceKind: "agent", resourceKey: "wiki-maintainer" },
|
||||
} }).where(eq(agents.id, created.agentId!));
|
||||
}
|
||||
const [before] = await db.select().from(agents).where(eq(agents.id, created.agentId!));
|
||||
await expect(services.agents.managedReconcile({ companyId, agentKey: "wiki-maintainer" })).rejects.toMatchObject({ status: 403 });
|
||||
expect(await db.select().from(pluginEntities)).toHaveLength(0);
|
||||
expect(await db.select().from(pluginManagedResources)).toHaveLength(0);
|
||||
const [after] = await db.select().from(agents).where(eq(agents.id, created.agentId!));
|
||||
expect(after.metadata).toEqual(before.metadata);
|
||||
},
|
||||
);
|
||||
|
||||
it("respects board approval policy for new managed agents", async () => {
|
||||
const { companyId, services } = await seedCompanyAndPlugin({ requireApproval: true });
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
writeEnvFileAtomicallyIfChanged,
|
||||
} from "@paperclipai/shared/env-file";
|
||||
import { resourceStatus, stockHash } from "../services/managed-resource-drift.js";
|
||||
import { agentInstructionsService } from "../services/agent-instructions.js";
|
||||
import { agentInstructionsService, resolveManagedInstructionsRoot } from "../services/agent-instructions.js";
|
||||
|
||||
/**
|
||||
* Cross-cutting setup/sync rerun survival test.
|
||||
@@ -23,7 +23,7 @@ import { agentInstructionsService } from "../services/agent-instructions.js";
|
||||
* - .env -> updateEnvFileContents + writeEnvFileAtomicallyIfChanged
|
||||
* - managed sandbox env -> resourceStatus/stockHash drift gate (the `shouldWrite`
|
||||
* classifier the boot reconciler and built-in sync share)
|
||||
* - managed instructions -> agentInstructionsService materialize + the drift gate that
|
||||
* - managed instructions -> agentInstructionsService export + the drift gate that
|
||||
* makes built-in/plugin/portability rebuilds skip operator edits
|
||||
*
|
||||
* The DB-backed end-to-end variants of the sandbox-row, skills-assignment, and
|
||||
@@ -31,7 +31,7 @@ import { agentInstructionsService } from "../services/agent-instructions.js";
|
||||
* server/src/__tests__/company-skills-service.test.ts (skills add/remove/replace)
|
||||
* server/src/services/managed-environments.test.ts (sandbox row boot reconcile)
|
||||
* server/src/__tests__/environment-service.test.ts (sandbox skip + stock update)
|
||||
* server/src/__tests__/agent-instructions-service.test.ts (managed instruction drift)
|
||||
* server/src/__tests__/agent-instruction-revisions.test.ts (guarded bundle materialization)
|
||||
*/
|
||||
|
||||
const cleanupDirs = new Set<string>();
|
||||
@@ -147,7 +147,7 @@ describe("setup/sync rerun survival — cross-cutting", () => {
|
||||
).toBe("stock_current");
|
||||
});
|
||||
|
||||
it("keeps operator edits and additions in a managed instructions tree across a re-materialize", async () => {
|
||||
it("keeps operator edits and additions when managed instructions reconciliation detects drift", async () => {
|
||||
const home = await tmp("pap16587-instr-home-");
|
||||
process.env.PAPERCLIP_HOME = home;
|
||||
process.env.PAPERCLIP_INSTANCE_ID = "test-instance";
|
||||
@@ -156,18 +156,25 @@ describe("setup/sync rerun survival — cross-cutting", () => {
|
||||
const agent = { id: "agent-1", companyId: "company-1", name: "Agent 1", adapterConfig: {} };
|
||||
const stockFiles = { "AGENTS.md": "# stock\n", "docs/TOOLS.md": "## stock tools\n" };
|
||||
|
||||
const first = await svc.materializeManagedBundle(agent, stockFiles, { entryFile: "AGENTS.md" });
|
||||
const root = first.bundle.managedRootPath!;
|
||||
// Initial files are fixture setup. Bundle materialization now requires a
|
||||
// real database so that it cannot bypass a canonical instruction revision.
|
||||
const root = resolveManagedInstructionsRoot(agent);
|
||||
for (const [name, content] of Object.entries(stockFiles)) {
|
||||
await fs.mkdir(path.dirname(path.join(root, name)), { recursive: true });
|
||||
await fs.writeFile(path.join(root, name), content, "utf8");
|
||||
}
|
||||
const managedAgent = { ...agent, adapterConfig: {
|
||||
instructionsBundleMode: "managed", instructionsRootPath: root,
|
||||
instructionsEntryFile: "AGENTS.md", instructionsFilePath: path.join(root, "AGENTS.md"),
|
||||
} };
|
||||
|
||||
// Operator hand-edits a managed file and adds a brand-new operator-only file.
|
||||
await fs.writeFile(path.join(root, "AGENTS.md"), "# stock\n\noperator note\n", "utf8");
|
||||
await fs.writeFile(path.join(root, "OPERATOR.md"), "operator-added\n", "utf8");
|
||||
|
||||
// The drift gate the built-in/plugin/portability rebuilds share: classify the tree.
|
||||
const currentFiles = {
|
||||
"AGENTS.md": await fs.readFile(path.join(root, "AGENTS.md"), "utf8"),
|
||||
"docs/TOOLS.md": await fs.readFile(path.join(root, "docs", "TOOLS.md"), "utf8"),
|
||||
};
|
||||
const currentFiles = (await svc.exportFiles(managedAgent)).files;
|
||||
expect(currentFiles["OPERATOR.md"]).toBe("operator-added\n");
|
||||
const status = resourceStatus({
|
||||
resourceId: agent.id,
|
||||
currentHash: stockHash(currentFiles),
|
||||
|
||||
Reference in new issue
Block a user