mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-29 23:56:43 +01:00
Merge current CI entry points from master
The trusted typecheck workflow now invokes ci-typecheck-lane.mjs. The stacked branches lacked that script and could not start qualification. Refresh the SSH base from master so its CI source matches the workflow, then propagate the base to the Tailscale connector branch. Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
commit
4c06df094c
102 files changed
+6160
-1333
No files matched your search
@@ -11,6 +11,7 @@ const mockAgentService = vi.hoisted(() => ({
|
||||
const mockHeartbeatService = vi.hoisted(() => ({
|
||||
list: vi.fn(async () => []),
|
||||
buildRunOutputSilence: vi.fn(),
|
||||
buildRunOutputSilences: vi.fn(),
|
||||
decorateActiveRunStatus: vi.fn(),
|
||||
getRunIssueSummary: vi.fn(),
|
||||
getActiveRunIssueSummaryForAgent: vi.fn(),
|
||||
@@ -344,6 +345,7 @@ describe("agent live run routes", () => {
|
||||
});
|
||||
mockInstanceSettingsService.listCompanyIds.mockResolvedValue(["company-1"]);
|
||||
mockHeartbeatService.buildRunOutputSilence.mockResolvedValue(null);
|
||||
mockHeartbeatService.buildRunOutputSilences.mockImplementation(async (runs: unknown[]) => runs.map(() => null));
|
||||
mockHeartbeatService.decorateActiveRunStatus.mockImplementation((run) => ({
|
||||
...run,
|
||||
currentStatusMessage: null,
|
||||
@@ -838,9 +840,9 @@ describe("agent live run routes", () => {
|
||||
expect(res.body).toHaveLength(50);
|
||||
expect(mockRunSecretRedactionRegistry.redactForRuns).toHaveBeenCalledTimes(1);
|
||||
expect(mockRunSecretRedactionRegistry.redactForRun).not.toHaveBeenCalled();
|
||||
expect(mockHeartbeatService.buildRunOutputSilence).toHaveBeenCalledTimes(
|
||||
50,
|
||||
);
|
||||
expect(mockHeartbeatService.buildRunOutputSilence).not.toHaveBeenCalled();
|
||||
expect(mockHeartbeatService.buildRunOutputSilences).toHaveBeenCalledTimes(1);
|
||||
expect(mockHeartbeatService.buildRunOutputSilences.mock.calls[0]![0]).toHaveLength(50);
|
||||
});
|
||||
|
||||
it("treats explicit zero or invalid live run limit as the capped default", async () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { Ajv2020 } from "ajv/dist/2020.js";
|
||||
import { requestHumanInputAction } from "../../../packages/paperclip-runner/src/protocol-actions/request-human-input.js";
|
||||
import { toolInputVariantError } from "../../../packages/paperclip-runner/src/contracts/tool-input-variants.js";
|
||||
import { questionSetToAskUserQuestionsPayload } from "@paperclipai/shared";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { eq } from "drizzle-orm";
|
||||
@@ -500,7 +501,9 @@ const support = await getEmbeddedPostgresTestSupport();
|
||||
expect(questionSetToAskUserQuestionsPayload(result.providerQuestionSet!).questions).toEqual([result.providerQuestion]);
|
||||
expect(result.instruction).toContain("questionSet:providerQuestionSet");
|
||||
expect(result.instruction).not.toContain("do not add questionSet");
|
||||
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload: { version: 1 } })).toBe(false);
|
||||
// The advertised schema is a plain object; the questions rule is a server-checked variant.
|
||||
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload: { version: 1 } })
|
||||
&& toolInputVariantError("request_human_input", { ...input, payload: { version: 1 } }) === null).toBe(false);
|
||||
expect(ajv.validate(requestHumanInputAction.live.descriptor.inputSchema, { ...input, payload: { version: 1,
|
||||
questionSet: { ...result.providerQuestionSet, questions: [{ ...result.providerQuestionSet!.questions[0], answerMode: "text" }] } } })).toBe(false);
|
||||
expect(result.results.every((item) => item.state !== "ready")).toBe(true);
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { runnerImageExpectationProblem } from "../../../scripts/check-runner-image-expectation.mjs";
|
||||
|
||||
/**
|
||||
* Drift guard for the Docker build-stamp wiring.
|
||||
@@ -22,6 +25,8 @@ const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."
|
||||
const dockerfile = readFileSync(path.join(repoRoot, "Dockerfile"), "utf8");
|
||||
const workflow = readFileSync(path.join(repoRoot, ".github", "workflows", "docker.yml"), "utf8");
|
||||
const previewWorkflow = readFileSync(path.join(repoRoot, ".github", "workflows", "release.yml"), "utf8");
|
||||
const mergeGroupWorkflow = readFileSync(path.join(repoRoot, ".github", "workflows", "docker-merge-group.yml"), "utf8");
|
||||
const appCheckWorkflow = readFileSync(path.join(repoRoot, ".github", "workflows", "docker-app-check.yml"), "utf8");
|
||||
|
||||
/**
|
||||
* Return the text of the Dockerfile stage that starts at the named target.
|
||||
@@ -77,31 +82,101 @@ describe("docker build-stamp wiring", () => {
|
||||
});
|
||||
|
||||
|
||||
describe("Docker Rust dependency cache", () => {
|
||||
it("caches the locked dependency recipe separately from source and per-build metadata", () => {
|
||||
const chef = stageBody(dockerfile, "rust-chef");
|
||||
const planner = stageBody(dockerfile, "runner-plan");
|
||||
const dependencies = stageBody(dockerfile, "runner-deps");
|
||||
expect(chef).toContain("FROM rust-toolchain AS rust-chef");
|
||||
expect(chef).toMatch(/cargo install cargo-chef --version \d+\.\d+\.\d+ --locked/);
|
||||
expect(planner).toContain("COPY packages/paperclip-runner/runner ./runner");
|
||||
expect(planner).toContain("cargo chef prepare --recipe-path /tmp/runner-recipe.json");
|
||||
expect(dependencies).toContain("FROM rust-chef AS runner-deps");
|
||||
expect(dependencies).toContain("COPY --from=runner-plan /tmp/runner-recipe.json /tmp/runner-recipe.json");
|
||||
expect(dependencies).toContain("cargo chef cook --release --locked --package paperclip-runner-core --bin paperclip-runnerd");
|
||||
expect(dependencies).not.toMatch(/COPY .*\.\/runner|COPY .*\.\/protocol|COPY \. \.|PAPERCLIP_BUILD_COMMIT/);
|
||||
describe("Application image Runner", () => {
|
||||
it("takes the Runner build and its stamp from runner-artifacts, and checks them before any application build", () => {
|
||||
const build = stageBody(dockerfile, "build");
|
||||
expect(build).toContain("FROM base AS build");
|
||||
const source = build.search(/^COPY \. \.$/m);
|
||||
const output = build.search(/^COPY --from=runner-artifacts \/runner-package\/dist \/app\/packages\/paperclip-runner\/dist$/m);
|
||||
const stamp = build.search(
|
||||
/^COPY --from=runner-artifacts \/runner-package\/node_modules\/\.cache\/paperclip-runner-build-inputs\.json \/app\/packages\/paperclip-runner\/node_modules\/\.cache\/paperclip-runner-build-inputs\.json$/m,
|
||||
);
|
||||
const required = build.search(/^ENV PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT=1$/m);
|
||||
const check = build.search(/^RUN node server\/scripts\/prepare-runner-vendor\.mjs$/m);
|
||||
const firstBuild = build.search(/^RUN pnpm /m);
|
||||
expect(source).toBeGreaterThanOrEqual(0);
|
||||
expect(output).toBeGreaterThan(source);
|
||||
expect(stamp).toBeGreaterThan(source);
|
||||
expect(required).toBeGreaterThan(Math.max(output, stamp));
|
||||
expect(check).toBeGreaterThan(required);
|
||||
expect(firstBuild).toBeGreaterThan(check);
|
||||
});
|
||||
|
||||
it("rebuilds real workspace code and embedded protocol inputs after cooking dependencies", () => {
|
||||
const native = stageBody(dockerfile, "runner-build");
|
||||
expect(native).toContain("FROM runner-deps AS runner-build");
|
||||
for (const source of ["runner", "protocol"]) {
|
||||
expect(native.indexOf(`COPY packages/paperclip-runner/${source} ./${source}`))
|
||||
.toBeLessThan(native.indexOf("cargo build --release"));
|
||||
expect(native).toContain(`COPY packages/paperclip-runner/${source} ./${source}`);
|
||||
it("checks the Runner against the inputs digest a build names, before it vendors the Runner", () => {
|
||||
const build = stageBody(dockerfile, "build");
|
||||
const stamp = build.search(/^COPY --from=runner-artifacts \/runner-package\/node_modules\//m);
|
||||
const argument = build.search(/^ARG PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST=""$/m);
|
||||
const check = build.indexOf(
|
||||
"RUN --mount=type=bind,from=runner-artifacts,source=/runner-image.json,target=/tmp/runner-image.json \\\n"
|
||||
+ " node scripts/check-runner-image-expectation.mjs /tmp/runner-image.json\n",
|
||||
);
|
||||
const vendor = build.search(/^ENV PAPERCLIP_RUNNER_VENDOR_REQUIRE_CURRENT=1$/m);
|
||||
expect(stamp).toBeGreaterThanOrEqual(0);
|
||||
expect(argument).toBeGreaterThan(stamp);
|
||||
expect(check).toBeGreaterThan(argument);
|
||||
expect(vendor).toBeGreaterThan(check);
|
||||
expect(dockerfile.match(/PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST/g)).toHaveLength(1);
|
||||
expect(dockerfile).toMatch(/^ARG PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST(?:=.*)?$/m);
|
||||
});
|
||||
|
||||
const inputs = "1".repeat(64);
|
||||
const other = "2".repeat(64);
|
||||
const published = { publication: true, inputsDigest: { digest: inputs } };
|
||||
const inline = { publication: false, inputsDigest: { digest: inputs } };
|
||||
|
||||
it.each<[string, object | null, string, RegExp | null]>([
|
||||
["no expectation and an inline Runner", inline, "", null],
|
||||
["no expectation and a published Runner", published, "", null],
|
||||
["the published Runner of the expected inputs", published, inputs, null],
|
||||
["an inline Runner, even of the expected inputs", inline, inputs, /^PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST is 1{64}, but the runner-artifacts of this build are not a published Runner image\. Pass /],
|
||||
["a published Runner of other inputs", published, other, /^PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST is 2{64}, but the runner-artifacts of this build have the inputs 1{64}\. Pass /],
|
||||
["a published Runner that names no inputs", { publication: true }, inputs, /have the inputs \(none\)/],
|
||||
["a record that is not an object", null, inputs, /are not a published Runner image/],
|
||||
["an expectation that is not a digest", published, "inputs-latest", /must be the 64 hexadecimal characters of a Runner inputs digest, not "inputs-latest"/],
|
||||
])("answers for %s", (_label, image, expected, problem) => {
|
||||
const answer = runnerImageExpectationProblem(image, expected);
|
||||
if (problem === null) expect(answer).toBeNull();
|
||||
else expect(answer).toMatch(problem);
|
||||
});
|
||||
|
||||
it("runs as the build runs it: nothing is read without an expectation, and a mismatch fails with the reason", () => {
|
||||
const directory = mkdtempSync(path.join(tmpdir(), "runner-image-expectation-"));
|
||||
try {
|
||||
const file = path.join(directory, "runner-image.json");
|
||||
const run = (expected: string | null, target = file) => spawnSync(
|
||||
process.execPath,
|
||||
[path.join(repoRoot, "scripts", "check-runner-image-expectation.mjs"), target],
|
||||
{ encoding: "utf8", env: expected === null ? {} : { PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST: expected } },
|
||||
);
|
||||
expect(run(null, path.join(directory, "absent.json")).status).toBe(0);
|
||||
expect(run("", path.join(directory, "absent.json")).status).toBe(0);
|
||||
writeFileSync(file, JSON.stringify(inline));
|
||||
expect(run(inputs)).toMatchObject({ status: 1, stderr: expect.stringMatching(/^ERROR: PAPERCLIP_RUNNER_EXPECT_INPUTS_DIGEST is 1{64}, but .* are not a published Runner image/) });
|
||||
writeFileSync(file, JSON.stringify(published));
|
||||
expect(run(inputs)).toMatchObject({ status: 0, stderr: "" });
|
||||
expect(run(other).status).toBe(1);
|
||||
} finally {
|
||||
rmSync(directory, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("compiles the Runner only in the runner-artifacts stages", () => {
|
||||
const names = [...dockerfile.matchAll(/^FROM \S+ AS (\S+)$/gm)].map((match) => match[1]);
|
||||
const application = names.filter((name) => !name.startsWith("runner-artifacts"));
|
||||
expect(application).toEqual(["base", "deps", "build", "runner-provider-pack", "production", "cloud-plugins", "cloud-server-deps", "cloud"]);
|
||||
for (const name of application) {
|
||||
expect(stageBody(dockerfile, name), name).not.toMatch(/\b(?:cargo|rustup|rustc|gcc)\b/);
|
||||
}
|
||||
});
|
||||
|
||||
it("gives an inline Runner the build commit as its revision and no publication argument", () => {
|
||||
const runner = stageBody(dockerfile, "runner-artifacts-build");
|
||||
expect(runner).toContain('revision="${PAPERCLIP_RUNNER_SOURCE_REVISION:-${PAPERCLIP_BUILD_COMMIT}}";');
|
||||
for (const [name, source] of [["standard", workflow], ["preview", previewWorkflow], ["merge group", mergeGroupWorkflow], ["pull request", appCheckWorkflow]]) {
|
||||
expect(source, name).toContain("PAPERCLIP_BUILD_COMMIT=");
|
||||
expect(source, name).not.toMatch(/PAPERCLIP_RUNNER_(?:SOURCE_REVISION|IMAGE_PUBLICATION)/);
|
||||
expect(source, name).not.toMatch(/runner-artifacts|build-contexts?\b/);
|
||||
}
|
||||
expect(native).toContain("cargo build --release --manifest-path runner/Cargo.toml --locked -p paperclip-runner-core --bin paperclip-runnerd");
|
||||
expect(stageBody(dockerfile, "build")).toContain("FROM runner-build AS build");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -110,17 +185,25 @@ describe("Standard image remote provider pack", () => {
|
||||
it("ships the build-owned pack in the production base used by downstream images", () => {
|
||||
const pack = stageBody(dockerfile, "runner-provider-pack");
|
||||
const production = stageBody(dockerfile, "production");
|
||||
expect(pack).toContain("FROM build AS runner-provider-pack");
|
||||
expect(pack).toContain('PAPERCLIP_RUNNER_SOURCE_REVISION="${PAPERCLIP_BUILD_COMMIT}"');
|
||||
expect(pack).toContain("build-provider-pack.mjs /provider-pack");
|
||||
expect(pack).toContain('if [ -n "${PAPERCLIP_BUILD_COMMIT}" ]; then');
|
||||
const runner = stageBody(dockerfile, "runner-artifacts-build");
|
||||
expect(pack).toContain("FROM base AS runner-provider-pack");
|
||||
expect(pack).toContain("RUN --mount=type=bind,from=runner-artifacts,target=/runner-artifacts \\\n");
|
||||
expect(pack).toContain("if [ -f /runner-artifacts/provider-pack/provider-pack.json ]; then");
|
||||
expect(pack).toContain("cp -a /runner-artifacts/provider-pack/. /provider-pack/");
|
||||
expect(pack).toContain("cp -a /runner-artifacts/provider-pack.archives /runner-artifacts/provider-pack.archive.json /provider-pack-transport/;");
|
||||
expect(pack).toContain("mkdir -p /provider-pack");
|
||||
expect(pack).toContain("Skipping remote provider pack");
|
||||
expect(production.match(/^COPY .*--from=runner-provider-pack .*$/gm)).toEqual([
|
||||
"COPY --link --chown=0:0 --from=runner-provider-pack /provider-pack-large/ /opt/paperclip-runner/provider-pack/",
|
||||
"COPY --chown=0:0 --from=runner-provider-pack /provider-pack /opt/paperclip-runner/provider-pack",
|
||||
"COPY --from=runner-provider-pack /provider-pack-transport/ /opt/paperclip-runner/",
|
||||
]);
|
||||
expect(production).toContain("--from=runner-provider-pack /provider-pack /opt/paperclip-runner/provider-pack");
|
||||
expect(production).not.toContain("--chown=node:node --from=runner-provider-pack");
|
||||
// Modes are granted in the layer that writes the pack. A recursive chmod
|
||||
// after the COPY duplicates every changed file into another image layer.
|
||||
expect(pack).toMatch(/build-provider-pack\.mjs[\s\S]*&& chmod -R a\+rX \/provider-pack$/m);
|
||||
expect(runner).toMatch(/build-provider-pack\.mjs \/out\/provider-pack;[\s\S]*chmod -R a\+rX \/out;/);
|
||||
expect(pack).not.toContain("chmod");
|
||||
expect(production).not.toMatch(/chmod -R [^\n]*\/opt\/paperclip-runner\/provider-pack/);
|
||||
expect(production).toContain("gosu 65534:65534 node");
|
||||
expect(production).toContain("Object.values(manifest.payload.artifacts)");
|
||||
@@ -134,7 +217,7 @@ describe("Standard image remote provider pack", () => {
|
||||
expect(cloud).toContain("FROM production AS cloud");
|
||||
expect(cloud).not.toContain("/opt/paperclip-runner/provider-pack");
|
||||
expect(cloud).not.toContain("PAPERCLIP_RUNNER_REMOTE_PROVIDER_PACK_PATH");
|
||||
expect(dockerfile.match(/build-provider-pack\.mjs \/provider-pack/g)).toHaveLength(1);
|
||||
expect(dockerfile.match(/build-provider-pack\.mjs/g)).toHaveLength(1);
|
||||
expect(previewWorkflow).toMatch(/^\s*target: cloud$/m);
|
||||
});
|
||||
});
|
||||
@@ -36,13 +36,13 @@ it("copies installed dependencies as their own layer, before the per-commit app
|
||||
|
||||
it("copies the large provider-pack files as a linked layer with fixed timestamps", () => {
|
||||
const pack = stageBody("runner-provider-pack");
|
||||
const archive = pack.indexOf("create-provider-pack-archive.mjs");
|
||||
const copy = pack.indexOf("cp -a /runner-artifacts/provider-pack/. /provider-pack/");
|
||||
const split = pack.indexOf("mv \"$1\" \"/provider-pack-large/$1\"");
|
||||
const timestamps = pack.indexOf("find /provider-pack-large -exec touch -h -d @0 {} +");
|
||||
// The transport archive reads the whole pack, so the split must follow it.
|
||||
expect(archive).toBeGreaterThanOrEqual(0);
|
||||
expect(split).toBeGreaterThan(archive);
|
||||
expect(copy).toBeGreaterThanOrEqual(0);
|
||||
expect(split).toBeGreaterThan(copy);
|
||||
expect(timestamps).toBeGreaterThan(split);
|
||||
expect(pack.match(/^RUN /gm)).toHaveLength(1);
|
||||
|
||||
const production = stageBody("production");
|
||||
const large = production.search(
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import express from "express";
|
||||
import request from "supertest";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
|
||||
import { heartbeatRunWatchdogDecisions, heartbeatRuns, issues, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
||||
import { agentRoutes } from "../routes/agents.js";
|
||||
import { errorHandler } from "../middleware/index.js";
|
||||
import { authorizationService, type AuthorizationActor } from "../services/authorization.js";
|
||||
import {
|
||||
canActorReadHeartbeatRun, getHeartbeatRunReadDecisions, redactHeartbeatRunListRow,
|
||||
} from "../services/heartbeat-run-privacy.js";
|
||||
import {
|
||||
ACTIVE_RUN_OUTPUT_CRITICAL_THRESHOLD_MS, ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS, recoveryService,
|
||||
} from "../services/recovery/service.js";
|
||||
import { describeEmbeddedPostgres, useEmbeddedPostgres } from "./helpers/route-test-harness.js";
|
||||
import {
|
||||
ISSUE_READ_VISIBILITY_ACTORS, seedIssueReadVisibilityFixture, type IssueReadVisibilityActorName,
|
||||
type IssueReadVisibilityFixture,
|
||||
} from "./helpers/issue-read-visibility-fixture.js";
|
||||
|
||||
const NOW = new Date("2026-11-13T12:00:00.000Z");
|
||||
const HOUR = 60 * 60 * 1000;
|
||||
|
||||
type RunBinding = { id: string; companyId: string; scopeKind: "company" | "issue"; issueId: string | null };
|
||||
|
||||
describeEmbeddedPostgres("live runs read in a bounded number of statements", () => {
|
||||
const ctx = useEmbeddedPostgres("paperclip-live-runs-batch-");
|
||||
const oldPrivacy = process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
|
||||
let f: IssueReadVisibilityFixture;
|
||||
let runs: RunBinding[];
|
||||
let foreignRuns: RunBinding[];
|
||||
let silenceRunIds: Record<"noOutput" | "snoozed" | "expiredSnooze" | "dismissed" | "recent" | "evaluated" | "doneEvaluation" | "queued", string>;
|
||||
|
||||
let order = 0;
|
||||
async function insertRun(input: {
|
||||
companyId: string; agentId: string; issueId?: string | null; scopeKind?: "company" | "issue";
|
||||
status?: string; lastOutputAt?: Date | null; lastOutputSeq?: number; lastOutputStream?: string | null;
|
||||
}) {
|
||||
const id = randomUUID();
|
||||
order += 1;
|
||||
const scopeKind = input.scopeKind ?? (input.issueId ? "issue" : "company");
|
||||
await ctx.db.insert(heartbeatRuns).values({
|
||||
id, companyId: input.companyId, agentId: input.agentId, scopeKind, issueId: input.issueId ?? null,
|
||||
status: input.status ?? "running", startedAt: new Date(NOW.getTime() - 3 * HOUR),
|
||||
createdAt: new Date(NOW.getTime() - 3 * HOUR - order * 1000), lastOutputAt: input.lastOutputAt ?? null,
|
||||
lastOutputSeq: input.lastOutputSeq ?? 0, lastOutputStream: input.lastOutputStream ?? null,
|
||||
usageJson: { inputTokens: 11, cachedInputTokens: 2, outputTokens: 7 }, resultJson: { costUsd: 0.42, summary: "secret summary" },
|
||||
contextSnapshot: input.issueId ? { issueId: input.issueId } : {},
|
||||
});
|
||||
return { id, companyId: input.companyId, scopeKind, issueId: input.issueId ?? null } satisfies RunBinding;
|
||||
}
|
||||
|
||||
async function seedRuns(fixture: IssueReadVisibilityFixture, openTaskRuns: number) {
|
||||
const agentIds = [fixture.readerAgentId, fixture.assigneeAgentId, fixture.lowTrustAgentId];
|
||||
const taskIds = [
|
||||
...Array.from({ length: openTaskRuns }, (_, index) => fixture.publicIds[index % fixture.publicIds.length]!),
|
||||
...fixture.ownedPrivateIds, ...fixture.grantedPrivateIds, ...fixture.assignedPrivateIds, ...fixture.unreadablePrivateIds,
|
||||
...fixture.privateProjectIssueIds, fixture.hiddenId,
|
||||
];
|
||||
const seeded: RunBinding[] = [];
|
||||
for (const [index, issueId] of taskIds.entries()) {
|
||||
seeded.push(await insertRun({ companyId: fixture.companyId, agentId: agentIds[index % agentIds.length]!, issueId }));
|
||||
}
|
||||
seeded.push(await insertRun({ companyId: fixture.companyId, agentId: fixture.readerAgentId }));
|
||||
const doomedTaskId = randomUUID();
|
||||
await ctx.db.insert(issues).values({ id: doomedTaskId, companyId: fixture.companyId, title: "Deleted", status: "todo" });
|
||||
const orphan = await insertRun({ companyId: fixture.companyId, agentId: fixture.assigneeAgentId, issueId: doomedTaskId });
|
||||
await ctx.db.delete(issues).where(eq(issues.id, doomedTaskId));
|
||||
seeded.push({ ...orphan, issueId: null });
|
||||
return seeded;
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = "enforce";
|
||||
f = await seedIssueReadVisibilityFixture(ctx.db, { publicCount: 12 });
|
||||
runs = await seedRuns(f, 3);
|
||||
foreignRuns = [
|
||||
await insertRun({ companyId: f.foreignCompanyId, agentId: f.foreignAgentId, issueId: f.foreignIds[0]! }),
|
||||
await insertRun({ companyId: f.foreignCompanyId, agentId: f.foreignAgentId, issueId: f.foreignIds[1]! }),
|
||||
await insertRun({ companyId: f.foreignCompanyId, agentId: f.foreignAgentId }),
|
||||
];
|
||||
const silenceRun = (extra: Partial<Parameters<typeof insertRun>[0]>) =>
|
||||
insertRun({ companyId: f.companyId, agentId: f.readerAgentId, ...extra });
|
||||
silenceRunIds = {
|
||||
noOutput: (await silenceRun({})).id,
|
||||
snoozed: (await silenceRun({ lastOutputAt: new Date(NOW.getTime() - 2 * HOUR), lastOutputSeq: 4, lastOutputStream: "stdout" })).id,
|
||||
expiredSnooze: (await silenceRun({ lastOutputAt: new Date(NOW.getTime() - 2 * HOUR), lastOutputSeq: 2, lastOutputStream: "stderr" })).id,
|
||||
dismissed: (await silenceRun({ lastOutputAt: new Date(NOW.getTime() - 5 * HOUR), lastOutputSeq: 9, lastOutputStream: "other" })).id,
|
||||
recent: (await silenceRun({ lastOutputAt: new Date(NOW.getTime() - 10 * 60 * 1000), lastOutputSeq: 1, lastOutputStream: "stdout" })).id,
|
||||
evaluated: (await silenceRun({})).id,
|
||||
doneEvaluation: (await silenceRun({})).id,
|
||||
queued: (await silenceRun({ status: "queued" })).id,
|
||||
};
|
||||
await ctx.db.insert(heartbeatRunWatchdogDecisions).values([
|
||||
{ companyId: f.companyId, runId: silenceRunIds.snoozed, decision: "snooze", snoozedUntil: new Date(NOW.getTime() + HOUR), createdAt: new Date(NOW.getTime() - 2 * HOUR) },
|
||||
{ companyId: f.companyId, runId: silenceRunIds.snoozed, decision: "continue", snoozedUntil: new Date(NOW.getTime() + 2 * HOUR), createdAt: new Date(NOW.getTime() - HOUR) },
|
||||
{ companyId: f.companyId, runId: silenceRunIds.expiredSnooze, decision: "snooze", snoozedUntil: new Date(NOW.getTime() - HOUR) },
|
||||
{ companyId: f.companyId, runId: silenceRunIds.dismissed, decision: "dismissed_false_positive" },
|
||||
{ companyId: f.companyId, runId: silenceRunIds.dismissed, decision: "snooze", snoozedUntil: new Date(NOW.getTime() + HOUR) },
|
||||
]);
|
||||
const evaluationId = randomUUID();
|
||||
await ctx.db.insert(issues).values([
|
||||
{ id: evaluationId, companyId: f.companyId, title: "Evaluate", status: "todo", identifier: "EVAL-1",
|
||||
assigneeAgentId: f.assigneeAgentId, originKind: "stale_active_run_evaluation", originId: silenceRunIds.evaluated },
|
||||
{ companyId: f.companyId, title: "Evaluated before", status: "done", originKind: "stale_active_run_evaluation", originId: silenceRunIds.doneEvaluation },
|
||||
{ companyId: f.foreignCompanyId, title: "Foreign evaluation", status: "todo", originKind: "stale_active_run_evaluation", originId: silenceRunIds.noOutput },
|
||||
]);
|
||||
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
||||
afterAll(() => {
|
||||
if (oldPrivacy === undefined) delete process.env.PAPERCLIP_ISSUE_PRIVACY_MODE;
|
||||
else process.env.PAPERCLIP_ISSUE_PRIVACY_MODE = oldPrivacy;
|
||||
});
|
||||
afterEach(() => { vi.useRealTimers(); });
|
||||
|
||||
function app(actor: AuthorizationActor, db = ctx.db) {
|
||||
const result = express();
|
||||
result.use(express.json());
|
||||
result.use((req, _res, next) => { req.actor = { ...actor } as Express.Request["actor"]; next(); });
|
||||
result.use("/api", agentRoutes(db, {} as never));
|
||||
result.use(errorHandler);
|
||||
return result;
|
||||
}
|
||||
function recording() {
|
||||
const statements: string[] = [];
|
||||
const db = drizzle(ctx.db.$client, {
|
||||
schema: ctx.db._.fullSchema, logger: { logQuery: (query) => statements.push(query) },
|
||||
}) as unknown as typeof ctx.db;
|
||||
return { db, statements };
|
||||
}
|
||||
async function liveRuns(actor: AuthorizationActor, companyId = f.companyId, db = ctx.db) {
|
||||
return request(app(actor, db)).get(`/api/companies/${companyId}/live-runs`);
|
||||
}
|
||||
const readEach = (actor: AuthorizationActor, bindings: RunBinding[]) =>
|
||||
Promise.all(bindings.map((run) => canActorReadHeartbeatRun(ctx.db, authorizationService(ctx.db), { ...actor }, run)));
|
||||
|
||||
it.each(ISSUE_READ_VISIBILITY_ACTORS)("decides every run read for %s exactly as one check per run does", async (name) => {
|
||||
const actor = f.actors[name];
|
||||
const bindings = [...runs, ...foreignRuns, ...foreignRuns.map((run) => ({ ...run, companyId: f.companyId }))];
|
||||
const batched = await getHeartbeatRunReadDecisions(ctx.db, authorizationService(ctx.db), { ...actor }, bindings);
|
||||
expect(batched).toEqual(await readEach(actor, bindings));
|
||||
});
|
||||
|
||||
it("covers readable and unreadable runs in the fixture", async () => {
|
||||
const decisions = async (name: IssueReadVisibilityActorName) => readEach(f.actors[name], runs);
|
||||
expect((await decisions("instance admin")).filter(Boolean).length).toBeGreaterThan((await decisions("board member")).filter(Boolean).length);
|
||||
expect(await decisions("board member")).toContain(false);
|
||||
expect(await decisions("board member")).toContain(true);
|
||||
expect(await decisions("agent key")).toContain(false);
|
||||
expect(runs.at(-1)).toMatchObject({ scopeKind: "issue", issueId: null });
|
||||
expect(await readEach(f.actors["instance admin"], [runs.at(-1)!])).toEqual([false]);
|
||||
});
|
||||
|
||||
it.each(ISSUE_READ_VISIBILITY_ACTORS)("returns %s the live runs one check per run would, redacting the rest field by field", async (name) => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(NOW);
|
||||
const actor = f.actors[name];
|
||||
const res = await liveRuns(actor);
|
||||
if (res.status !== 200) {
|
||||
expect([401, 403]).toContain(res.status);
|
||||
for (const run of runs) expect(JSON.stringify(res.body)).not.toContain(run.id);
|
||||
return;
|
||||
}
|
||||
const full = await liveRuns(f.actors["local implicit board"]);
|
||||
expect(full.status).toBe(200);
|
||||
const fullById = new Map((full.body as Array<Record<string, unknown> & { id: string }>).map((row) => [row.id, row]));
|
||||
const body = res.body as Array<Record<string, unknown> & { id: string; scopeKind?: string }>;
|
||||
expect(body.map((row) => row.id)).toEqual([...fullById.keys()]);
|
||||
const bindings = body.map((row) => {
|
||||
const source = fullById.get(row.id)!;
|
||||
return { id: row.id, companyId: f.companyId, scopeKind: source.scopeKind as "company" | "issue", issueId: (source.issueId as string | null) ?? null };
|
||||
});
|
||||
const expected = await readEach(actor, bindings);
|
||||
for (const [index, row] of body.entries()) {
|
||||
const source = fullById.get(row.id)!;
|
||||
if (expected[index]) {
|
||||
expect(row.redacted).toBeUndefined();
|
||||
expect(row.outputSilence).toEqual(source.outputSilence);
|
||||
expect(row.issueId).toEqual(source.issueId);
|
||||
} else {
|
||||
expect(row).toEqual(JSON.parse(JSON.stringify(redactHeartbeatRunListRow(source))));
|
||||
}
|
||||
}
|
||||
expect(expected).toContain(true);
|
||||
});
|
||||
|
||||
it("builds each run's output silence as the single-run reader does, including runs with no output yet", async () => {
|
||||
vi.useFakeTimers({ toFake: ["Date"] });
|
||||
vi.setSystemTime(NOW);
|
||||
const res = await liveRuns(f.actors["local implicit board"]);
|
||||
expect(res.status).toBe(200);
|
||||
const byId = new Map((res.body as Array<{ id: string; outputSilence: unknown }>).map((row) => [row.id, row.outputSilence]));
|
||||
const recovery = recoveryService(ctx.db, { enqueueWakeup: vi.fn() } as never);
|
||||
const rows = await ctx.db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, f.companyId));
|
||||
const single = new Map(await Promise.all(rows.map(async (run) => [run.id, JSON.parse(JSON.stringify(await recovery.buildRunOutputSilence(run, NOW)))] as const)));
|
||||
for (const [id, silence] of byId) {
|
||||
if (silence !== undefined) expect(silence).toEqual(single.get(id));
|
||||
}
|
||||
const thresholds = { suspicionThresholdMs: ACTIVE_RUN_OUTPUT_SUSPICION_THRESHOLD_MS, criticalThresholdMs: ACTIVE_RUN_OUTPUT_CRITICAL_THRESHOLD_MS };
|
||||
const silenceOf = (id: string) => single.get(id) as Record<string, unknown>;
|
||||
expect(silenceOf(silenceRunIds.noOutput)).toEqual({
|
||||
lastOutputAt: null, lastOutputSeq: 0, lastOutputStream: null,
|
||||
silenceStartedAt: new Date(NOW.getTime() - 3 * HOUR).toISOString(), silenceAgeMs: 3 * HOUR, level: "critical", ...thresholds,
|
||||
snoozedUntil: null, evaluationIssueId: null, evaluationIssueIdentifier: null, evaluationIssueAssigneeAgentId: null,
|
||||
});
|
||||
expect(silenceOf(silenceRunIds.snoozed)).toMatchObject({
|
||||
lastOutputSeq: 4, lastOutputStream: "stdout", level: "snoozed", snoozedUntil: new Date(NOW.getTime() + 2 * HOUR).toISOString(),
|
||||
});
|
||||
expect(silenceOf(silenceRunIds.expiredSnooze)).toMatchObject({ lastOutputStream: "stderr", level: "critical", snoozedUntil: null });
|
||||
expect(silenceOf(silenceRunIds.dismissed)).toMatchObject({ lastOutputStream: null, level: "not_applicable", snoozedUntil: null });
|
||||
expect(silenceOf(silenceRunIds.recent)).toMatchObject({ level: "suspicious", silenceAgeMs: 10 * 60 * 1000 });
|
||||
expect(silenceOf(silenceRunIds.evaluated)).toMatchObject({ evaluationIssueIdentifier: "EVAL-1", evaluationIssueAssigneeAgentId: f.assigneeAgentId });
|
||||
expect(silenceOf(silenceRunIds.doneEvaluation)).toMatchObject({ evaluationIssueId: null });
|
||||
expect(silenceOf(silenceRunIds.queued)).toMatchObject({ level: "not_applicable", silenceAgeMs: null });
|
||||
|
||||
const batched = await recovery.buildRunOutputSilences([...rows, ...rows.slice(0, 2)], NOW);
|
||||
expect(batched.map((silence) => JSON.parse(JSON.stringify(silence))))
|
||||
.toEqual([...rows, ...rows.slice(0, 2)].map((run) => single.get(run.id)));
|
||||
expect(await recovery.buildRunOutputSilences([], NOW)).toEqual([]);
|
||||
const missing = rows.find((run) => run.id === silenceRunIds.noOutput)!;
|
||||
expect(JSON.parse(JSON.stringify(await recovery.buildRunOutputSilence({ ...missing, id: randomUUID() }, NOW))))
|
||||
.toEqual(silenceOf(silenceRunIds.noOutput));
|
||||
});
|
||||
|
||||
it.each([
|
||||
"board owner", "board member", "instance admin", "local implicit board", "agent key", "agent run for operator",
|
||||
] as const)("sends the same number of statements for %s whether 19 or 49 runs are live", async (name) => {
|
||||
const small = await seedIssueReadVisibilityFixture(ctx.db, { publicCount: 12 });
|
||||
const large = await seedIssueReadVisibilityFixture(ctx.db, { publicCount: 12 });
|
||||
const smallRuns = await seedRuns(small, 0);
|
||||
const largeRuns = await seedRuns(large, 30);
|
||||
const actorFor = (fixture: IssueReadVisibilityFixture) => fixture.actors[name];
|
||||
const first = recording();
|
||||
const smallRes = await liveRuns(actorFor(small), small.companyId, first.db);
|
||||
const second = recording();
|
||||
const largeRes = await liveRuns(actorFor(large), large.companyId, second.db);
|
||||
expect(smallRes.status).toBe(200);
|
||||
expect(largeRes.status).toBe(200);
|
||||
expect(smallRes.body).toHaveLength(smallRuns.length + 1);
|
||||
expect(largeRes.body).toHaveLength(largeRuns.length + 1);
|
||||
expect(second.statements.length).toBe(first.statements.length);
|
||||
expect(second.statements.length).toBeLessThanOrEqual(24);
|
||||
});
|
||||
});
|
||||
@@ -312,9 +312,14 @@ describe("Runner image stages", () => {
|
||||
]);
|
||||
// `docker build .` builds the last stage.
|
||||
expect(names.at(-1)).toBe("cloud");
|
||||
for (const stage of stages) {
|
||||
if (!stage.name.startsWith("runner-artifacts")) expect(stage.lines.join("\n"), stage.name).not.toMatch(/runner-artifacts/);
|
||||
const application = stages.filter((stage) => !stage.name.startsWith("runner-artifacts"));
|
||||
for (const stage of application) {
|
||||
expect(stage.from, stage.name).not.toMatch(/^runner-artifacts/);
|
||||
const read = [...stage.lines.join("\n").matchAll(/from=(runner-artifacts[a-z-]*)/g)].map((match) => match[1]);
|
||||
expect(read.filter((name) => name !== "runner-artifacts"), stage.name).toEqual([]);
|
||||
}
|
||||
expect(application.filter((stage) => /from=runner-artifacts/.test(stage.lines.join("\n"))).map((stage) => stage.name))
|
||||
.toEqual(["build", "runner-provider-pack"]);
|
||||
});
|
||||
|
||||
it("name the published image in the pack only for a publication build, which is off by default", () => {
|
||||
|
||||
@@ -31,7 +31,7 @@ import {
|
||||
import { issueRecoveryActionService } from "../../../services/issue-recovery-actions.js";
|
||||
import { RECOVERY_ORIGIN_KINDS } from "../../../services/recovery/origins.js";
|
||||
import { isTerminalIssueStatus } from "../domain/policy.js";
|
||||
import type { WatchdogRunReader, WatchdogWriter } from "../application/ports.js";
|
||||
import type { FindLatestDecisionResult, WatchdogRunReader, WatchdogWriter } from "../application/ports.js";
|
||||
import type {
|
||||
EvaluationIssueSnapshot,
|
||||
FoldOutcome,
|
||||
@@ -159,10 +159,14 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
|
||||
return row?.pending ?? true;
|
||||
}
|
||||
|
||||
async function findLatestDecision(companyId: string, runId: string, now: Date) {
|
||||
async function findLatestDecisions(companyId: string, runIds: readonly string[], now: Date) {
|
||||
const ids = [...new Set(runIds)];
|
||||
const result = new Map<string, FindLatestDecisionResult>();
|
||||
if (ids.length === 0) return result;
|
||||
const [quietUntilRows, dismissedRows] = await Promise.all([
|
||||
db
|
||||
.select({
|
||||
.selectDistinctOn([heartbeatRunWatchdogDecisions.runId], {
|
||||
runId: heartbeatRunWatchdogDecisions.runId,
|
||||
decision: heartbeatRunWatchdogDecisions.decision,
|
||||
snoozedUntil: heartbeatRunWatchdogDecisions.snoozedUntil,
|
||||
})
|
||||
@@ -170,32 +174,39 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
|
||||
.where(
|
||||
and(
|
||||
eq(heartbeatRunWatchdogDecisions.companyId, companyId),
|
||||
eq(heartbeatRunWatchdogDecisions.runId, runId),
|
||||
inArray(heartbeatRunWatchdogDecisions.runId, ids),
|
||||
inArray(heartbeatRunWatchdogDecisions.decision, ["snooze", "continue"]),
|
||||
gt(heartbeatRunWatchdogDecisions.snoozedUntil, now),
|
||||
),
|
||||
)
|
||||
.orderBy(desc(heartbeatRunWatchdogDecisions.createdAt))
|
||||
.limit(1),
|
||||
.orderBy(heartbeatRunWatchdogDecisions.runId, desc(heartbeatRunWatchdogDecisions.createdAt)),
|
||||
db
|
||||
.select({ id: heartbeatRunWatchdogDecisions.id })
|
||||
.selectDistinct({ runId: heartbeatRunWatchdogDecisions.runId })
|
||||
.from(heartbeatRunWatchdogDecisions)
|
||||
.where(
|
||||
and(
|
||||
eq(heartbeatRunWatchdogDecisions.companyId, companyId),
|
||||
eq(heartbeatRunWatchdogDecisions.runId, runId),
|
||||
inArray(heartbeatRunWatchdogDecisions.runId, ids),
|
||||
eq(heartbeatRunWatchdogDecisions.decision, "dismissed_false_positive"),
|
||||
),
|
||||
)
|
||||
.limit(1),
|
||||
),
|
||||
]);
|
||||
const quietUntilRow = quietUntilRows[0];
|
||||
return {
|
||||
dismissedFalsePositive: dismissedRows.length > 0,
|
||||
quietUntilDecision: quietUntilRow && quietUntilRow.snoozedUntil
|
||||
? { decision: quietUntilRow.decision as "snooze" | "continue", snoozedUntil: quietUntilRow.snoozedUntil }
|
||||
: null,
|
||||
};
|
||||
const quietUntilByRun = new Map(quietUntilRows.map((row) => [row.runId, row]));
|
||||
const dismissed = new Set(dismissedRows.map((row) => row.runId));
|
||||
for (const runId of ids) {
|
||||
const quietUntilRow = quietUntilByRun.get(runId);
|
||||
result.set(runId, {
|
||||
dismissedFalsePositive: dismissed.has(runId),
|
||||
quietUntilDecision: quietUntilRow && quietUntilRow.snoozedUntil
|
||||
? { decision: quietUntilRow.decision as "snooze" | "continue", snoozedUntil: quietUntilRow.snoozedUntil }
|
||||
: null,
|
||||
});
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
async function findLatestDecision(companyId: string, runId: string, now: Date): Promise<FindLatestDecisionResult> {
|
||||
return (await findLatestDecisions(companyId, [runId], now)).get(runId)!;
|
||||
}
|
||||
|
||||
function selectEvaluationIssueSnapshot() {
|
||||
@@ -211,21 +222,29 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
|
||||
};
|
||||
}
|
||||
|
||||
async function findOpenStaleRunEvaluation(companyId: string, runId: string): Promise<EvaluationIssueSnapshot | null> {
|
||||
const [row] = await db
|
||||
.select(selectEvaluationIssueSnapshot())
|
||||
async function findOpenStaleRunEvaluations(companyId: string, runIds: readonly string[]) {
|
||||
const ids = [...new Set(runIds)];
|
||||
const result = new Map<string, EvaluationIssueSnapshot>();
|
||||
if (ids.length === 0) return result;
|
||||
const rows = await db
|
||||
.selectDistinctOn([issues.originId], selectEvaluationIssueSnapshot())
|
||||
.from(issues)
|
||||
.where(
|
||||
and(
|
||||
eq(issues.companyId, companyId),
|
||||
eq(issues.originKind, STALE_ACTIVE_RUN_EVALUATION_ORIGIN_KIND),
|
||||
eq(issues.originId, runId),
|
||||
inArray(issues.originId, ids),
|
||||
visibleIssueCondition(),
|
||||
notInArray(issues.status, ["done", "cancelled"]),
|
||||
),
|
||||
)
|
||||
.limit(1);
|
||||
return row ?? null;
|
||||
.orderBy(issues.originId);
|
||||
for (const row of rows) if (row.originId) result.set(row.originId, row);
|
||||
return result;
|
||||
}
|
||||
|
||||
async function findOpenStaleRunEvaluation(companyId: string, runId: string): Promise<EvaluationIssueSnapshot | null> {
|
||||
return (await findOpenStaleRunEvaluations(companyId, [runId])).get(runId) ?? null;
|
||||
}
|
||||
|
||||
async function findEvaluationIssueById(companyId: string, issueId: string): Promise<EvaluationIssueSnapshot | null> {
|
||||
@@ -532,7 +551,9 @@ export function createPostgresWatchdogAdapter(db: Db): WatchdogRunReader & Watch
|
||||
findRunForCompany,
|
||||
isRuntimeSettlementPending,
|
||||
findLatestDecision,
|
||||
findLatestDecisions,
|
||||
findOpenStaleRunEvaluation,
|
||||
findOpenStaleRunEvaluations,
|
||||
findEvaluationIssueById,
|
||||
findLatestSameRunTerminalEvidence,
|
||||
findSourceIssue,
|
||||
|
||||
@@ -56,7 +56,9 @@ export interface WatchdogRunReader {
|
||||
findRunForCompany(companyId: string, runId: string): Promise<RunSnapshot | null>;
|
||||
isRuntimeSettlementPending(companyId: string, runId: string): Promise<boolean>;
|
||||
findLatestDecision(companyId: string, runId: string, now: Date): Promise<FindLatestDecisionResult>;
|
||||
findLatestDecisions(companyId: string, runIds: readonly string[], now: Date): Promise<Map<string, FindLatestDecisionResult>>;
|
||||
findOpenStaleRunEvaluation(companyId: string, runId: string): Promise<EvaluationIssueSnapshot | null>;
|
||||
findOpenStaleRunEvaluations(companyId: string, runIds: readonly string[]): Promise<Map<string, EvaluationIssueSnapshot>>;
|
||||
findLatestSameRunTerminalEvidence(
|
||||
companyId: string,
|
||||
input: FindLatestSameRunTerminalEvidenceInput,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
createBuildRunOutputSilence,
|
||||
createBuildRunOutputSilences,
|
||||
createFoldSourceResolvedRun,
|
||||
createRecordWatchdogDecision,
|
||||
createScanSilentActiveRuns,
|
||||
@@ -35,18 +36,29 @@ describe("application", () => {
|
||||
}
|
||||
|
||||
function makeReader(overrides: Partial<WatchdogRunReader> = {}): WatchdogRunReader {
|
||||
return {
|
||||
const reader: WatchdogRunReader = {
|
||||
findCandidateSilentRuns: async () => [],
|
||||
findRunForCompany: async () => null,
|
||||
isRuntimeSettlementPending: async () => false,
|
||||
findLatestDecision: async () => ({ quietUntilDecision: null, dismissedFalsePositive: false }),
|
||||
findLatestDecisions: async (companyId, runIds, now) => new Map(await Promise.all(runIds.map(async (runId) =>
|
||||
[runId, await reader.findLatestDecision(companyId, runId, now)] as const))),
|
||||
findOpenStaleRunEvaluation: async () => null,
|
||||
findOpenStaleRunEvaluations: async (companyId, runIds) => {
|
||||
const found = new Map();
|
||||
for (const runId of runIds) {
|
||||
const evaluation = await reader.findOpenStaleRunEvaluation(companyId, runId);
|
||||
if (evaluation) found.set(runId, evaluation);
|
||||
}
|
||||
return found;
|
||||
},
|
||||
findLatestSameRunTerminalEvidence: async () => null,
|
||||
findSourceIssue: async () => null,
|
||||
findRunningAgent: async () => null,
|
||||
findEvaluationIssueById: async () => null,
|
||||
...overrides,
|
||||
};
|
||||
return reader;
|
||||
}
|
||||
|
||||
describe("createBuildRunOutputSilence", () => {
|
||||
@@ -105,6 +117,33 @@ describe("application", () => {
|
||||
expect(summary).toMatchObject({ level: "snoozed", snoozedUntil });
|
||||
});
|
||||
|
||||
it("reads decisions and evaluations once per company for a batch, defaulting runs the reader omits", async () => {
|
||||
const now = new Date("2026-01-01T05:00:00.000Z");
|
||||
const calls: string[] = [];
|
||||
const reader = makeReader({
|
||||
findLatestDecisions: async (companyId, runIds) => {
|
||||
calls.push(`decisions ${companyId} ${runIds.join(",")}`);
|
||||
return new Map();
|
||||
},
|
||||
findOpenStaleRunEvaluations: async (companyId, runIds) => {
|
||||
calls.push(`evaluations ${companyId} ${runIds.join(",")}`);
|
||||
return new Map();
|
||||
},
|
||||
});
|
||||
const deps = { reader, suspicionThresholdMs: SUSPICION_THRESHOLD_MS, criticalThresholdMs: CRITICAL_THRESHOLD_MS };
|
||||
const runs = [makeRun({ id: "run-1" }), makeRun({ id: "run-2", companyId: "company-2" }), makeRun({ id: "run-3" })];
|
||||
|
||||
const summaries = await createBuildRunOutputSilences(deps)(runs, now);
|
||||
|
||||
expect(calls.sort()).toEqual([
|
||||
"decisions company-1 run-1,run-3", "decisions company-2 run-2",
|
||||
"evaluations company-1 run-1,run-3", "evaluations company-2 run-2",
|
||||
]);
|
||||
const single = await createBuildRunOutputSilence({ ...deps, reader: makeReader() })(makeRun(), now);
|
||||
expect(summaries).toEqual([single, single, single]);
|
||||
expect(single).toMatchObject({ level: "critical", snoozedUntil: null, evaluationIssueId: null, lastOutputAt: null, lastOutputSeq: 0 });
|
||||
});
|
||||
|
||||
it("reports not_applicable for a run that is not running", async () => {
|
||||
const now = new Date("2026-01-01T05:00:00.000Z");
|
||||
const run = makeRun({ status: "succeeded" });
|
||||
|
||||
@@ -31,43 +31,68 @@ export type BuildRunOutputSilenceRunInput = Pick<
|
||||
"id" | "companyId" | "status" | "lastOutputAt" | "lastOutputSeq" | "lastOutputStream" | "processStartedAt" | "startedAt" | "createdAt"
|
||||
>;
|
||||
|
||||
export function createBuildRunOutputSilences(deps: BuildRunOutputSilenceDeps) {
|
||||
return async function buildRunOutputSilences(
|
||||
runs: readonly BuildRunOutputSilenceRunInput[],
|
||||
now: Date,
|
||||
): Promise<RunOutputSilenceSummary[]> {
|
||||
const runIdsByCompany = new Map<string, string[]>();
|
||||
for (const run of runs) {
|
||||
const runIds = runIdsByCompany.get(run.companyId) ?? [];
|
||||
runIds.push(run.id);
|
||||
runIdsByCompany.set(run.companyId, runIds);
|
||||
}
|
||||
const stateByCompany = new Map(await Promise.all([...runIdsByCompany].map(async ([companyId, runIds]) => {
|
||||
const [decisions, evaluations] = await Promise.all([
|
||||
deps.reader.findLatestDecisions(companyId, runIds, now),
|
||||
deps.reader.findOpenStaleRunEvaluations(companyId, runIds),
|
||||
]);
|
||||
return [companyId, { decisions, evaluations }] as const;
|
||||
})));
|
||||
return runs.map((run) => {
|
||||
const state = stateByCompany.get(run.companyId);
|
||||
const { dismissedFalsePositive, quietUntilDecision } = state?.decisions.get(run.id)
|
||||
?? { dismissedFalsePositive: false, quietUntilDecision: null };
|
||||
const evaluation = state?.evaluations.get(run.id) ?? null;
|
||||
const isRunningRun = run.status === "running";
|
||||
const silenceAgeMsValue = isRunningRun ? silenceAgeMs(run, now) : null;
|
||||
const level = classifySilenceLevel({
|
||||
isRunningRun,
|
||||
silenceAgeMs: silenceAgeMsValue,
|
||||
dismissedFalsePositive,
|
||||
snoozed: Boolean(quietUntilDecision),
|
||||
suspicionThresholdMs: deps.suspicionThresholdMs,
|
||||
criticalThresholdMs: deps.criticalThresholdMs,
|
||||
});
|
||||
|
||||
return {
|
||||
lastOutputAt: run.lastOutputAt ?? null,
|
||||
lastOutputSeq: run.lastOutputSeq ?? 0,
|
||||
lastOutputStream: run.lastOutputStream === "stdout" || run.lastOutputStream === "stderr"
|
||||
? run.lastOutputStream
|
||||
: null,
|
||||
silenceStartedAt: silenceStartedAt(run),
|
||||
silenceAgeMs: silenceAgeMsValue,
|
||||
level,
|
||||
suspicionThresholdMs: deps.suspicionThresholdMs,
|
||||
criticalThresholdMs: deps.criticalThresholdMs,
|
||||
snoozedUntil: dismissedFalsePositive ? null : quietUntilDecision?.snoozedUntil ?? null,
|
||||
evaluationIssueId: evaluation?.id ?? null,
|
||||
evaluationIssueIdentifier: evaluation?.identifier ?? null,
|
||||
evaluationIssueAssigneeAgentId: evaluation?.assigneeAgentId ?? null,
|
||||
};
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
export function createBuildRunOutputSilence(deps: BuildRunOutputSilenceDeps) {
|
||||
const buildRunOutputSilences = createBuildRunOutputSilences(deps);
|
||||
return async function buildRunOutputSilence(
|
||||
run: BuildRunOutputSilenceRunInput,
|
||||
now: Date,
|
||||
): Promise<RunOutputSilenceSummary> {
|
||||
const [decisionState, evaluation] = await Promise.all([
|
||||
deps.reader.findLatestDecision(run.companyId, run.id, now),
|
||||
deps.reader.findOpenStaleRunEvaluation(run.companyId, run.id),
|
||||
]);
|
||||
const { dismissedFalsePositive, quietUntilDecision } = decisionState;
|
||||
const isRunningRun = run.status === "running";
|
||||
const silenceAgeMsValue = isRunningRun ? silenceAgeMs(run, now) : null;
|
||||
const level = classifySilenceLevel({
|
||||
isRunningRun,
|
||||
silenceAgeMs: silenceAgeMsValue,
|
||||
dismissedFalsePositive,
|
||||
snoozed: Boolean(quietUntilDecision),
|
||||
suspicionThresholdMs: deps.suspicionThresholdMs,
|
||||
criticalThresholdMs: deps.criticalThresholdMs,
|
||||
});
|
||||
|
||||
return {
|
||||
lastOutputAt: run.lastOutputAt ?? null,
|
||||
lastOutputSeq: run.lastOutputSeq ?? 0,
|
||||
lastOutputStream: run.lastOutputStream === "stdout" || run.lastOutputStream === "stderr"
|
||||
? run.lastOutputStream
|
||||
: null,
|
||||
silenceStartedAt: silenceStartedAt(run),
|
||||
silenceAgeMs: silenceAgeMsValue,
|
||||
level,
|
||||
suspicionThresholdMs: deps.suspicionThresholdMs,
|
||||
criticalThresholdMs: deps.criticalThresholdMs,
|
||||
snoozedUntil: dismissedFalsePositive ? null : quietUntilDecision?.snoozedUntil ?? null,
|
||||
evaluationIssueId: evaluation?.id ?? null,
|
||||
evaluationIssueIdentifier: evaluation?.identifier ?? null,
|
||||
evaluationIssueAssigneeAgentId: evaluation?.assigneeAgentId ?? null,
|
||||
};
|
||||
const [summary] = await buildRunOutputSilences([run], now);
|
||||
return summary!;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ import { createPostgresWatchdogAdapter } from "./adapters/postgres.js";
|
||||
import { createProcessAdapter } from "./adapters/process.js";
|
||||
import {
|
||||
createBuildRunOutputSilence,
|
||||
createBuildRunOutputSilences,
|
||||
createFoldSourceResolvedRun,
|
||||
createRecordWatchdogDecision,
|
||||
createScanSilentActiveRuns,
|
||||
@@ -42,6 +43,11 @@ export function createActiveRunWatchdog(db: Db, config: ActiveRunWatchdogConfig)
|
||||
suspicionThresholdMs: config.suspicionThresholdMs,
|
||||
criticalThresholdMs: config.criticalThresholdMs,
|
||||
}),
|
||||
buildRunOutputSilences: createBuildRunOutputSilences({
|
||||
reader: postgresAdapter,
|
||||
suspicionThresholdMs: config.suspicionThresholdMs,
|
||||
criticalThresholdMs: config.criticalThresholdMs,
|
||||
}),
|
||||
scanSilentActiveRuns,
|
||||
recordWatchdogDecision: createRecordWatchdogDecision({
|
||||
reader: postgresAdapter,
|
||||
|
||||
@@ -7314,13 +7314,17 @@ export function agentRoutes(
|
||||
}
|
||||
|
||||
const projections = await executionProjectionsForRuns(db, companyId, rows.map(run => run.id));
|
||||
res.json(await runRedactions.redactForRuns(companyId, await Promise.all(rows.map(async (run) => !(await actorCanReadRun(req, run)) ? redactHeartbeatRunListRow(run) : ({
|
||||
const readDecisions = await getHeartbeatRunReadDecisions(db, access, req.actor, rows);
|
||||
const readableRuns = rows.filter((_, index) => readDecisions[index]);
|
||||
const silences = await heartbeat.buildRunOutputSilences(readableRuns);
|
||||
const silenceByRun = new Map(readableRuns.map((run, index) => [run.id, silences[index]!]));
|
||||
res.json(await runRedactions.redactForRuns(companyId, rows.map((run, index) => !readDecisions[index] ? redactHeartbeatRunListRow(run) : ({
|
||||
...heartbeat.decorateActiveRunStatus(run),
|
||||
agentAppearance: resolveAgentAppearance(run.agentAppearance, run.agentId),
|
||||
avatarUrl: agentAvatarUrl(resolveAgentAppearance(run.agentAppearance, run.agentId), 512),
|
||||
execution: projections.get(run.id) ?? null,
|
||||
outputSilence: await heartbeat.buildRunOutputSilence(run),
|
||||
}))), req.actor.type === "board" ? getActorInfo(req).actorId : null));
|
||||
outputSilence: silenceByRun.get(run.id)!,
|
||||
})), req.actor.type === "board" ? getActorInfo(req).actorId : null));
|
||||
});
|
||||
|
||||
function readHeartbeatRunId(req: Request): string {
|
||||
|
||||
@@ -1774,6 +1774,24 @@ export function heartbeatService(
|
||||
return recovery.buildRunOutputSilence(run, now);
|
||||
}
|
||||
|
||||
async function buildRunOutputSilences(
|
||||
runs: ReadonlyArray<Pick<
|
||||
typeof heartbeatRuns.$inferSelect,
|
||||
| "id"
|
||||
| "companyId"
|
||||
| "status"
|
||||
| "lastOutputAt"
|
||||
| "lastOutputSeq"
|
||||
| "lastOutputStream"
|
||||
| "processStartedAt"
|
||||
| "startedAt"
|
||||
| "createdAt"
|
||||
>>,
|
||||
now = new Date(),
|
||||
) {
|
||||
return recovery.buildRunOutputSilences(runs, now);
|
||||
}
|
||||
|
||||
async function reconcileResolvedDependencyWakes(opts?: Parameters<typeof recovery.reconcileResolvedDependencyWakeBackstop>[0]) {
|
||||
return recovery.reconcileResolvedDependencyWakeBackstop(opts);
|
||||
}
|
||||
@@ -4736,6 +4754,7 @@ export function heartbeatService(
|
||||
reconcileCostAccounting,
|
||||
|
||||
buildRunOutputSilence,
|
||||
buildRunOutputSilences,
|
||||
|
||||
tickTimers,
|
||||
tickAgentTimers,
|
||||
|
||||
@@ -174,7 +174,7 @@ describe("native case tools through authenticated production routes", () => {
|
||||
const receipt = await f.call("create_case", { idempotencyKey: "reusable-kickoff", title: "Reusable receipt", caseType: "loose",
|
||||
workflowId: created.data.id, kickoff: { toAgentId: f.agentId, phase: "custom phase", instructions: "Read workflow" } }) as { taskId: string; caseId: string };
|
||||
expect((await documentService(server.db).getIssueDocumentByKey(receipt.taskId, "workflow"))?.body).toBe(prompt);
|
||||
await expect(f.call("read_workflow", { workflowId: created.data.id, responseText: { offsetBytes: 8192 } })).rejects.toThrow("Invalid workflow arguments");
|
||||
await expect(f.call("read_workflow", { workflowId: created.data.id, responseText: { offsetBytes: 8192 } })).rejects.toThrow("Invalid tool input for read_workflow: A nonzero responseText.offsetBytes continues an earlier read: also send the snapshot it returned");
|
||||
expect(await f.call("update_workflow", { workflowId: created.data.id, idempotencyKey: "workflow-edit", prompt: prompt.replaceAll("Reusable", "Adjusted") })).toMatchObject({ ok: true });
|
||||
expect(await f.call("read_workflow", { workflowId: created.data.id, snapshot, responseText: { offsetBytes: 8192 } })).toMatchObject({ ok: false, status: 409 });
|
||||
const restarted = await f.call("read_workflow", { workflowId: created.data.id, responseText: { limitBytes: 4 } }) as { ok: boolean; data: string; snapshot: string };
|
||||
@@ -293,7 +293,7 @@ describe("native case tools through authenticated production routes", () => {
|
||||
for (const extra of [{ status: "done" }, { phase: "done" }, { workIssueId: f.blockerId }, { responsibleUserId: randomUUID() }]) {
|
||||
await expect(f.call("update_case", { idempotencyKey: randomUUID(), title: "No", ...extra })).rejects.toThrow("Invalid case tool arguments");
|
||||
}
|
||||
await expect(f.call("update_case", { idempotencyKey: "empty" })).rejects.toThrow("Invalid case tool arguments");
|
||||
await expect(f.call("update_case", { idempotencyKey: "empty" })).rejects.toThrow("Invalid tool input for update_case: update_case changes nothing without at least one of title, summary, fields.");
|
||||
await expect(f.call("write_case_document", { key: "receipt", body: "No" })).rejects.toThrow();
|
||||
const [foreign] = await server.db.insert(cases).values({ companyId: f.foreignCompanyId, caseNumber: 1,
|
||||
identifier: `C-${randomUUID()}`, caseType: "private", title: "foreign-data-must-not-leak" }).returning();
|
||||
|
||||
@@ -12513,6 +12513,52 @@ describe("native warm session supervision", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("releases a retired warm predecessor's tool authority when the follow-up fails before admitting its own", async () => {
|
||||
const { base } = fixture("authority-failed-follow-up");
|
||||
const next = { ...base, binding: { ...base.binding, runId: "authority-failed-follow-up-next" } };
|
||||
const root = await mkdtemp(join(tmpdir(), "native-authority-failed-follow-up-"));
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", root);
|
||||
const close = vi.fn(async () => undefined);
|
||||
const issueService = vi.spyOn(issueServiceModule, "issueService").mockReturnValue({
|
||||
update: vi.fn(async () => ({ status: "blocked", statusVersion: 1 })),
|
||||
} as unknown as ReturnType<typeof issueServiceModule.issueService>);
|
||||
const assigned = { PAPERCLIP_NATIVE_MCP_NAME: "assigned", PAPERCLIP_NATIVE_MCP_URL: "http://127.0.0.1/mcp/gateways/assigned-follow-up",
|
||||
PAPERCLIP_NATIVE_MCP_TOKEN: "follow-up-fixture" };
|
||||
state.createAssignedMcpTools.mockResolvedValueOnce({ definitions: () => [], has: () => false, execute: vi.fn() })
|
||||
.mockRejectedValueOnce(new Error("assigned tools unavailable"));
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
state.createBackend.mock.calls.at(-1)![1].codexTransportFactory!();
|
||||
const factory = state.createTransport.mock.calls.at(-1)![0];
|
||||
const identity = { ...factory.prpIdentity, normalizedSessionId: base.session.normalizedSessionId };
|
||||
await mkdir(join(factory.stateDirectory!, "control-plane"), { recursive: true });
|
||||
await mkdir(join(factory.stateDirectory!, "runner"), { recursive: true });
|
||||
await writeFile(join(factory.stateDirectory!, "control-plane", "control-plane-state.json"), JSON.stringify(durableControlPlaneState(identity)));
|
||||
await writeFile(join(factory.stateDirectory!, "runner", "runner-state.json"), JSON.stringify(durableRunnerState(identity, "ready")));
|
||||
await options.onSession?.({ close }); return result;
|
||||
});
|
||||
try {
|
||||
const before = sessionToolAuthorityCount();
|
||||
await executePaperclipNativeSession({ db: leaseDb(base), execution: base, runnerInstanceId: "runner", useRunnerd: true,
|
||||
runnerEnvironment: assigned });
|
||||
expect(sessionToolAuthorityCount()).toBe(before + 1);
|
||||
const current = leaseDb(next);
|
||||
const nextDb = { ...current, select: (columns?: Record<string, unknown>) => columns?.status && columns?.runnerProfileJson
|
||||
? { from: () => ({ where: () => ({ limit: () => Promise.resolve([{ status: "succeeded", runnerProfileJson: { nativeExecutionInput: base } }]) }) }) }
|
||||
: current.select(columns as never) } as unknown as Db;
|
||||
const failure = await executePaperclipNativeSession({ db: nextDb, execution: next, runnerInstanceId: "runner", useRunnerd: true,
|
||||
runnerEnvironment: { ...assigned, PAPERCLIP_AGENT_KEY_ID: "sha256:follow-up-key" } }).catch((error: Error) => error);
|
||||
expect(failure).toMatchObject({ message: "assigned tools unavailable" });
|
||||
expect(state.createAssignedMcpTools).toHaveBeenCalledTimes(2);
|
||||
expect(close).toHaveBeenCalledWith({ reason: "warm native session configuration changed" });
|
||||
expect(state.execute).toHaveBeenCalledOnce();
|
||||
expect(sessionToolAuthorityCount()).toBe(before);
|
||||
} finally {
|
||||
issueService.mockRestore();
|
||||
vi.unstubAllEnvs();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
it("awaits prior idle ownership retirement before launching the accepted-plan session", async () => {
|
||||
const { base, next, run } = fixture("identity-handoff");
|
||||
let finishClose!: () => void;
|
||||
@@ -23099,3 +23145,68 @@ describe("isTransientRemoteCheckpointReadFailure", () => {
|
||||
await expect(retryTransientRemoteCheckpointRead(async () => { if (drops-- > 0) throw reset(); return "settled"; }, vi.fn(), 0)).resolves.toBe("settled");
|
||||
});
|
||||
});
|
||||
|
||||
describe("released native session tool authority", () => {
|
||||
const assignedTool = (label: string) => ({ name: `app_released_${label}`, description: `Released ${label}`, inputSchema: { type: "object" } });
|
||||
const assignedTools = (label: string) => {
|
||||
const tool = assignedTool(label);
|
||||
return { definitions: () => [tool], has: (name: string) => name === tool.name,
|
||||
execute: vi.fn(async (_call: unknown) => ({ content: [{ type: "text", text: label }] })) };
|
||||
};
|
||||
const scoped = (runId: string) => ({ ...execution,
|
||||
binding: { ...execution.binding, runId, issueId: "released-authority-issue" },
|
||||
session: { ...execution.session, normalizedSessionId: "released-authority-session",
|
||||
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } } } as NativeExecutionInputV1);
|
||||
const environment = { PAPERCLIP_NATIVE_MCP_NAME: "assigned", PAPERCLIP_NATIVE_MCP_URL: "http://localhost/mcp/gateways/assigned-released",
|
||||
PAPERCLIP_NATIVE_MCP_TOKEN: "released-token" };
|
||||
const call = (tool: string) => ({ tool, callId: `call-${tool}`, arguments: {} }) as never;
|
||||
|
||||
beforeEach(() => {
|
||||
state.toolAuthorityDefinitions.mockImplementation(async binding =>
|
||||
((binding.assignedMcpTools as ReturnType<typeof assignedTools> | undefined)?.definitions() ?? []) as never);
|
||||
state.toolAuthorityExecute.mockReset().mockImplementation(async (binding: Record<string, unknown>, value: unknown) => {
|
||||
const tools = binding.assignedMcpTools as ReturnType<typeof assignedTools>;
|
||||
const { tool, arguments: args } = value as { tool: string; arguments: unknown };
|
||||
if (!tools.has(tool)) throw new Error("unknown tool");
|
||||
return tools.execute({ tool, arguments: args });
|
||||
});
|
||||
});
|
||||
afterEach(() => {
|
||||
state.toolAuthorityDefinitions.mockImplementation(async () => []);
|
||||
state.toolAuthorityExecute.mockReset();
|
||||
});
|
||||
|
||||
it("refuses a released session's late tool call and completion feedback and admits the next run with only its own assignments", async () => {
|
||||
const first = assignedTools("first"), second = assignedTools("second");
|
||||
const current = scoped("released-authority-first");
|
||||
state.createAssignedMcpTools.mockResolvedValueOnce(first);
|
||||
state.execute.mockReset().mockImplementationOnce(async options => {
|
||||
await options.onSession?.({ close: async () => {} });
|
||||
return { result: { summary: "done" }, terminal: { runTerminalState: "succeeded" }, turnId: "turn",
|
||||
normalizedSessionId: current.session.normalizedSessionId, providerSessionId: null, driverKind: "test", driverVersion: "1",
|
||||
nativeEventCount: 0, highestContiguousSourceSeq: 0 };
|
||||
});
|
||||
await executePaperclipNativeSession({ db: leaseDb(current), execution: current, runnerInstanceId: "runner", useRunnerd: true,
|
||||
runnerEnvironment: environment });
|
||||
const released = state.createBackend.mock.calls.at(-1)![1];
|
||||
await expect(Promise.resolve().then(() => released.dynamicToolHandler!(call(assignedTool("first").name))))
|
||||
.rejects.toThrow("native_session_tool_authority_unavailable");
|
||||
await expect(released.completionFeedback!({} as never)).rejects.toThrow("native_session_tool_authority_unavailable");
|
||||
expect(first.execute).not.toHaveBeenCalled();
|
||||
const next = scoped("released-authority-second");
|
||||
state.createAssignedMcpTools.mockResolvedValueOnce(second);
|
||||
const directory = await mkdtemp(join(tmpdir(), "native-authority-readmission-"));
|
||||
vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", directory);
|
||||
try {
|
||||
await createRunnerdBackend({ db: leaseDb(next), execution: next, runnerInstanceId: "runner", runnerEnvironment: environment });
|
||||
} finally {
|
||||
vi.unstubAllEnvs();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
const admitted = state.createBackend.mock.calls.at(-1)![1];
|
||||
await expect(admitted.dynamicToolHandler!(call(assignedTool("second").name))).resolves.toEqual({ content: [{ type: "text", text: "second" }] });
|
||||
await expect(admitted.dynamicToolHandler!(call(assignedTool("first").name))).rejects.toThrow("unknown tool");
|
||||
expect(first.execute).not.toHaveBeenCalled();
|
||||
expect(state.createAssignedMcpTools).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -72,7 +72,7 @@ import { canActorReadAssetContent } from "../asset-content-access.js";
|
||||
import { getSecretProvider } from "../../secrets/provider-registry.js";
|
||||
import { runnerApiSensitiveResponse } from "./runner-api-sensitive-response.js";
|
||||
import { workspaceFileResourceService } from "../workspace-file-resources.js";
|
||||
import { badRequest, forbidden, notFound, HttpError } from "../../errors.js";
|
||||
import { badRequest, forbidden, notFound, HttpError, unprocessable } from "../../errors.js";
|
||||
import { casesDisabledError } from "../cases-disabled.js";
|
||||
import { runnerApiCatalog, searchRunnerApi, withCompanyPagePaths } from "./runner-api-catalog.js";
|
||||
import { assertRunnerApiDispatchable, executeRunnerApi, validateRunnerApiCall, RUNNER_API_MAX_BYTES, type RunnerApiCall, type RunnerApiFile, type RunnerApiIo } from "./runner-api-client.js";
|
||||
@@ -102,7 +102,7 @@ import {
|
||||
projects,
|
||||
issueThreadInteractions,
|
||||
} from "@paperclipai/db";
|
||||
import { CAPABILITY_CANONICAL_OPERATIONS, CAPABILITY_SEMANTIC_TOOL_CATALOG, parseNativeExecutionInput, runnerCodexDynamicToolsFit, SemanticToolOutcomeUnknownError } from "../../vendor/paperclip-runner/index.js";
|
||||
import { CAPABILITY_CANONICAL_OPERATIONS, CAPABILITY_SEMANTIC_TOOL_CATALOG, parseNativeExecutionInput, runnerCodexDynamicToolsFit, SemanticToolOutcomeUnknownError, toolInputVariantError } from "../../vendor/paperclip-runner/index.js";
|
||||
import { agentService } from "../agents.js";
|
||||
import { approvalService } from "../approvals.js";
|
||||
import { documentService } from "../documents.js";
|
||||
@@ -631,6 +631,12 @@ export class PaperclipRunnerToolAuthority {
|
||||
callId: string;
|
||||
arguments: unknown;
|
||||
}): Promise<unknown> {
|
||||
// Advertised schemas are plain objects so every model host shows their
|
||||
// arguments; their cross-field variants are checked here with named errors.
|
||||
if (!this.binding.assignedMcpTools?.has(call.tool) && !isConnectorTool(call.tool)) {
|
||||
const variantError = toolInputVariantError(call.tool, call.arguments);
|
||||
if (variantError) throw unprocessable(variantError);
|
||||
}
|
||||
if ((call.tool === "handoff_case" || call.tool === "create_case") && !this.binding.nativeReview) {
|
||||
if (this.binding.workMode && this.binding.workMode !== "standard") throw forbidden("Case tools require standard work mode");
|
||||
const create = call.tool === "create_case" ? createNativeCaseSchema.parse(call.arguments) : null;
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Db } from "@paperclipai/db";
|
||||
import { HttpError } from "../../errors.js";
|
||||
import { CAPABILITY_SEMANTIC_TOOL_CATALOG, providerToolSchemaShapeIssues } from "../../vendor/paperclip-runner/index.js";
|
||||
import { RUNTIME_CONNECTION_TOOL_DEFINITIONS } from "../connection-tool-definitions.js";
|
||||
import { DOWNLOAD_ARTIFACT_DEFINITION } from "./artifact-transfer.js";
|
||||
import { READ_CHAT_ATTACHMENT_TOOL_DEFINITION } from "./chat-attachment-read.js";
|
||||
import { LIST_CHAT_ATTACHMENTS_TOOL_DEFINITION, REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION } from "./chat-attachment-reuse.js";
|
||||
import { READ_CURRENT_WAKE_COMMENTS_TOOL_DEFINITION } from "./current-wake-comments.js";
|
||||
import { GENERATE_IMAGE_DEFINITION } from "./generate-image-tool.js";
|
||||
import { SKILL_LIBRARY_TOOL_DEFINITIONS } from "./native-skill-library-tools.js";
|
||||
import { SessionAuthorityEpoch } from "./native-session-executor.js";
|
||||
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
|
||||
import { runnerBridgeDefinitions } from "./runner-bridge-tools.js";
|
||||
import { TASK_ATTACHMENT_DEFINITIONS } from "./runner-task-attachments.js";
|
||||
import { READ_TOOL_RESULT_DEFINITION } from "./runner-tool-results.js";
|
||||
|
||||
const A = "00000000-0000-4000-8000-000000000101";
|
||||
const binding = { companyId: A, agentId: A, issueId: A, runId: A, casesEnabled: true };
|
||||
|
||||
describe("agent-facing tool input schemas", () => {
|
||||
it("are plain objects with named top-level properties", () => {
|
||||
const tools: Array<{ name: unknown; inputSchema: unknown }> = [
|
||||
...CAPABILITY_SEMANTIC_TOOL_CATALOG.map(tool => ({ name: tool.operationId, inputSchema: tool.inputSchema })),
|
||||
...RUNTIME_CONNECTION_TOOL_DEFINITIONS, DOWNLOAD_ARTIFACT_DEFINITION, GENERATE_IMAGE_DEFINITION,
|
||||
READ_CURRENT_WAKE_COMMENTS_TOOL_DEFINITION, LIST_CHAT_ATTACHMENTS_TOOL_DEFINITION, REUSE_CHAT_ATTACHMENT_TOOL_DEFINITION,
|
||||
READ_CHAT_ATTACHMENT_TOOL_DEFINITION, READ_TOOL_RESULT_DEFINITION, ...TASK_ATTACHMENT_DEFINITIONS, ...SKILL_LIBRARY_TOOL_DEFINITIONS,
|
||||
...runnerBridgeDefinitions({ workspace: true, skills: true, api: true, mode: "standard" }),
|
||||
];
|
||||
const offenders = tools.flatMap(tool => {
|
||||
const issues = providerToolSchemaShapeIssues(tool.inputSchema);
|
||||
return issues.length ? [`${String(tool.name)}: ${issues.join(", ")}`] : [];
|
||||
});
|
||||
expect(tools.length).toBeGreaterThan(70);
|
||||
expect(offenders).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("server-side tool input variants", () => {
|
||||
const authority = new PaperclipRunnerToolAuthority({} as Db, binding);
|
||||
const reject = (tool: string, args: unknown) => authority.execute({ tool, callId: "c", arguments: args }).then(() => null, (error: unknown) => error);
|
||||
|
||||
it("refuses a handoff that matches neither variant with a named 422 before any dispatch", async () => {
|
||||
const error = await reject("handoff_case", { idempotencyKey: "k", case: { id: A }, instructions: "Next." });
|
||||
expect(error).toBeInstanceOf(HttpError);
|
||||
expect((error as HttpError).status).toBe(422);
|
||||
expect((error as HttpError).message).toBe('Invalid tool input for handoff_case: An agent handoff requires toAgentId, phase. To finish an existing case instead, send to: "done" with expectedHandoffVersion and expectedIssueStatusVersion.');
|
||||
const questions = await reject("request_human_input", { idempotencyKey: "k", interactionKind: "questions", title: "T", prompt: "P", continuationPolicy: "wake_assignee", payload: { version: 1 } });
|
||||
expect((questions as HttpError).message).toContain('interactionKind: "questions" requires payload.questionSet');
|
||||
});
|
||||
|
||||
it("lets the repeated failure guard stop the third identical variant rejection", async () => {
|
||||
const epoch = new SessionAuthorityEpoch(A, authority);
|
||||
const args = { idempotencyKey: "k", caseType: "receipt", title: "T", kickoff: { toAgentId: A, phase: "triage", instructions: "Go." } };
|
||||
const messages: string[] = [];
|
||||
for (const callId of ["1", "2", "3"]) {
|
||||
messages.push(await epoch.execute({ tool: "create_case", callId, arguments: args }).then(() => "ran", (error: Error) => error.message));
|
||||
}
|
||||
expect(messages[0]).toMatch(/^Invalid tool input for create_case: create_case requires workflowId/);
|
||||
expect(messages[1]).toContain("This exact call has now failed 2 times with the same arguments.");
|
||||
expect(messages[2]).toMatch(/^This call was not run: create_case already failed 2 times/);
|
||||
});
|
||||
});
|
||||
@@ -2432,6 +2432,24 @@ export function recoveryService(
|
||||
return watchdog.buildRunOutputSilence(run, now);
|
||||
}
|
||||
|
||||
async function buildRunOutputSilences(
|
||||
runs: ReadonlyArray<Pick<
|
||||
typeof heartbeatRuns.$inferSelect,
|
||||
| "id"
|
||||
| "companyId"
|
||||
| "status"
|
||||
| "lastOutputAt"
|
||||
| "lastOutputSeq"
|
||||
| "lastOutputStream"
|
||||
| "processStartedAt"
|
||||
| "startedAt"
|
||||
| "createdAt"
|
||||
>>,
|
||||
now = new Date(),
|
||||
): Promise<RunOutputSilenceSummary[]> {
|
||||
return watchdog.buildRunOutputSilences(runs, now);
|
||||
}
|
||||
|
||||
async function appendRecoveryRunEvent(
|
||||
run: typeof heartbeatRuns.$inferSelect,
|
||||
event: {
|
||||
@@ -6845,6 +6863,7 @@ export function recoveryService(
|
||||
return {
|
||||
assignedWork,
|
||||
buildRunOutputSilence,
|
||||
buildRunOutputSilences,
|
||||
escalateStrandedRecoveryIssueInPlace,
|
||||
escalateStrandedAssignedIssue,
|
||||
recordWatchdogDecision,
|
||||
|
||||
+2
@@ -127,6 +127,8 @@ export type SemanticInputAdmission = import("@paperclipai/paperclip-runner").Sem
|
||||
export const PaperclipSemanticDispatcher = runner.PaperclipSemanticDispatcher;
|
||||
export const CAPABILITY_SEMANTIC_TOOL_CATALOG =
|
||||
runner.CAPABILITY_SEMANTIC_TOOL_CATALOG;
|
||||
export const toolInputVariantError = runner.toolInputVariantError;
|
||||
export const providerToolSchemaShapeIssues = runner.providerToolSchemaShapeIssues;
|
||||
export const CAPABILITY_CANONICAL_OPERATIONS = runner.CAPABILITY_CANONICAL_OPERATIONS;
|
||||
export const HarnessRuntimeRequestResolutionError =
|
||||
runner.HarnessRuntimeRequestResolutionError;
|
||||
|
||||
Reference in new issue
Block a user