Merge remote-tracking branch 'origin/master' into swarm-neon-tmp

* origin/master:
  fix(e2e): preserve exact spacing around handoff mentions (#22825)
  fix(routines): prefer X-Hub-Signature-256 on app_webhook triggers (#18581)
  fix(claude-local): label ACP usage rows from the run's AI connection (#20955)
  fix(agents): reject a blank taskKey on reset-session instead of resetting all task state (#19282)
  fix(documents): return the new body only after a document update or restore (#21036)
This commit is contained in:
Dotta committed 2026-11-24 16:13:42 -06:00
commit d78911f8c2
19 files changed
+302 -29

No files matched your search

@@ -15,4 +15,14 @@ describe("ACP accounting model", () => {
it("does not price a turn that changed models as one model", () => {
expect(acpxAccountingModel("gpt-6.1-sol", selected("gpt-6.1-sol"), selected("gpt-6-astra"))).toBeNull();
});
it("names the requested model over the bridge's alias when the run asks for it", () => {
const options = { preferRequested: true };
expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("opus"), options)).toBe("acme-claude-sonnet-gw");
expect(acpxAccountingModel("acme-claude-sonnet-gw", selected("opus"), selected("sonnet"), options)).toBe("acme-claude-sonnet-gw");
});
it("never names the bridge's current model when the run asked for none", () => {
const options = { preferRequested: true };
expect(acpxAccountingModel("", selected("opus"), selected("opus"), options)).toBeNull();
expect(acpxAccountingModel(" ", null, selected("opus"), options)).toBeNull();
});
});
@@ -2,7 +2,13 @@ import type { AcpRuntimeStatus } from "acpx/runtime";
/** Use provider-selected IDs, including its default. A mid-turn model change
* cannot be priced as a single-model receipt; never guess from a display name. */
export function acpxAccountingModel(requested: string, before: AcpRuntimeStatus | null, after: AcpRuntimeStatus | null): string | null {
export function acpxAccountingModel(
requested: string,
before: AcpRuntimeStatus | null,
after: AcpRuntimeStatus | null,
options: { preferRequested?: boolean } = {},
): string | null {
if (options.preferRequested) return requested.trim() || null;
const pre = before?.models?.currentModelId?.trim();
const post = after?.models?.currentModelId?.trim();
if (pre && post && pre !== post) return null;
@@ -1641,6 +1641,34 @@ describe("shared ACPX engine runtime behavior", () => {
expect(statusLine?.text).toContain('"cost"');
});
it.each([
{ preferRequestedModel: true, expected: "acme-claude-sonnet-gw" },
{ preferRequestedModel: undefined, expected: "opus" },
])("labels usage with the model $expected when preferRequestedModel is $preferRequestedModel", async ({ preferRequestedModel, expected }) => {
const root = await makeTempRoot();
const onUsage = vi.fn();
const execute = createAcpxEngineExecutor({
createRuntime: () => ({
...buildRuntime(),
getStatus: async () => ({ models: { currentModelId: "opus", availableModelIds: [] } }),
}) as never,
resolveBillingIdentity: () => ({ provider: "anthropic", biller: "anthropic", billingType: "api", preferRequestedModel }),
});
const result = await execute({
runId: "run-requested-model",
onUsage,
agent: { id: "agent-1", companyId: "company-1" },
runtime: {},
config: { agent: "custom", agentCommand: "node ./fake-acp.js", stateDir: path.join(root, "state"), model: "acme-claude-sonnet-gw" },
context: {},
onLog: async () => {},
onMeta: async () => {},
} as never);
expect(result.exitCode).toBe(0);
expect(result.model).toBe(expected);
expect(onUsage).toHaveBeenLastCalledWith(expect.objectContaining({ model: expected, complete: true }));
});
it.each(["checkpoint", "terminal"])("returns received usage after the %s receipt sink rejects and still closes the runtime", async (failedSave) => {
const root = await makeTempRoot();
const close = vi.fn(async () => {});
@@ -286,6 +286,7 @@ export interface AcpxEngineBillingIdentity {
provider?: string | null;
biller?: string | null;
billingType?: AdapterBillingType | null;
preferRequestedModel?: boolean;
}
/**
@@ -5162,7 +5163,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
// Snapshot pre-turn usage so cumulative agent-reported cost can be
// attributed to this run alone.
preTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null);
accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, null, { preferRequested: billingIdentity?.preferRequestedModel });
// The prepare phase (prompt build + usage snapshot) finished; the turn
// phase starts next.
await emitPhase("prepare_turn", preparePhaseStart, "ok");
@@ -5454,7 +5455,7 @@ export function createAcpxEngineExecutor(deps: AcpxEngineExecutorOptions = {}) {
const turnSucceeded = terminal.status === "completed" && !timedOut && !channelLost;
// Read usage before the settlement can discard runtime state.
const postTurnStatus = await readRuntimeStatus(runtime, sessionHandle);
accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus);
accountingModel = acpxAccountingModel(prepared.requestedModel, preTurnStatus, postTurnStatus, { preferRequested: billingIdentity?.preferRequestedModel });
const turnUsage = summarizeAcpxTurnUsage({
preStatus: preTurnStatus,
postStatus: postTurnStatus,
@@ -0,0 +1,33 @@
import type { AdapterBillingType } from "@paperclipai/adapter-utils";
import { parseObject } from "@paperclipai/adapter-utils/server-utils";
export function resolveManagedApiKeyBilling(
config: Record<string, unknown>,
): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel: true } | null {
const connection = parseObject(config.managedAiConnection);
const provider = typeof connection.provider === "string" ? connection.provider.trim() : "";
if (connection.method !== "api_key" || !provider) return null;
return {
provider,
biller: parseObject(config.managedAiRouting).kind === "bedrock" ? "aws_bedrock" : provider,
billingType: "metered_api",
preferRequestedModel: true,
};
}
export function resolveEnvBillingIdentity(
readEnvValue: (key: string) => string,
): { provider: string; biller: string; billingType: AdapterBillingType } {
const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK");
const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL"));
const billingType: AdapterBillingType = bedrock
? "metered_api"
: readEnvValue("ANTHROPIC_API_KEY")
? "api"
: "subscription";
return {
provider: "anthropic",
biller: bedrock ? "aws_bedrock" : "anthropic",
billingType,
};
}
@@ -1842,6 +1842,74 @@ describe("resolveClaudeAcpBillingIdentity", () => {
});
});
describe("with a managed AI connection", () => {
const attribution = (overrides: Record<string, unknown>) => ({
connectionId: "conn-1", grantId: "grant-1", mode: "shared", responsibleUserId: null, ...overrides,
});
it("labels a gateway api_key connection from the connection, whatever credential env it projects", () => {
delete process.env.ANTHROPIC_API_KEY;
expect(
resolveClaudeAcpBillingIdentity({
config: {
model: "acme-claude-sonnet-gw",
managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }),
managedAiRouting: { kind: "gateway", auth: "bearer", baseUrl: "https://gateway.example.test", protocol: "messages" },
env: { ANTHROPIC_AUTH_TOKEN: "token", ANTHROPIC_BASE_URL: "https://gateway.example.test" },
},
}),
).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true });
});
it("bills an OpenRouter connection to OpenRouter", () => {
expect(
resolveClaudeAcpBillingIdentity({
config: {
managedAiConnection: attribution({ provider: "openrouter", method: "api_key" }),
managedAiRouting: { kind: "openrouter", auth: "bearer" },
},
}),
).toEqual({ provider: "openrouter", biller: "openrouter", billingType: "metered_api", preferRequestedModel: true });
});
it("bills a local-routing connection to its provider", () => {
expect(
resolveClaudeAcpBillingIdentity({
config: {
managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }),
managedAiRouting: { kind: "local", auth: "none" },
},
}),
).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "metered_api", preferRequestedModel: true });
});
it("keeps Bedrock routing metered", () => {
expect(
resolveClaudeAcpBillingIdentity({
config: {
managedAiConnection: attribution({ provider: "anthropic", method: "api_key" }),
managedAiRouting: { kind: "bedrock", region: "eu-central-1" },
},
}),
).toEqual({ provider: "anthropic", biller: "aws_bedrock", billingType: "metered_api", preferRequestedModel: true });
});
it("leaves a subscription connection with the labels it always got", () => {
delete process.env.ANTHROPIC_API_KEY;
delete process.env.CLAUDE_CODE_USE_BEDROCK;
delete process.env.ANTHROPIC_BEDROCK_BASE_URL;
const identity = resolveClaudeAcpBillingIdentity({
config: {
model: "claude-sonnet-5-5",
managedAiConnection: attribution({ provider: "anthropic", method: "subscription" }),
env: { ANTHROPIC_API_KEY: "" },
},
});
expect(identity).toEqual({ provider: "anthropic", biller: "anthropic", billingType: "subscription" });
expect(identity).not.toHaveProperty("preferRequestedModel");
});
});
it("ignores host env for remote execution targets", () => {
process.env.ANTHROPIC_API_KEY = "sk-ant-host-only";
expect(
@@ -40,6 +40,7 @@ import {
asString,
parseObject,
} from "@paperclipai/adapter-utils/server-utils";
import { resolveEnvBillingIdentity, resolveManagedApiKeyBilling } from "./acp-billing.js";
import {
materializeRemoteClaudeConfig,
overrideRemoteClaudeLocalPermissionMode,
@@ -177,7 +178,9 @@ export function buildClaudeAcpConfig(
export function resolveClaudeAcpBillingIdentity(
ctx: Pick<AdapterExecutionContext, "config"> &
Partial<Pick<AdapterExecutionContext, "executionTarget" | "executionTransport">>,
): { provider: string; biller: string; billingType: AdapterBillingType } {
): { provider: string; biller: string; billingType: AdapterBillingType; preferRequestedModel?: true } {
const connection = resolveManagedApiKeyBilling(ctx.config);
if (connection) return connection;
const envConfig = parseObject(parseObject(ctx.config).env);
const target = readAdapterExecutionTarget({
executionTarget: ctx.executionTarget,
@@ -190,18 +193,7 @@ export function resolveClaudeAcpBillingIdentity(
const fromHost = considerHostEnv ? process.env[key] : undefined;
return typeof fromHost === "string" ? fromHost.trim() : "";
};
const bedrockFlag = readEnvValue("CLAUDE_CODE_USE_BEDROCK");
const bedrock = bedrockFlag === "1" || bedrockFlag === "true" || Boolean(readEnvValue("ANTHROPIC_BEDROCK_BASE_URL"));
const billingType: AdapterBillingType = bedrock
? "metered_api"
: readEnvValue("ANTHROPIC_API_KEY")
? "api"
: "subscription";
return {
provider: "anthropic",
biller: bedrock ? "aws_bedrock" : "anthropic",
billingType,
};
return resolveEnvBillingIdentity(readEnvValue);
}
/**
+17 -1
View File
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { updateAgentSchema } from "./agent.js";
import { resetAgentSessionSchema, updateAgentSchema } from "./agent.js";
describe("agent update schema", () => {
it.each(["paused", "idle", "terminated"])("accepts lifecycle status request %s", status => {
@@ -23,3 +23,19 @@ describe("agent update schema", () => {
expect(updateAgentSchema.parse({ name: "Renamed", budgetMonthlyCents: 100 })).toEqual({ name: "Renamed", budgetMonthlyCents: 100 });
});
});
describe("reset agent session schema", () => {
it.each([{}, { taskKey: null }])("accepts a full reset request: %j", payload => {
expect(resetAgentSessionSchema.parse(payload)).toEqual(payload);
});
it("trims a task key", () => {
expect(resetAgentSessionSchema.parse({ taskKey: " task-1 " })).toEqual({ taskKey: "task-1" });
});
it.each(["", " ", "\t\n"])("rejects a blank task key %j", taskKey => {
const result = resetAgentSessionSchema.safeParse({ taskKey });
expect(result.success).toBe(false);
if (!result.success) expect(result.error.issues).toEqual(expect.arrayContaining([
expect.objectContaining({ path: ["taskKey"] }),
]));
});
});
+1 -1
View File
@@ -279,7 +279,7 @@ export const wakeAgentSchema = z.object({
export type WakeAgent = z.infer<typeof wakeAgentSchema>;
export const resetAgentSessionSchema = z.object({
taskKey: z.string().min(1).optional().nullable(),
taskKey: z.string().trim().min(1).optional().nullable(),
});
export type ResetAgentSession = z.infer<typeof resetAgentSessionSchema>;
@@ -189,6 +189,31 @@ describeEmbeddedPostgres("documentService system issue documents", () => {
});
});
it("returns the saved document from update and restore exactly as a fresh read returns it", async () => {
const { issueId } = await createIssueWithDocuments();
const original = (await svc.getIssueDocumentByKey(issueId, "plan"))!;
const updated = await svc.upsertIssueDocument({
issueId,
key: "plan",
title: "Plan",
format: "markdown",
body: "# Second plan",
baseRevisionId: original.latestRevisionId,
});
expect(updated.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan"));
expect(updated.document).not.toHaveProperty("latestBody");
const restored = await svc.restoreIssueDocumentRevision({
issueId,
key: "plan",
revisionId: original.latestRevisionId!,
});
expect(restored.document.body).toBe(original.body);
expect(restored.document).toEqual(await svc.getIssueDocumentByKey(issueId, "plan"));
expect(restored.document).not.toHaveProperty("latestBody");
});
it("locks and unlocks issue documents", async () => {
const { issueId } = await createIssueWithDocuments();
@@ -2904,6 +2904,54 @@ describeEmbeddedPostgres("routine service live-execution coalescing", () => {
});
it.each([
"both signature headers",
"SHA-256 header only",
"legacy header only",
])("accepts a signed app webhook with %s", async (headers) => {
const { svc, routine, trigger, secretMaterial } = await firefliesFixture(false, "app_webhook");
const payload = { event: "deployment.completed", deployment_id: "deploy-headers" };
const rawBody = Buffer.from(JSON.stringify(payload));
const secret = secretMaterial!.webhookSecret;
const signature = `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`;
const result = await svc.firePublicTrigger(trigger.publicId!, {
rawBody,
payload,
hubSignatureHeader: headers === "legacy header only" ? undefined : signature,
firefliesSignatureHeader: headers === "SHA-256 header only"
? undefined
: headers === "legacy header only"
? signature
: `sha1=${createHmac("sha1", secret).update(rawBody).digest("hex")}`,
});
expect(result.status).toBe("issue_created");
const runs = await svc.listRuns(routine.id);
expect(runs).toHaveLength(1);
expect(runs[0].triggerPayload).toEqual(payload);
});
it.each(["invalid SHA-256 header", "SHA-1 header only"])(
"rejects an app webhook with %s despite valid bearer authorization",
async (headers) => {
const { svc, routine, trigger, secretMaterial } = await firefliesFixture(false, "app_webhook");
const payload = { event: "deployment.completed", deployment_id: "deploy-invalid" };
const rawBody = Buffer.from(JSON.stringify(payload));
const secret = secretMaterial!.webhookSecret;
await expect(svc.firePublicTrigger(trigger.publicId!, {
rawBody,
payload,
authorizationHeader: `Bearer ${secret}`,
hubSignatureHeader: headers === "SHA-1 header only" ? undefined : `sha256=${"0".repeat(64)}`,
firefliesSignatureHeader: headers === "SHA-1 header only"
? `sha1=${createHmac("sha1", secret).update(rawBody).digest("hex")}`
: `sha256=${createHmac("sha256", secret).update(rawBody).digest("hex")}`,
})).rejects.toMatchObject({ status: 401 });
expect(await svc.listRuns(routine.id)).toEqual([]);
},
);
it("dispatches one Fireflies run for concurrent retries and passes meeting metadata", async () => {
const { svc, routine, trigger, delivery, wakeups } = await firefliesFixture();
const results = await Promise.all([
+1 -4
View File
@@ -4509,10 +4509,7 @@ export function agentRoutes(
if (!agent) return;
await assertBoardCanManageAgentsForCompany(req, agent.companyId);
const taskKey =
typeof req.body.taskKey === "string" && req.body.taskKey.trim().length > 0
? req.body.taskKey.trim()
: null;
const taskKey: string | null = req.body.taskKey ?? null;
const state = await heartbeat.resetRuntimeSession(id, { taskKey });
await logActivity(db, {
+4 -2
View File
@@ -464,10 +464,11 @@ export function documentService(db: Db) {
.set({ updatedAt: now })
.where(eq(issueDocuments.documentId, existing.id));
const { latestBody: _previousBody, ...existingMetadata } = existing;
return {
created: false as const,
document: {
...existing,
...existingMetadata,
title: input.title ?? null,
format: input.format,
body: input.body,
@@ -751,11 +752,12 @@ export function documentService(db: Db) {
.set({ updatedAt: now })
.where(eq(issueDocuments.documentId, existing.id));
const { latestBody: _previousBody, ...existingMetadata } = existing;
return {
restoredFromRevisionId: revision.id,
restoredFromRevisionNumber: revision.revisionNumber,
document: {
...existing,
...existingMetadata,
title: revision.title ?? null,
format: revision.format,
body: revision.body,
+1 -1
View File
@@ -3319,7 +3319,7 @@ export function routineService(
appDelivery = verifyAppWebhook({
secret: await resolveTriggerSecret(trigger, routine.companyId),
publicId, authorization: input.authorizationHeader,
signature: input.firefliesSignatureHeader ?? input.hubSignatureHeader,
signature: input.hubSignatureHeader ?? input.firefliesSignatureHeader,
rawBody: input.rawBody, idempotencyKey: input.idempotencyKey,
});
} else if (trigger.signingMode === "fireflies_hmac") {
+8
View File
@@ -829,3 +829,11 @@ unknown outside heartbeat accounting, never zero. This candidate includes only
the focused local native-probe prerequisite from core PR18103; all candidate
outcomes are separate from frozen39e qualification. Source acceptance is not
permission to run the unused initial.
The hiring journey retains `hire-user-message-checks.json` before grading each
submitted message. Its private receipt contains comment IDs, exact byte counts,
SHA-256 body hashes and comparison results. It contains no raw message bodies or
provider session state. Mention insertion uses ordinary keyboard editing to
remove the editor-added space before typing the next exact source slice. The
exact saved-body check and single-message count remain required.
@@ -11,7 +11,7 @@ test.afterAll(async () => { await fixture?.close(); });
const references = hireHandoffMentions({ companyId: r.companyId, leadId: r.leadId, projectId: r.projectId, campaignId: r.campaignId }, r.agentId,
{ id: r.agentId, companyId: r.companyId, reportsTo: r.leadId, name: `Morgan Reviewer ${r.campaignId}`, icon: "code" },
{ id: r.projectId, companyId: r.companyId, name: `Journey QA hire-delegate-reuse ${r.campaignId}`, color: "#336699" });
const message = (review = false) => `Have the existing ${references.teammate} ${review ? "review the checklist on QA-1 and write a separate saved review" : "write a concise launch checklist as a saved Paperclip document"}. Create exactly one task in ${references.project}, already assigned to that teammate when it is created. Link the result here.`;
const message = (review = false) => `Have the existing ${references.teammate} ${review ? "review the checklist on QA-1 and write a separate saved review" : 'write a concise launch checklist as a saved Paperclip document with the line "Reference: HIREjourney1deadbeef"'}. Create exactly one task in ${references.project}, already assigned to that teammate when it is created. Link the result here.`;
async function open(page: Page, key: string, variant = "valid", mode = "production") {
const url = new URL("/__hire.html", fixture.url); url.searchParams.set("case", key); url.searchParams.set("variant", variant); url.searchParams.set("mode", mode);
await page.goto(url.href);
@@ -36,6 +36,18 @@ export async function sendHireHandoffMessage(page: Page, text: string, reference
await expect(chip).toBeVisible({ timeout: timeout() });
if (await chip.getAttribute("href") !== token.href) throw new JourneyError("failed", "hire_handoff_mention_mismatch");
await page.evaluate(() => new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))));
// Mention insertion leaves the caret after one editor-added space. Remove
// that space through the normal keyboard path; the next source slice owns
// its exact whitespace (including punctuation directly after a mention).
const hasInsertedSpace = await editable.evaluate(element => {
const selection = element.ownerDocument.getSelection();
const node = selection?.anchorNode;
return Boolean(selection?.isCollapsed && node?.nodeType === Node.TEXT_NODE
&& element.contains(node) && selection.anchorOffset > 0
&& node.textContent?.slice(selection.anchorOffset - 1, selection.anchorOffset) === " ");
});
if (!hasInsertedSpace) throw new JourneyError("failed", "hire_handoff_caret_mismatch");
await editable.press("Backspace");
offset = token.at + token.markdown.length;
}
const suffix = text.slice(offset);
@@ -16,7 +16,7 @@ type Row = Record<string, any>;
const directories: string[] = [];
afterEach(async () => { vi.mocked(sendChatMessage).mockReset(); await Promise.all(directories.splice(0).map(directory => rm(directory, { recursive: true, force: true }))); });
async function fixture(options: { readError?: Error; mutate?(agents: Row[], tasks: Row[]): void; ownError?: Error; firstSendError?: Error; connectionList?: Row; connectionReadError?: Error } = {}) {
async function fixture(options: { storedBody?: string; readError?: Error; mutate?(agents: Row[], tasks: Row[]): void; ownError?: Error; firstSendError?: Error; connectionList?: Row; connectionReadError?: Error } = {}) {
const campaignId = "journey-1-deadbeef", names = hireDelegateNames(campaignId), owned: Row[] = [], comments: Row[] = [];
const binding = { connectionId: "approved" }, lead = { id: "lead", companyId: "company", name: `Lead ${campaignId}`, permissions: { canCreateAgents: true }, runtimeConfig: { aiConnection: binding } };
const hire = { id: "hired", companyId: "company", name: names.hire, reportsTo: lead.id, adapterType: "paperclip_runner",
@@ -35,7 +35,7 @@ async function fixture(options: { readError?: Error; mutate?(agents: Row[], task
const stop = new JourneyError("failed", "test_stop_before_delegation");
vi.mocked(sendChatMessage).mockImplementation(async (_page, text) => {
if (sent) throw stop;
sent = true; if (options.firstSendError) throw options.firstSendError; comments.push({ id: "user-comment", authorUserId: "user", body: text });
sent = true; if (options.firstSendError) throw options.firstSendError; comments.push({ id: "user-comment", authorUserId: "user", body: options.storedBody ?? text });
});
const api = { origin: "https://qa.example.test", async get(route: string) {
if (route === "/api/instance/settings/experimental") return { enableAgentChat: true };
@@ -355,3 +355,19 @@ it.each(["earlier-handoff", "foreign-company", "foreign-chat", "wrong-run", "for
{ companyId: "company", chatId: "chat", runId: "callback" })).toBe(false);
expect(clicked).toBe(false);
});
it("retains an exact failed message comparison before grading, without retaining raw bodies", async () => {
const f = await fixture({ storedBody: "A changed private fixture message" });
await expect(f.run()).rejects.toMatchObject({ code: "hire_user_messages_stored_once" });
const raw = await readFile(path.join(f.directory, "hire-user-message-checks.json"), "utf8");
const receipt = JSON.parse(raw);
expect(receipt).toMatchObject({ schema: "paperclip.product-journey.hire-user-messages/v1", checks: [
{ turn: 1, matches: false, added: [{ id: "user-comment", matches: false }] },
] });
expect(receipt.checks[0].expected.sha256).toMatch(/^[a-f0-9]{64}$/);
expect(receipt.checks[0].added[0].body.sha256).not.toBe(receipt.checks[0].expected.sha256);
expect(raw).not.toContain("private fixture message");
expect(raw).not.toContain("Hire exactly one");
expect(sendChatMessage).toHaveBeenCalledTimes(1);
});
@@ -1,3 +1,4 @@
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import { isDeepStrictEqual } from "node:util";
import path from "node:path";
@@ -172,6 +173,10 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target
}
throw new JourneyError("failed", awaitingReply ? "hire_completion_reply_missing" : "hire_chat_not_completed");
};
const messageChecks: Row[] = [];
const bodyReceipt = (body: unknown) => typeof body === "string" ? {
byteSize: Buffer.byteLength(body), sha256: createHash("sha256").update(body).digest("hex"),
} : null;
const turn = async (text: string, count: number, handoff?: ReturnType<typeof hireHandoffMentions>) => {
await page.goto(chatUrl, { waitUntil: "domcontentloaded" });
const before = await api.get<Row | null>(chatPath);
@@ -181,7 +186,13 @@ export async function hireDelegateReuse(context: JourneyContext, session: Target
const state = await waitForIdle(count);
const comments = await api.get<Row[]>(`/api/issues/${state.chat.id}/comments?order=asc`);
const added = comments.filter(row => row.authorUserId === context.user.id && !prior.some(old => old.id === row.id));
check("hire-user-messages-stored-once", added.length === 1 && added[0].body === text);
const matches = added.length === 1 && added[0].body === text;
messageChecks.push({ turn: messageChecks.length + 1, expected: bodyReceipt(text), matches,
added: added.map(row => ({ id: row.id, body: bodyReceipt(row.body), matches: row.body === text })) });
// Keep the actual comparison inputs before a failed grade, without copying
// message bodies, private session state or credentials into this receipt.
await retain("hire-user-message-checks.json", { schema: "paperclip.product-journey.hire-user-messages/v1", checks: messageChecks });
check("hire-user-messages-stored-once", matches);
return state;
};
await session.own({ kind: "agent", name: names.hire, journeyId: "hire-delegate-reuse" });