mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-24 05:47:10 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The native Runner starts each agent harness and owns its lifecycle, credentials and recovery > - Google Antigravity is Google's only first-party coding harness, and it is the harness for Gemini 4 Neon > - The Runner had an Antigravity integration, but only as a pending candidate: ACP server 1.4.3, macOS ARM64 only, Google sign-in only, closed unless an operator opened it for one company and one model > - Cloud sandboxes run Linux and use API keys, so the candidate could not run there, and it had one attended test cell > - This pull request moves the integration to ACP server 1.5.2, makes it run on Linux and with a Gemini API key, adds the tests the other ACPX harnesses have, and removes the code paths that would block recovery after release > - The benefit is that the release of Antigravity becomes a small declaration change after the live suites pass. The profile stays `pending` in this pull request. ## Linked Issues or Issue Description Refs #98 Refs #6559 Refs #8523 Refs #21121 (a separate legacy-style `agy_local` adapter that uses the CLI print protocol; this pull request does not replace or include it) ## What Changed **Runtime** - Pin Antigravity ACP server 1.5.2 (was 1.4.3). Owned admission patch is `1.5.2-paperclip.2`. - Verified patched closures for `darwin-arm64`, `linux-x64` and `linux-arm64`. `darwin-x64` stays inventory-only. - The patcher reads Mach-O and ELF builds. It signs macOS output only. One admission source serves all platforms. - Platform gates in TypeScript, Rust, the sidecar schema and the server admit each host that has a verified closure. **Auth and models** - Gemini API-key auth reaches an exact-model session receipt. Admission accepts a model only when the base model and the thinking level both match the requested ID. - API-key connections get a model list on local and cloud environments. The list is generated at build time from the pinned runtime. The server starts no process to read it. - Gemini 4 Neon, Carbon, Argon and Hydrogen are selectable. The picker marks them "needs a paid Gemini API plan" for API-key connections. - One shared module maps model ID to family and thinking level. - `google/gemini-4-neon` is added to the OpenCode model list. A new model audit is in `doc/adapter-model-audit-2026-11-22.md`. **Lifecycle and failures** - A provider error no longer completes the turn. The driver classifies it: overloaded, rate limit, quota, auth rejected, model unavailable. - Overload retries are bounded (3 attempts, about 14 seconds). - A refused session reload maps to incompatible saved state, so the automatic replacement conversation applies. - Server gates that refused restart recovery, remote targets and shared state for Antigravity now apply only while the profile is pending. - A Google sign-in connection with a cloud environment is refused at save and at Test, with a plain message. - A released profile rejects candidate grants in TypeScript and in Rust. **Launch cost and integrity (all native ACPX providers)** - Each closure is verified one time into a sealed read-only store. Later launches check file identities and hash the exact executable they start. - Remote provider-pack verification is recorded per sandbox lease. Later runs check kernel identity and fall back to the full hash on any difference. - Superseded stores are removed in the background after a launch. **Provider pack and image** - The provider pack carries Antigravity for `linux-x64` as a candidate provider. It becomes an ordinary provider from the profile status alone. - The Daytona image build accepts the candidate. A credential-free smoke runs in the build. **Tests and CI** - New `antigravity-qualification` suite: 24 cells, local and Daytona. - New model lineup suites: 14 API-key cells and 14 Gemini 4 cells. Each cell requires the exact model in the Runner receipt. - Antigravity can run the `chat-features` cases with `--profile runner-acpx-antigravity`. - `runner-full-stack-e2e.yml` passes `GEMINI_API_KEY` for the new profile and derives candidate providers from the selected Daytona cells. **Docs** - `doc/plans/2026-11-22-antigravity-qualification.md` is the current release contract, acceptance ledger and operator recipe. ## Verification Commands that passed on the final revision: - `pnpm build` - Typecheck for all packages, including the runner-e2e test projects - `pnpm test:e2e:runner:unit`: 11,665 Vitest tests passed, 25 skipped; 386 node tests passed - `cargo test -p paperclip-runner-core -- --test-threads=4`: 1,199 passed, 2 failed. The 2 failures are Codex transport timing tests that pass alone and on `master`. - `cargo fmt --check`, `check:acpx-profiles`, `check:protocol-types`, `node scripts/check-maps.mjs` - Native patch tests: 9 of 9 on `darwin-arm64` and 9 of 9 on `linux-x64` - UI picker tests: 397 of 397 Known failures that also fail on `master`: - 11 runner package script tests (browser, Pi and package-boundary checks) - 6 `runtime-selection` tests that read an untracked local skill file Live evidence, without a prompt: - Clean provisioning on `darwin-arm64` and on `linux-x64` in a Daytona sandbox. The closure digests reproduce. A changed or missing file is rejected. - `initialize` reports 1.5.2. An API-key session returns a receipt for exactly `gemini-3.8-flash-low` and the exact instruction bytes, on both platforms. - All 28 model IDs (14 Gemini 3, 14 Gemini 4) return an exact receipt under an API key. - A session survives a process kill and resumes in a new process with exact receipts, on both platforms. - The server's remote path verifies the provider pack in a Daytona sandbox. - Run start to native `initialize`: 3.45 s to 1.46 s on macOS, 3.65 s to 1.74 s on Linux x64, before the per-launch executable hash was restored (about 60 ms on macOS; not measured on Linux). - Remote pack verification on a reused sandbox lease: about 4.3 s to about 0.25 s. Live evidence, with a prompt, on an already-released harness: - Pi native, `pi-native.runner-acpx-pi.local.agent-files-fresh-run`, on `darwin-arm64` at `427e9b088b`: 1 of 1 passed, 14 of 14 checks, both native runs succeeded (25.5 s and 25.7 s). The process started from the new launch store with no fallback warning. - The same cell and `native-pending-controller-restart` failed in the paid workflow on this branch and on `master` in the same way, before any native start. The workflow does not install the Pi runtime for local cells, so the agent setup check fails. That is a workflow gap, not part of this change. **Not run.** No Antigravity prompt completed on 1.5.2 on any platform. The only Gemini key available is on the free tier, and Google returned 503 or 429 for each attempt on two days. These gates are open: - All 24 `antigravity-qualification` cells - Both model lineup suites, including inference on Gemini 4 Neon - The attended Google sign-in journey on 1.5.2 - The chat cases under Antigravity - Image pull time and startup time on a published image - A native start on `linux-arm64` - A live provider-death cell for Kimi, Pi or Copilot on the new launch store (one ordinary Pi cell passed live; see above) ## Risks - **The launch store changes how every native ACPX provider starts** (Kimi, Copilot, Cursor, Pi), not only Antigravity. A review found two defects in the first version (an executable swap was possible, and Pi launches broke). Both are fixed with tests. One live Pi cell passed on this branch on macOS. No live provider-death cell and no Linux cell ran for those providers. - The profile digest changes. Saved Antigravity candidate sessions and existing candidate grants stop working. The new release refuses old state by name and starts a replacement conversation. - The Linux provider pack and the Daytona image grow by about 834 MB (about 274 MB compressed) when Antigravity is included. - The pack verification record is in server memory. The first run after a server restart pays the full hash again. - Antigravity 1.5.2 reads the workspace `GEMINI.md` and `AGENTS.md` as user rules. This is deliberate and matches Codex. Any other rule file is refused. - Orchestrator mode is not available. ACP server 1.5.2 does not expose it. - Antigravity stays `pending`. Normal users cannot run it until a later change removes the pending status. ## Model Used - Claude Fable 5.2 (`claude-fable-5-2`) planned, briefed and integrated the work, with tool use. - Claude Opus 5.5 (`claude-opus-5-5`) subagents wrote the code and ran the tests, with tool use and code execution. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 <noreply@anthropic.com>
260 lines
21 KiB
TypeScript
260 lines
21 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { execFileSync, spawn } from "node:child_process";
|
|
import { statSync, realpathSync } from "node:fs";
|
|
import { describe, expect, it } from "vitest";
|
|
import { assertSameKimiPending, observeKimiLifecyclePending, readKimiLifecycleSettlement } from "./kimi-lifecycle-evidence.js";
|
|
import { dispatchKimiLifecycleAction } from "./kimi-lifecycle.js";
|
|
import { KIMI_MAC_PROCESS_OBSERVER, readKimiLocalProcesses, selectKimiLocalTarget, type KimiLocalProcess } from "./kimi-local-provider-fault.js";
|
|
|
|
type Row = Record<string, any>;
|
|
const caller = { type: "board", userId: "local-board", source: "local_implicit" } as const;
|
|
const cancellationRequestId = "11111111-2222-4333-8444-555555555555";
|
|
const sha = (value: string) => `sha256:${createHash("sha256").update(value).digest("hex")}`;
|
|
function fixture(remote = false) {
|
|
const scope = { companyId: "company", issueId: "issue", runId: "run", target: "denied/target.txt", ...(remote ? { actionFile: `.paperclip-eval-action-${"a".repeat(36)}.txt` } : {}) };
|
|
const run: Row = { id: "run", companyId: "company", nativeIssueId: "issue", runtimeMode: "native", status: "running", nativeSessionId: "session", runnerInstanceId: "runner", resultJson: {} };
|
|
const issue: Row = { id: "issue", companyId: "company", status: "in_progress" };
|
|
const row = (eventType: string, sourceSeq: number, payload: Row): Row => ({ companyId: "company", runId: "run", seq: sourceSeq, eventType, protocolSchemaVersion: 1,
|
|
payload: { prpEvent: { schema: "paperclip.prp.event.v1", schemaVersion: 1, sourceKind: "runner", eventType, runId: "run", turnId: "turn", normalizedSessionId: "session",
|
|
sourceInstanceId: "runner", sourceSeq, sourceEventId: `runner:run:${sourceSeq}`, emittedAt: "2026-10-28T00:00:00Z", payload } } });
|
|
const tool = (executionId: string, name: string, operation: string, target: string | null, status = "running") => ({ schema: "paperclip.tool.execution.v1", executionId, transport: "builtin", name, operation, target, status });
|
|
const request: Row = { schema: "paperclip.runtime_request.v2", type: "permission", requestKind: "permission_approval", status: "pending", requestId: "request", turnId: "turn", itemId: "permission-item",
|
|
prompt: `Change file: ${scope.target}`, choices: [{ key: "accept", label: "Allow once" }, { key: "decline", label: "Deny" }, { key: "cancel", label: "Cancel" }],
|
|
details: { toolCallId: "0:native-write" }, origin: { adapter: "acpx-runtime-sidecar", provider: "kimi", method: "session/request_permission" } };
|
|
const events: Row[] = remote ? [row("tool.execution.started", 1, tool("0:read", "Read", "read", scope.actionFile!)), row("tool.execution.completed", 2, tool("0:read", "Read", "read", scope.actionFile!, "completed"))] : [];
|
|
events.push(row("tool.execution.started", events.length + 1, tool("0:native-write", "Write", "edit", null)),
|
|
row("tool.execution.progressed", events.length + 2, tool("0:native-write", "Write", "edit", null)),
|
|
row("runtime_request.created", events.length + 3, { request }));
|
|
const state = () => ({ run, issue, events });
|
|
const observe = () => observeKimiLifecyclePending({ ...state(), scope });
|
|
const settle = (branch: "stop" | "loss", cancelId = cancellationRequestId) => {
|
|
const pending = observe();
|
|
if (branch === "stop") {
|
|
run.status = "cancelled";
|
|
run.resultJson = { startupCancellation: { cancellationRequestId: cancelId, requestedBy: { type: "board", userId: "local-board" } }, nativeCancellation: {
|
|
schema: "paperclip.native-cancellation.v1", intentId: `native-cancellation:${cancelId}`, companyId: "company", runId: "run", issueId: "issue", scope: "run",
|
|
dispatched: true, dispatchState: "acknowledged", reasonCode: "cancellation_run_only", effects: ["release_run_resources"], intentAuditId: "intent-audit", acknowledgementAuditId: "ack-audit",
|
|
} };
|
|
events.push(row("runtime_request.cancelled", events.length + 1, { requestId: "request", requestKind: "permission_approval", turnId: "turn", itemId: "permission-item", reason: "turn_terminal" }));
|
|
events.push(row("turn.cancelled", events.length + 1, { status: "cancelled", error: null }));
|
|
} else {
|
|
run.status = "failed"; issue.status = "blocked";
|
|
events.push(row("runtime_request.expired", events.length + 1, { requestId: "request", requestKind: "permission_approval", requestType: "permission", turnId: "turn", itemId: "permission-item", reason: "provider_process_lost", replayAllowed: false }));
|
|
events.push(row("turn.failed", events.length + 1, { error: { code: "provider_transport_lost" } }));
|
|
}
|
|
const dispatchMonotonicNs = process.hrtime.bigint().toString();
|
|
return { pending, dispatchMonotonicNs, caller, cancellationRequestId: cancelId, branch };
|
|
};
|
|
return { scope, run, issue, events, request, row, tool, state, observe, settle };
|
|
}
|
|
const payload = (row: Row) => row.payload.prpEvent.payload;
|
|
|
|
function retainedLocalStopRows() {
|
|
const scope = { companyId: "26725944-fac6-4382-883c-a57d5448a3ba", issueId: "9334a1c6-3f67-4536-8570-e81db0b70498",
|
|
runId: "209bc4ba-4f54-4ff8-98b2-49879cfb52f8", target: "pc-denied-6WPcjH/kimi-stop-c5be66dab0a0-1.txt" };
|
|
const session = "18298d7f-4d8f-4185-8ae7-660daa69ead7", source = "38cdabd8-af4c-4c76-9f20-9931e36475df",
|
|
turn = "turn_lab_8e3a1a4a520442ad80c36025a1353ba6", item = `item-${scope.runId}`, toolCallId = "0:tool_uKx4azxIHxpU6e5TZ2xLHbVj";
|
|
const origin = { method: "session/request_permission", adapter: "acpx-runtime-sidecar", provider: "kimi" };
|
|
const choices = [{ key: "accept", label: "Allow once" }, { key: "decline", label: "Deny" }, { key: "cancel", label: "Cancel" }];
|
|
const request = { type: "permission", itemId: item, method: "session/request_permission", origin,
|
|
prompt: `Change file: ${scope.target}`, schema: "paperclip.runtime_request.v2", status: "pending", turnId: turn, choices,
|
|
details: { itemId: item, origin, reason: `Change file: ${scope.target}`, turnId: turn, choices,
|
|
threadId: "paperclip-9558eb1e0ea79ed9b728d62643b53ab02477d5a4711ef634d8cf0c5b5d8d0af9", toolCallId },
|
|
requestId: "acpx-input-25f63168069f72f421df7bd9", requestKind: "permission_approval" };
|
|
const row = (eventType: string, seq: number, sourceSeq: number, emittedAt: string, value: Row): Row => ({
|
|
companyId: scope.companyId, runId: scope.runId, seq, eventType, protocolSchemaVersion: 1,
|
|
payload: { prpEvent: { runId: scope.runId, itemId: item, schema: "paperclip.prp.event.v1", turnId: turn, payload: value,
|
|
priority: 1, emittedAt, eventType, sourceSeq, sourceKind: "runner", schemaVersion: 1,
|
|
sourceEventId: `${source}:${scope.runId}:${sourceSeq}`, sourceInstanceId: source, normalizedSessionId: session } },
|
|
});
|
|
const events = [row("tool.execution.started", 59, 30, "2026-10-28T14:48:05.538Z", {
|
|
name: "Write", output: "null", schema: "paperclip.tool.execution.v1", status: "running", target: null, exitCode: null,
|
|
progress: "Write (pending)", readOnly: false, namespace: null, operation: "edit", transport: "builtin", durationMs: null,
|
|
executionId: toolCallId, outputBytes: 4, inputUpdated: false,
|
|
outputDigest: "sha256:74234e98afe7498fb5daf1f36ac2d78acc339464f950703b8c019892f982b90b", outputTruncated: false,
|
|
}), row("runtime_request.created", 141, 112, "2026-10-28T14:48:06.604Z", { request })];
|
|
return { scope, events,
|
|
run: { id: scope.runId, companyId: scope.companyId, nativeIssueId: scope.issueId, status: "running", runtimeMode: "native",
|
|
nativeSessionId: session, runnerInstanceId: source, resultJson: null },
|
|
issue: { id: scope.issueId, companyId: scope.companyId, status: "in_progress" } };
|
|
}
|
|
|
|
describe("Kimi native Write lifecycle evidence", () => {
|
|
it("accepts retained local Stop rows with a null execution target and no permission kind", () => {
|
|
const actual = retainedLocalStopRows();
|
|
expect(payload(actual.events[0]!).target).toBeNull();
|
|
expect(payload(actual.events[1]!).request.details).not.toHaveProperty("kind");
|
|
expect(observeKimiLifecyclePending(actual)).toMatchObject({
|
|
requestId: "acpx-input-25f63168069f72f421df7bd9", toolCallId: "0:tool_uKx4azxIHxpU6e5TZ2xLHbVj",
|
|
executionId: "0:tool_uKx4azxIHxpU6e5TZ2xLHbVj", startedSourceSeq: 30, requestSourceSeq: 112,
|
|
});
|
|
});
|
|
it.each(["target", "kind", "callback", "edit-operation", "tool-name", "prompt"])("rejects conflicting retained local Stop %s", conflict => {
|
|
const actual = retainedLocalStopRows(), tool = payload(actual.events[0]!), request = payload(actual.events[1]!).request;
|
|
if (conflict === "target") tool.target = "another.txt";
|
|
if (conflict === "kind") request.details.kind = "execute";
|
|
if (conflict === "callback") request.details.toolCallId = "0:other";
|
|
if (conflict === "edit-operation") tool.operation = "execute";
|
|
if (conflict === "tool-name") tool.name = "Edit";
|
|
if (conflict === "prompt") request.prompt = "Change file: another.txt";
|
|
expect(() => observeKimiLifecyclePending(actual)).toThrow();
|
|
});
|
|
it("accepts explicit matching edit metadata without requiring it on the native permission", () => {
|
|
const f = fixture();
|
|
f.request.details.kind = "edit"; payload(f.events[1]!).target = f.scope.target;
|
|
expect(f.observe().executionId).toBe("0:native-write");
|
|
});
|
|
it.each([false, true])("binds actual Write approval to its native edit execution (remote=%s)", remote => {
|
|
const f = fixture(remote), before = f.observe(), later = f.observe();
|
|
expect(before).toMatchObject({ toolCallId: "0:native-write", executionId: "0:native-write", normalizedSessionId: "session", sourceInstanceId: "runner" });
|
|
expect(() => assertSameKimiPending(before, later)).not.toThrow();
|
|
});
|
|
it.each([
|
|
["another provider", (f: ReturnType<typeof fixture>) => { f.request.origin.provider = "copilot"; }],
|
|
["semantic permission", f => { f.request.origin.method = "semantic/tool"; }],
|
|
["missing safe card path", f => { f.request.prompt = "Write"; }],
|
|
["conflicting permission kind", f => { f.request.details.kind = "other"; }],
|
|
["session-wide authority", f => { f.request.choices.push({ key: "accept_for_session" }); }],
|
|
["missing decline", f => { f.request.choices = f.request.choices.filter((x: Row) => x.key !== "decline"); }],
|
|
["wrong native call", f => { f.request.details.toolCallId = "foreign"; }],
|
|
["different file", f => { payload(f.events[1]!).target = "elsewhere.txt"; }],
|
|
["native Edit substituted for Write", f => { payload(f.events[1]!).name = "Edit"; }],
|
|
["completed file effect", f => { f.events.push(f.row("tool.execution.completed", 4, f.tool("0:native-write", "Write", "edit", f.scope.target, "completed"))); }],
|
|
["extra shell", f => { f.events.unshift(f.row("tool.execution.started", 0, f.tool("shell", "Bash", "execute", null))); }],
|
|
["replayed start", f => { f.events.push(f.row("tool.execution.started", 4, f.tool("0:native-write", "Write", "edit", f.scope.target))); }],
|
|
["foreign company", f => { f.events[0]!.companyId = "foreign"; }],
|
|
["foreign source", f => { f.events[0]!.payload.prpEvent.sourceInstanceId = "other"; }],
|
|
["restored session", f => { f.run.nativeSessionId = "replacement"; }],
|
|
["another provider generation", f => { f.run.runnerInstanceId = "replacement"; }],
|
|
] satisfies Array<[string, (f: ReturnType<typeof fixture>) => void]>)("rejects %s", (_name, mutate) => {
|
|
const f = fixture(); mutate(f); expect(f.observe).toThrow();
|
|
});
|
|
it.each(["wrong-path", "unclosed", "extra-write", "post-write-read"])("rejects ambiguous bootstrap %s", kind => {
|
|
const f = fixture(true);
|
|
if (kind === "wrong-path") payload(f.events[0]!).target = "another.txt";
|
|
if (kind === "unclosed") f.events.splice(1, 1);
|
|
if (kind === "extra-write") payload(f.events[0]!).operation = "edit";
|
|
if (kind === "post-write-read") { f.events[0]!.seq = 99; }
|
|
expect(f.observe).toThrow();
|
|
});
|
|
it.each(["stop", "loss"] as const)("accepts the original %s callback closure", branch => {
|
|
const f = fixture(), binding = f.settle(branch);
|
|
expect(readKimiLifecycleSettlement({ ...f.state(), ...binding })).toMatchObject({ branch, replayAllowed: false, completedMutation: false });
|
|
payload(f.events.at(-2)!).requestId = "other";
|
|
expect(() => readKimiLifecycleSettlement({ ...f.state(), ...binding })).toThrow();
|
|
});
|
|
it("keeps the observed permission row bound when native expiry omits its full request", () => {
|
|
const f = fixture(), binding = f.settle("loss");
|
|
expect(payload(f.events.at(-2)!)).not.toHaveProperty("request");
|
|
expect(readKimiLifecycleSettlement({ ...f.state(), ...binding })).toMatchObject({ branch: "loss", replayAllowed: false });
|
|
f.request.choices[0].label = "Changed after pending observation";
|
|
expect(() => readKimiLifecycleSettlement({ ...f.state(), ...binding })).toThrow("original pre-action pending receipt changed or missing");
|
|
});
|
|
it.each(["replay", "cancelled", "wrong-reason", "changed-request", "injected-original-request", "new-turn", "new-operation", "success", "Stop"])("rejects false native loss %s", kind => {
|
|
const f = fixture(), binding = f.settle("loss"), expiry = f.events.at(-2)!;
|
|
if (kind === "replay") payload(expiry).replayAllowed = true;
|
|
if (kind === "cancelled") expiry.eventType = expiry.payload.prpEvent.eventType = "runtime_request.cancelled";
|
|
if (kind === "wrong-reason") payload(expiry).reason = "durable_handoff";
|
|
if (kind === "changed-request") payload(expiry).request = { ...f.request, prompt: "replacement" };
|
|
if (kind === "injected-original-request") payload(expiry).request = f.request;
|
|
if (kind === "new-turn") { f.events.at(-1)!.payload.prpEvent.turnId = "replacement"; }
|
|
if (kind === "new-operation") f.events.push(f.row("tool.execution.started", 6, f.tool("late", "Write", "edit", f.scope.target)));
|
|
if (kind === "success") f.run.status = "succeeded";
|
|
if (kind === "Stop") f.run.resultJson.nativeCancellation = {};
|
|
expect(() => readKimiLifecycleSettlement({ ...f.state(), ...binding })).toThrow();
|
|
});
|
|
it("refuses a changed pending callback before dispatching a Stop or fault", async () => {
|
|
const f = fixture(); let reads = 0, actions = 0;
|
|
await expect(dispatchKimiLifecycleAction({ scope: f.scope, caller, branch: "stop", deadlineAt: Date.now() + 1000,
|
|
load: async () => { if (++reads === 2) f.request.requestId = "replacement"; return f.state(); }, retain: async () => {},
|
|
act: async () => { actions++; } })).rejects.toThrow("pending callback changed");
|
|
expect(actions).toBe(0);
|
|
});
|
|
it("retains and refreshes the pending observation before its only mutating action", async () => {
|
|
const f = fixture(), order: string[] = [];
|
|
const result = await dispatchKimiLifecycleAction({ scope: f.scope, caller, branch: "stop", deadlineAt: Date.now() + 1000,
|
|
load: async () => { order.push("load"); return f.state(); }, retain: async () => { order.push("retain"); },
|
|
act: async (_pending, requestId) => { order.push("action"); f.settle("stop", requestId); return { source: "public-Stop-test-double" }; } });
|
|
expect(order.slice(0, 4)).toEqual(["load", "retain", "load", "action"]);
|
|
expect(order.filter(x => x === "action")).toHaveLength(1);
|
|
expect(result.settlement.branch).toBe("stop");
|
|
});
|
|
});
|
|
|
|
function localFixture() {
|
|
const closureSha256 = "c".repeat(64), timestamp = Date.parse("2026-10-28T00:00:00Z");
|
|
const launch = "/private/tmp/paperclip-acpx-native-fixture/launch", distribution = `/private/tmp/paperclip-verified-native-501/${closureSha256}/distribution`;
|
|
const bootId = "12345678-1234-1234-1234-123456789abc", loader = "exact compiled guarded loader";
|
|
const proc = (pid: number, ppid: number, executable: string, command: string): KimiLocalProcess => ({ pid, ppid, pgid: pid === 21 ? 21 : 22,
|
|
startUs: String(timestamp * 1000 + pid), executable, executableDev: "1", executableIno: String(pid), command, argv: [executable], cwd: "/workspace", bootId });
|
|
const processes = [proc(21, 1, "/runner", "/runner --run-id run --lifecycle-mode per_turn"),
|
|
proc(22, 21, "/host-node", `/host-node --eval ${loader} ${launch} .paperclip-native-entry.cjs 0 0 commonjs [] 0`),
|
|
proc(23, 22, `${distribution}/node/bin/node`, "kimi-code")];
|
|
processes[1]!.argv = ["/host-node", "--eval", loader, launch, ".paperclip-native-entry.cjs", "0", "0", "commonjs", "[]", "0"];
|
|
const input = { authority: { pid: 21, groupId: 21, startedAt: new Date(timestamp).toISOString(), runId: "run" },
|
|
journal: processes.map(row => ({ pid: row.pid, parent: row.ppid, start: new Date(timestamp).toISOString() })), processes, workspacePath: "/workspace", guardLoaderSha256: sha(loader), closureSha256 };
|
|
return { input, select: () => selectKimiLocalTarget(input) };
|
|
}
|
|
describe("Kimi local native child selector", () => {
|
|
it("selects the exact pinned-path native descendant independently of its title", () => {
|
|
const f = localFixture(); expect(f.select().target.pid).toBe(23);
|
|
f.input.processes[2]!.command = "anything"; expect(f.select().target.pid).toBe(23);
|
|
});
|
|
it("uses byte-exact loader argv even when ps renders a different command", () => {
|
|
const f = localFixture(); f.input.processes[1]!.command = "a rendered command that cannot preserve loader bytes";
|
|
expect(f.select().target.pid).toBe(23);
|
|
});
|
|
it("decodes exactly argc arguments and excludes the trailing environment", () => {
|
|
const source = KIMI_MAC_PROCESS_OBSERVER.slice(KIMI_MAC_PROCESS_OBSERVER.indexOf("def decode_arguments(data):"), KIMI_MAC_PROCESS_OBSERVER.indexOf("def arguments(pid):"));
|
|
const run = (bytes: Buffer) => execFileSync("/usr/bin/python3", ["-I", "-B", "-c", `import base64,json,struct,sys\n${source}\nprint(json.dumps(decode_arguments(base64.b64decode(sys.argv[1]))))`, bytes.toString("base64")], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
|
const args = ["/node", "--eval", "line-one\nline-two", ""];
|
|
const header = Buffer.alloc(4); header.writeInt32LE(args.length);
|
|
const body = Buffer.from(`/node\0\0${args.join("\0")}\0CANARY=must-never-be-returned\0`);
|
|
const decoded = run(Buffer.concat([header, body])); expect(JSON.parse(decoded)).toEqual(args); expect(decoded).not.toContain("CANARY");
|
|
for (const count of [0, 129]) { const wrong = Buffer.from(header); wrong.writeInt32LE(count); expect(() => run(Buffer.concat([wrong, body]))).toThrow(); }
|
|
const changed = Buffer.from(header); changed.writeInt32LE(5);
|
|
expect(() => run(Buffer.concat([changed, Buffer.from(`/node\0\0${args.join("\0")}\0`) ]))).toThrow();
|
|
expect(() => run(Buffer.concat([header, Buffer.from("/node\0\0/node\0--eval\0truncated")]))).toThrow();
|
|
expect(() => run(Buffer.alloc(2))).toThrow();
|
|
});
|
|
it.skipIf(process.platform !== "darwin" || process.arch !== "arm64")("reads literal multiline argv without retaining a real child's environment", async () => {
|
|
const program = 'process.stdout.write("ready");setInterval(()=>{},1000)';
|
|
const literal = "line-one\nline-two";
|
|
const child = spawn(process.execPath, ["--eval", program, literal], { env: { PATH: "/usr/bin:/bin", CANARY: "must-never-be-returned" }, stdio: ["ignore", "pipe", "ignore"] });
|
|
const closed = new Promise(resolve => child.once("close", resolve));
|
|
try {
|
|
await new Promise(resolve => child.stdout!.once("data", resolve));
|
|
const rows = readKimiLocalProcesses([child.pid!]);
|
|
expect(rows[0]!.argv).toEqual([process.execPath, "--eval", program, literal]);
|
|
expect(JSON.stringify(rows)).not.toContain("must-never-be-returned");
|
|
} finally { child.kill("SIGTERM"); await closed; }
|
|
});
|
|
it("returns the store distribution and the separate launch directory", () => {
|
|
const selected = localFixture().select();
|
|
expect(selected.distribution).toBe(`/private/tmp/paperclip-verified-native-501/${"c".repeat(64)}/distribution`);
|
|
expect(selected.launch).toBe("/private/tmp/paperclip-acpx-native-fixture/launch");
|
|
});
|
|
it.each(["root", "foreign-loader", "wrong-entry", "unowned", "wrong-cwd", "boot", "cycle", "ambiguous", "foreign-closure", "old-snapshot-layout", "foreign-launch"])("fails closed for %s", kind => {
|
|
const f = localFixture();
|
|
if (kind === "foreign-closure") f.input.closureSha256 = "d".repeat(64);
|
|
if (kind === "old-snapshot-layout") f.input.processes[2]!.executable = "/private/tmp/paperclip-acpx-native-fixture/distribution/node/bin/node";
|
|
if (kind === "foreign-launch") f.input.processes[1]!.argv[3] = "/private/tmp/elsewhere/launch";
|
|
if (kind === "root") f.input.authority.runId = "other";
|
|
if (kind === "foreign-loader") f.input.processes[1]!.argv[2] = "wrong loader";
|
|
if (kind === "wrong-entry") f.input.processes[1]!.argv[4] = "foreign.cjs";
|
|
if (kind === "unowned") f.input.journal.pop();
|
|
if (kind === "wrong-cwd") f.input.processes[2]!.cwd = "/elsewhere";
|
|
if (kind === "boot") f.input.processes[2]!.bootId = "foreign";
|
|
if (kind === "cycle") f.input.processes[1]!.ppid = 23;
|
|
if (kind === "ambiguous") { f.input.processes.push({ ...f.input.processes[2]!, pid: 24 }); f.input.journal.push({ ...f.input.journal[2]!, pid: 24 }); }
|
|
expect(f.select).toThrow();
|
|
});
|
|
it.skipIf(process.platform !== "darwin" || process.arch !== "arm64")("reads real macOS kernel process birth and executable inode without environment inspection", () => {
|
|
const rows = readKimiLocalProcesses([process.pid]), current = rows.find(row => row.pid === process.pid);
|
|
expect(current?.executable).toBe(realpathSync(process.execPath));
|
|
const stat = statSync(current!.executable);
|
|
expect(current?.executableDev).toBe(String(stat.dev)); expect(current?.executableIno).toBe(String(stat.ino));
|
|
expect(Math.abs(Date.now() - Number(current!.startUs) / 1000 - process.uptime() * 1000)).toBeLessThan(5000);
|
|
});
|
|
});
|