mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-01 06:42:06 +01:00
## Thinking Path > - Paperclip helps people manage AI agents and inspect their work. > - Agent startup can reuse a lease, workspace, Runner, process, or session. > - A session ID can remain the same when other resources are new. > - The old cold/warm label did not show these separate decisions. > - This pull request records closed reuse receipts and derives labels from them. > - Reports now show partial reuse and missing evidence. ## Linked Issues or Issue Description Refs #11685. That issue tracks a specific ACPX fingerprint repair. This change records reuse evidence across startup resources. It does not repeat that repair. **What existing behavior does this improve?** Startup labels in the operator trace and Product E2E reports. **Current behavior** A cached runtime or a continuous session can suggest a warm startup even when workspace staging or provider launch work occurs. **Proposed behavior** Record each layer's reuse decision and a closed reason. Record observed provider launch counts. Use `warm`, `cold`, `partial_reuse`, or `unknown` from those receipts. Keep old runs unknown when they have no receipts. ## What Changed - Add local run-log receipts for the lease, workspace, Runner, provider process, and provider session. - Count physical ACPX launches, including respawns. Preserve the reason for a new process. - Reuse native workspace adoption and session lifecycle evidence. Keep native and bridged remote provider-process reuse and launch counts unknown where physical evidence is absent. - Show the per-run summary in retained results and the dashboard. Keep missing legacy values explicit. - Set the legacy trace boolean only for fully evidenced cold or warm startup. Keep the operator OTLP gate. Add no first-party Telemetry. - Test full reuse, workspace invalidation, two direct provider launches with session continuity, and report generation. - Start the final diagnostic write without waiting for persistence. Keep lease cleanup independent of a stalled event sink. - Keep remote provider evidence unknown after runtime setup fails or the host relay starts twice. - Align a stale Pi support-test expectation with current master profile 28 and its suite fingerprint. Keep the qualification rules unchanged. ## Verification - Passed: all 319 runtime, startup-timing, reuse-summary, and native workspace-history tests. Disposable local Git tests used the native Git binary. - Passed on the current commit: all 2,768 Runner E2E support tests across 128 files. This includes report and history tests for generated HTML and normalized JSON. - Passed: `pnpm --filter @paperclipai/adapter-utils typecheck`. - Passed on `df60f8dbdbfcb6d80c84cd3bf563f8d58b2f9f03`: all PR CI gates, including repository typecheck and build, all test shards, and browser tests. Both automated reviews are 5/5. GitHub reports 55 successful checks, one neutral review, and two skipped Storybook checks. - The first server shard run failed because an unchanged workspace-runtime fixture did not accept health connections within 10 seconds. Its isolated local test and the single failed-jobs rerun both pass. This establishes recovery; the cause of the first timeout remains unknown. - Passed in the hosted source run on this exact commit: recursive typecheck, token gates, the large Runner E2E typecheck, Runner E2E unit tests, and build. The retained `source.txt` matches this PR head. - The extra unsharded `pnpm test:run` reached its 60-minute limit (exit 124). It has no complete verdict. The broad workflow therefore reports failure. No assertion-failure marker appears in the retained partial log. Full-suite acceptance uses the passing canonical PR CI partitions. A read-only inventory check found no gaps across 1,023 general server files, 161 serialized suites, and 20 workspace projects. The separate chat/native Runner lanes cover the excluded server files. No tests or timeouts were weakened. The local environment has 4 GiB of memory. Use CI for the large Runner E2E typecheck. - The initial report tests failed because the harness could not resolve package imports from the repository root. Relative source imports fixed that failure. - The first broad local run had timeouts from the environment Git bridge. Native Git resolves the ancestry timeout and all runtime tests pass. The added report fixture lacked its required screenshot; the corrected report tests pass. A stale master assertion expected Pi profile 27, while the generated profile is 28. Updated its expectation and exact suite fingerprint; all 78 targeted support tests pass. The clean full support run passes all 2,768 tests. - The three review regression cases failed before repair. They showed remote counts of zero and two, and a completed run that waited for the final diagnostic sink. They now pass. The stalled-sink case keeps persistence pending while the run returns, both bridge stops run once, and the staging lock map becomes empty. - Hosted evidence for this commit: [source verification](https://github.com/paperclipai/paperclip/actions/runs/39335475416), [retained command logs and status table](https://github.com/paperclipai/paperclip/actions/runs/39335475416/artifacts/12228829282). All listed commands exited zero except the incomplete unsharded test command described above. - The physical-launch test drives the executor's spawn callback twice. The native workspace test uses real Git repositories and verifies reuse and invalidation. These are deterministic tests, not a paid provider qualification campaign. ## Risks - Consumers must handle `partial_reuse` and `unknown`. Partial evidence no longer produces a legacy cold/warm boolean. - Native and remote bridged provider process evidence is still unavailable on some paths. The report shows unknown values for those paths. - Receipt emission is best effort. Missing receipts reduce confidence in a label and must not change execution or settlement. - No schema migration, first-party Telemetry event, or endpoint default changes are included. ## Model Used OpenAI Codex, based on GPT-6, used reasoning, repository tools, and code execution. The exact provider model ID and context window are not exposed to this session. The existing implementation checkpoint was preserved from the earlier agent run. ## 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: Paperclip <noreply@paperclip.ing> Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
191 lines
12 KiB
TypeScript
191 lines
12 KiB
TypeScript
import { execFile } from "node:child_process";
|
|
import { summarizeStartupReuse } from "@paperclipai/adapter-utils/startup-reuse";
|
|
import { mkdir, mkdtemp, readFile, readdir, rm, writeFile } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { heartbeatRuns, type Db } from "@paperclipai/db";
|
|
import type { EnvironmentLease } from "@paperclipai/shared";
|
|
import type { AdapterSandboxExecutionTarget } from "@paperclipai/adapter-utils/execution-target";
|
|
import type { CommandManagedRuntimeRunner } from "@paperclipai/adapter-utils/command-managed-runtime";
|
|
import * as restoreMerge from "@paperclipai/adapter-utils/workspace-restore-merge";
|
|
import * as workspaceSeedCache from "@paperclipai/adapter-utils/workspace-seed-cache";
|
|
import * as gitWorkspaceSync from "@paperclipai/adapter-utils/git-workspace-sync";
|
|
import { runLocalGit } from "@paperclipai/adapter-utils/git-workspace-sync";
|
|
import { prepareNativeWorkspaceSync, nativeWorkspaceSyncInternals } from "../services/native-runtime/native-workspace-sync.js";
|
|
|
|
const runner: CommandManagedRuntimeRunner = {
|
|
execute: (input) => new Promise((resolve, reject) => {
|
|
const child = execFile(input.command, input.args ?? [], {
|
|
cwd: input.cwd, env: { ...process.env, ...input.env },
|
|
timeout: input.timeoutMs, maxBuffer: 16 * 1024 * 1024,
|
|
}, (error, stdout, stderr) => resolve({
|
|
exitCode: error ? (typeof error.code === "number" ? error.code : 1) : 0,
|
|
signal: error?.signal ?? null, timedOut: error?.killed ?? false, stdout, stderr,
|
|
}));
|
|
// Git probes may exit without consuming stdin; their exit status remains
|
|
// authoritative. Surface unexpected pipe errors instead of masking them.
|
|
child.stdin?.on("error", (error: NodeJS.ErrnoException) => {
|
|
if (error.code !== "EPIPE") reject(error);
|
|
});
|
|
child.stdin?.end(input.stdin ?? "");
|
|
}),
|
|
};
|
|
|
|
async function git(cwd: string, ...args: string[]) {
|
|
return (await runLocalGit(cwd, args)).stdout.trim();
|
|
}
|
|
|
|
describe("native warm workspace Git history", () => {
|
|
const oldHome = process.env.PAPERCLIP_HOME;
|
|
const oldInstance = process.env.PAPERCLIP_INSTANCE_ID;
|
|
const roots: string[] = [];
|
|
afterEach(async () => {
|
|
vi.restoreAllMocks();
|
|
if (oldHome === undefined) delete process.env.PAPERCLIP_HOME;
|
|
else process.env.PAPERCLIP_HOME = oldHome;
|
|
if (oldInstance === undefined) delete process.env.PAPERCLIP_INSTANCE_ID;
|
|
else process.env.PAPERCLIP_INSTANCE_ID = oldInstance;
|
|
await Promise.all(roots.splice(0).map(root => rm(root, { recursive: true, force: true })));
|
|
});
|
|
|
|
it.each(["unchanged", "host_commit", "host_branch", "host_origin", "remote_commit", "remote_commit_corrupt_seed", "remote_commit_missing_seed", "remote_commit_cache_refused", "host_bytes_cache_refused", "remote_commit_missing_run_seed", "remote_commit_corrupt_run_seed", "nested_commit", "plain_nested_commit"] as const)(
|
|
"checks Git identity before reusing a warm sandbox: %s", async (change) => {
|
|
const invalidRunSeed = change === "remote_commit_missing_run_seed" || change === "remote_commit_corrupt_run_seed";
|
|
const cacheRefused = change === "remote_commit_cache_refused" || change === "host_bytes_cache_refused" || invalidRunSeed;
|
|
const snapshotWorker = vi.spyOn(restoreMerge, "captureDirectorySnapshotOffThread");
|
|
const packClone = vi.spyOn(gitWorkspaceSync, "withShallowGitWorkspaceClone");
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-warm-history-"));
|
|
roots.push(root);
|
|
process.env.PAPERCLIP_HOME = path.join(root, "home");
|
|
process.env.PAPERCLIP_INSTANCE_ID = "test";
|
|
const host = path.join(root, "host");
|
|
const remote = path.join(root, "remote");
|
|
async function initRepo(dir: string) {
|
|
await mkdir(dir, { recursive: true });
|
|
await git(dir, "init", "-b", "work");
|
|
await git(dir, "config", "user.name", "Test");
|
|
await git(dir, "config", "user.email", "test@paperclip.dev");
|
|
await writeFile(path.join(dir, "file.txt"), "unchanged contents\n");
|
|
await git(dir, "add", ".");
|
|
await git(dir, "commit", "-m", "base");
|
|
}
|
|
if (change === "plain_nested_commit") await mkdir(host, { recursive: true });
|
|
else await initRepo(host);
|
|
const nestedPath = path.join(".paperclip-repositories", "nested");
|
|
if (change === "nested_commit" || change === "plain_nested_commit") await initRepo(path.join(host, nestedPath));
|
|
const lease = { id: "lease", providerLeaseId: "sandbox", metadata: {} } as EnvironmentLease;
|
|
let runnerProfileJson: Record<string, unknown> = {};
|
|
// Persist the real service's descriptors and stamps; only the DB query
|
|
// plumbing is in memory. Git, staging, warm adoption, and restore are real.
|
|
const db = {
|
|
select: () => {
|
|
const query = {
|
|
from: () => query, where: () => query, for: () => query,
|
|
limit: async () => [{ runnerProfileJson, metadata: lease.metadata }],
|
|
};
|
|
return query;
|
|
},
|
|
update: (table: unknown) => ({
|
|
set: (value: { runnerProfileJson?: Record<string, unknown>; metadata?: Record<string, unknown> }) => ({
|
|
where: async () => {
|
|
if (table === heartbeatRuns) runnerProfileJson = value.runnerProfileJson!;
|
|
else lease.metadata = value.metadata!;
|
|
},
|
|
}),
|
|
}),
|
|
transaction: async (fn: (tx: unknown) => Promise<unknown>) => fn(db),
|
|
};
|
|
const target: AdapterSandboxExecutionTarget = {
|
|
kind: "remote", transport: "sandbox", providerKey: "test", leaseId: lease.id,
|
|
remoteCwd: remote, runner, timeoutMs: 30_000,
|
|
sandboxLeaseAcquisition: { outcome: "created", providerLeaseId: "sandbox" },
|
|
};
|
|
const input = { db: db as unknown as Db, companyId: "company", workspaceId: "workspace", workspaceLocalDir: host, lease, target };
|
|
const first = (await prepareNativeWorkspaceSync({ ...input, runId: "first" }))!;
|
|
expect(first.mode).toBe("host_current");
|
|
expect(snapshotWorker).toHaveBeenCalled();
|
|
expect(first.reference.schema).toBe("paperclip.native-workspace-sync/v3");
|
|
if (change === "plain_nested_commit") {
|
|
const recovered = await nativeWorkspaceSyncInternals.readDescriptor({ runId: "first", reference: first.reference });
|
|
expect(recovered.descriptor.gitSnapshot).toBeNull();
|
|
expect(recovered.descriptor.repositories?.[0]?.path).toBe(nestedPath);
|
|
}
|
|
await first.restoreWorkspace();
|
|
await first.cleanup();
|
|
|
|
if (change === "host_commit" || change === "nested_commit" || change === "plain_nested_commit") {
|
|
await git(change === "nested_commit" || change === "plain_nested_commit" ? path.join(host, nestedPath) : host, "commit", "--allow-empty", "-m", "host only");
|
|
} else if (change === "host_branch") {
|
|
await git(host, "checkout", "-b", "other");
|
|
} else if (change === "host_origin") {
|
|
await git(host, "remote", "add", "origin", "https://github.com/paperclipai/new-source.git");
|
|
} else if (change === "host_bytes_cache_refused") {
|
|
await writeFile(path.join(host, "file.txt"), "updated host content\n");
|
|
await writeFile(path.join(host, "extra.txt"), "new host file\n");
|
|
} else if (change.startsWith("remote_commit")) {
|
|
await git(remote, "-c", "user.name=Test", "-c", "user.email=test@paperclip.dev", "commit", "--allow-empty", "-m", "remote only");
|
|
}
|
|
if (change === "remote_commit_corrupt_seed" || change === "remote_commit_missing_seed") {
|
|
const cache = path.join(process.env.PAPERCLIP_HOME!, "instances", "test", "native-workspace-sync", "generations", "company", "workspace");
|
|
const [generation] = (await readdir(cache)).filter(name => /^[a-f0-9]{64}$/.test(name));
|
|
expect(generation).toBeDefined();
|
|
const archive = path.join(cache, generation!, "workspace.tar");
|
|
await rm(archive);
|
|
if (change === "remote_commit_corrupt_seed") await writeFile(archive, "invalid cached archive");
|
|
}
|
|
if (cacheRefused) {
|
|
await rm(path.join(process.env.PAPERCLIP_HOME!, "instances", "test", "native-workspace-sync", "generations", "company", "workspace"), { recursive: true, force: true });
|
|
vi.spyOn(workspaceSeedCache, "publishWorkspaceSeedGeneration").mockResolvedValue(false);
|
|
}
|
|
const hostRepo = change === "plain_nested_commit" ? path.join(host, nestedPath) : host;
|
|
const remoteRepo = change === "plain_nested_commit" ? path.join(remote, nestedPath) : remote;
|
|
const expectedContents = await readFile(path.join(hostRepo, "file.txt"), "utf8");
|
|
const expectedHead = await git(hostRepo, "rev-parse", "HEAD");
|
|
const expectedBranch = await git(hostRepo, "symbolic-ref", "--short", "HEAD");
|
|
const nestedHead = change === "nested_commit" || change === "plain_nested_commit" ? await git(path.join(host, nestedPath), "rev-parse", "HEAD") : null;
|
|
runnerProfileJson = {};
|
|
packClone.mockClear();
|
|
let invalidatedRunSeed = false;
|
|
const secondRunner: CommandManagedRuntimeRunner = {
|
|
execute: async operation => {
|
|
const result = await runner.execute(operation);
|
|
if (invalidRunSeed && !invalidatedRunSeed && operation.args?.some(arg => arg.includes("cat ") && arg.includes("workspace-sync-v1.json"))) {
|
|
invalidatedRunSeed = true;
|
|
const seed = nativeWorkspaceSyncInternals.durableSeedPaths("second");
|
|
await rm(seed.workspaceArchivePath);
|
|
if (change === "remote_commit_corrupt_run_seed") await writeFile(seed.workspaceArchivePath, "invalid prepared archive");
|
|
}
|
|
return result;
|
|
},
|
|
};
|
|
const reuseEvents: import("@paperclipai/adapter-utils").AdapterRuntimeEvent[] = [];
|
|
const second = (await prepareNativeWorkspaceSync({ ...input, runId: "second", onEvent: async event => { reuseEvents.push(event); }, target: {
|
|
...target, runner: secondRunner, sandboxLeaseAcquisition: { outcome: "resumed", providerLeaseId: "sandbox" },
|
|
} }))!;
|
|
try {
|
|
if (change === "remote_commit") expect(packClone).not.toHaveBeenCalled();
|
|
if (cacheRefused) expect(packClone).toHaveBeenCalledTimes(invalidRunSeed ? 2 : 1);
|
|
if (invalidRunSeed) expect(invalidatedRunSeed).toBe(true);
|
|
if (change === "remote_commit_corrupt_seed" || change === "remote_commit_missing_seed") expect(packClone).toHaveBeenCalled();
|
|
expect(second.mode).toBe(change === "unchanged" ? "adopt_remote" : "host_current");
|
|
expect(summarizeStartupReuse(reuseEvents).layers.workspace).toEqual(change === "unchanged"
|
|
? { state: "reused", reason: "verified_reuse" }
|
|
: { state: "fresh", reason: "workspace_changed" });
|
|
expect(await readFile(path.join(remoteRepo, "file.txt"), "utf8")).toBe(expectedContents);
|
|
if (change === "host_bytes_cache_refused") expect(await readFile(path.join(remote, "extra.txt"), "utf8")).toBe("new host file\n");
|
|
expect(await git(remoteRepo, "rev-parse", "HEAD")).toBe(expectedHead);
|
|
expect(await git(remoteRepo, "symbolic-ref", "--short", "HEAD")).toBe(expectedBranch);
|
|
if (change === "host_origin") expect(await git(remote, "remote", "get-url", "origin")).toBe("https://github.com/paperclipai/new-source.git");
|
|
await second.restoreWorkspace();
|
|
expect(await readFile(path.join(hostRepo, "file.txt"), "utf8")).toBe(expectedContents);
|
|
expect(await git(hostRepo, "rev-parse", "HEAD")).toBe(expectedHead);
|
|
if (nestedHead) {
|
|
expect(await git(path.join(remote, nestedPath), "rev-parse", "HEAD")).toBe(nestedHead);
|
|
expect(await git(path.join(host, nestedPath), "rev-parse", "HEAD")).toBe(nestedHead);
|
|
}
|
|
} finally { await second.cleanup(); }
|
|
}, 30_000,
|
|
);
|
|
});
|