Merge origin/master into feat/antigravity-swarm-command

Resolve the recovery service import conflict by keeping both the swarm
refusal code (non-retryable continuation) and master's dependency-wake
circuit breaker.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 committed 2026-11-24 15:31:24 -06:00
commit 6f36e2a24a
139 files changed
+13035 -5187

No files matched your search

+23
View File
@@ -487,6 +487,29 @@ saved daily TestOps plan only after an inspected real QA Cloud pass including
usage, artifact/decision evidence and cleanup. The daily driver runs that saved
plan against the registered QA tenant; it does not substitute a local instance.
The scheduled-routine browser actions use the current routine form's Title,
Default agent, Project and Instructions controls. Each picker opens explicitly;
agent selection does not imply project focus. The schedule's normal popover
owns Resume and Pause, and both actions wait for the exact trigger PATCH.
The task-history read returns to the routine page's History field; the separate
/history route contains configuration revisions. The existing scheduled-run,
output attribution, duplicate-run and pause-window checks remain independent.
A credential-free control renders the production form, entity pickers and
routine page in Chromium. It resolves React from the UI workspace, as required
by an isolated pnpm install. It checks exact owner/project selection, refusal of a
missing agent or project, and one Resume/Pause mutation for the owned trigger. Its unrelated
editor/display boundaries are stubbed: AgentAvatar, Identity initials, style
joining, router Link, MarkdownBody, RunButton, TaskSummaryList, MarkdownEditor,
RoutineVariablesEditor, EnvironmentVariablesEditor, and ScheduleEditor (including
its schedule-description formatter). The stub map is next to the browser fixture.
The real Markdown serialization, task-history content and schedule-expression
editor are outside this control's scope. It is not full-stack or QA qualification:
```sh
node --import ./cli/node_modules/tsx/dist/loader.mjs tests/runner-e2e/product-journeys/routine-schedule-ui.browser.mjs
```
The scheduled-routine pause oracle uses a full 65 seconds of monotonic elapsed
time after both pause acknowledgement and work completion. Its enable receipt
uses the server's timestamp; client and server wall clocks are never compared.
@@ -4,6 +4,7 @@ import path from "node:path";
import { createHash } from "node:crypto";
import { afterEach, expect, it, vi } from "vitest";
import { runScheduledRoutine } from "./routine-schedule-flow.js";
import { resolveRoutineAddress } from "../../../ui/src/components/routine-page/routine-routes.js";
import type { JourneyContext, JourneyEvidence, TargetSession } from "./types.js";
// Browser rendering is covered by the real Routines component tests. This entry
@@ -34,6 +35,7 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
const revision = { id: "revision", documentId: document.id, body, createdByAgentId: agent.id,
createdByRunId: fault === "revision-run" ? "foreign-run" : run.id };
const reads: string[] = [];
const visited: string[] = [];
let instructions = "", pastes = 0, triggerCreated = false, responseResolver: ((value: unknown) => void) | undefined;
const routine = () => ({ id: "routine", companyId: "company", title: `Journey QA scheduled routine ${campaignId}`,
projectId: fault === "creation-project" ? "foreign-project" : project.id, assigneeAgentId: agent.id,
@@ -41,7 +43,7 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
description: fault === "creation-description" ? instructions.replaceAll("`", "\\`") : instructions,
concurrencyPolicy: "always_enqueue", triggers: triggerCreated ? [trigger] : [] });
const locator = (name = ""): any => ({ first() { return this; }, getByRole: (_role: string, options: { name?: string } = {}) => locator(options.name),
getByPlaceholder: () => locator(), locator: () => ({
getByPlaceholder: () => locator(), focus: async () => {}, locator: () => ({
fill: async (value: string) => { instructions = value; }, focus: async () => {},
// The real MDX browser discriminator covers serialization. Keep this unit
// editor boundary separate from the production API reads and grade.
@@ -50,9 +52,13 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
pastes += 1; instructions = text;
},
}),
fill: async () => {}, click: async () => {
if (name === "Enable trigger") { trigger.enabled = true; responseResolver?.({ status: () => 200, json: async () => ({ ...trigger }) }); }
if (name === "Pause trigger") trigger.enabled = false;
fill: async (value: string) => { if (name === "Instructions") instructions = value; },
evaluate: async (_action: unknown, text?: string) => {
if (text === undefined) return false;
pastes += 1; instructions = text;
}, click: async () => {
if (name === "Resume") { trigger.enabled = true; responseResolver?.({ status: () => 200, json: async () => ({ ...trigger }) }); }
if (name === "Pause") { trigger.enabled = false; responseResolver?.({ status: () => 200 }); }
if (name === "Create routine") responseResolver?.({ status: () => 201, json: async () => routine() });
} });
const api = { origin: "https://qa.example.test", async post(route: string) {
@@ -76,13 +82,20 @@ async function fixture(fault: "body" | "document-author" | "revision-run" | "cre
if (route === "/api/issues/task/documents/scheduled-summary/revisions/revision") return revision;
throw new Error(`Unexpected fixture read ${route}`);
} };
const page = { getByRole: (_role: string, options: { name?: string } = {}) => locator(options.name), getByPlaceholder: () => locator(),
async goto(url: string) { if (url.endsWith("/routines/routine/runs")) throw new Error("Stop the positive control before the real pause window"); },
const page = { getByRole: (role: string, options: { name?: string } = {}) => {
if (role === "link" && options.name === task.identifier) {
// Stop at the task-link assertion, independently of the address chosen.
// The test below checks that address using the production route resolver.
throw new Error("Stop the positive control before the real pause window");
}
return locator(options.name);
}, getByPlaceholder: () => locator(),
async goto(url: string) { visited.push(url); }, async reload() {},
waitForResponse: () => new Promise(resolve => { responseResolver = resolve; }) };
const context = { api, page, company: { id: "company", issuePrefix: "QA" }, user: { id: "user" }, agent, environmentId: "environment" } as unknown as JourneyContext;
const directory = await mkdtemp(path.join(os.tmpdir(), "routine-attribution-")); directories.push(directory);
const evidence = { checks: [] } as unknown as JourneyEvidence;
return { expectedBody, body, instructions: () => instructions, pastes: () => pastes, evidence, trigger, directory, reads,
return { expectedBody, body, instructions: () => instructions, pastes: () => pastes, evidence, trigger, directory, reads, visited,
run: () => runScheduledRoutine(context, { async own() {} } as unknown as TargetSession, campaignId, evidence,
{ directory, deadlineAt: Date.now() + 10_000 }) };
}
@@ -125,6 +138,10 @@ it("keeps the real journey attribution failure when final trigger disabling also
it("sends the unchanged exact two-line body as a delimited instruction and accepts valid attribution", async () => {
const f = await fixture();
await expect(f.run()).rejects.toMatchObject({ code: "routine_open_history_failed" });
const historyUrl = new URL(f.visited.at(-1)!);
const section = historyUrl.pathname.split("/")[4];
expect(resolveRoutineAddress({ routineId: "routine", section }).view).toBe("routine");
expect(historyUrl.pathname).toBe("/QA/routines/routine");
const block = f.instructions().match(/```text\n([\s\S]*?)\n```/);
expect(block?.[1]).toBe(f.expectedBody);
expect(f.instructions()).toContain("including the final period");
@@ -1,8 +1,9 @@
import { enableRoutineScheduleTrigger } from "./routine-schedule-ui.js";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { describe, expect, it, vi } from "vitest";
import { enableRoutineScheduleTrigger, routineUiStep, withRoutineTriggerCleanup } from "./routine-schedule-flow.js";
import { routineUiStep, withRoutineTriggerCleanup } from "./routine-schedule-flow.js";
import { JourneyError } from "./types.js";
describe("routine trigger cleanup failure reporting", () => {
@@ -31,11 +32,11 @@ describe("routine trigger cleanup failure reporting", () => {
describe("routine UI failure evidence", () => {
it("retains a closed step code without browser messages or form values", async () => {
const error = await routineUiStep("select_project", async () => {
const error = await routineUiStep("fill_form", async () => {
throw new Error("Timeout at https://private.example/?token=secret with form value private-project");
}).catch(value => value);
expect(error).toBeInstanceOf(JourneyError);
expect(error).toMatchObject({ outcome: "failed", code: "routine_select_project_failed", message: "routine_select_project_failed" });
expect(error).toMatchObject({ outcome: "failed", code: "routine_fill_form_failed", message: "routine_fill_form_failed" });
expect(JSON.stringify(error)).not.toMatch(/private|token|secret/);
});
it("keeps a semantic journey failure instead of replacing its evidence code", async () => {
@@ -52,20 +53,16 @@ describe("routine UI failure evidence", () => {
describe("schedule trigger controls", () => {
it("opens the collapsed schedule editor before its single enable action", async () => {
it("opens the schedule popover before one attributed resume action", async () => {
let expanded = false, clicks = 0, resolveResponse!: (value: any) => void;
const response = { status: () => 200 };
const pending = new Promise<any>(resolve => { resolveResponse = resolve; });
const schedule = { getByRole: (_role: string, options: { name: string }) => ({ click: async () => {
if (options.name === "Edit schedule") { expanded = true; return; }
if (options.name !== "Enable trigger" || !expanded) throw new Error("schedule control is not rendered");
const page = { getByRole: (_role: string, options: { name: string | RegExp }) => ({ click: async () => {
if (options.name instanceof RegExp && options.name.test("Change schedule: Every minute")) { expanded = true; return; }
if (options.name !== "Resume" || !expanded) throw new Error("schedule control is not rendered");
clicks += 1;
resolveResponse(response);
} }) };
const page = { getByRole: (role: string, options: { name: string }) => {
if (role === "region" && options.name === "Schedule trigger") return schedule;
return schedule.getByRole(role, options);
}, waitForResponse: () => pending } as unknown as Parameters<typeof enableRoutineScheduleTrigger>[0];
} }), waitForResponse: () => pending } as unknown as Parameters<typeof enableRoutineScheduleTrigger>[0];
expect(await enableRoutineScheduleTrigger(page, "/api/routine-triggers/owned-trigger")).toBe(response);
expect(expanded).toBe(true);
expect(clicks).toBe(1);
@@ -1,10 +1,11 @@
import { fillRoutineCreateForm, enableRoutineScheduleTrigger, setRoutineScheduleEnabled } from "./routine-schedule-ui.js";
import { createObservedReader } from "./observation-read.js";
import { createHash } from "node:crypto";
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { expect } from "@playwright/test";
import { ConnectionFailure } from "../connection-config.js";
import { fillTaskPrompt, withBrowserEvent } from "../user-actions.js";
import { withBrowserEvent } from "../user-actions.js";
import { validateAgentTaskState, waitFor } from "./agent-flows.js";
import { openDocumentAuthoring } from "./task-document-flow.js";
import { scheduledInvocationMatches, schedulePauseMatches, schedulePauseObservationMs, type ScheduledInvocation, type ScheduledTask } from "./routine-schedule-evidence.js";
@@ -12,7 +13,7 @@ import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSes
type Row = Record<string, any>;
const journeyId = "routine-scheduled-run" as const;
type RoutineUiStep = "open_composer" | "select_responsible" | "select_project" | "fill_instructions" | "submit" | "enable_trigger" | "pause_trigger" | "open_history" | "reopen_result";
type RoutineUiStep = "open_composer" | "fill_form" | "submit" | "enable_trigger" | "pause_trigger" | "open_history" | "reopen_result";
export async function routineUiStep<T>(step: RoutineUiStep, action: () => Promise<T>): Promise<T> {
try { return await action(); }
catch (error) {
@@ -21,15 +22,6 @@ export async function routineUiStep<T>(step: RoutineUiStep, action: () => Promis
throw new JourneyError("failed", `routine_${step}_failed`);
}
}
export async function enableRoutineScheduleTrigger(page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string) {
const schedule = page.getByRole("region", { name: "Schedule trigger", exact: true });
// The enable/pause controls are children of the collapsed schedule editor.
await schedule.getByRole("button", { name: "Edit schedule", exact: true }).click();
return withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "PATCH"
&& new URL(response.url()).pathname === triggerRoute),
() => schedule.getByRole("button", { name: "Enable trigger", exact: true }).click());
}
export async function withRoutineTriggerCleanup<T>(input: {
api: Pick<JourneyContext["api"], "patch">; triggerRoute: string; directory: string; run(): Promise<T>;
}): Promise<T> {
@@ -86,21 +78,9 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
await page.getByRole("button", { name: "New routine", exact: true }).first().click();
});
const dialog = page.getByRole("dialog");
await routineUiStep("select_responsible", async () => {
await dialog.getByPlaceholder("Routine title", { exact: true }).fill(title);
await dialog.getByRole("button", { name: "Responsible", exact: true }).click();
await page.getByPlaceholder("Search responsible...", { exact: true }).fill(agent.name);
await page.getByRole("button", { name: agent.name, exact: true }).click();
});
await routineUiStep("select_project", async () => {
// Selecting Responsible focuses Project and opens its picker. Clicking
// its trigger again closes the picker before the search field can fill.
const projectSearch = page.getByPlaceholder("Search projects...", { exact: true });
await expect(projectSearch).toBeVisible();
await projectSearch.fill(projectName);
await page.getByRole("button", { name: projectName, exact: true }).click();
});
await routineUiStep("fill_instructions", () => fillTaskPrompt(dialog.locator('[contenteditable="true"]'), prompt));
await routineUiStep("fill_form", () => fillRoutineCreateForm(page, {
title, agentName: agent.name, projectName, prompt,
}));
await session.own({ kind: "routine", name: title, journeyId });
const response = await routineUiStep("submit", () => withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "POST"
@@ -149,7 +129,7 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
let pausedAt = 0;
await withRoutineTriggerCleanup({ api, triggerRoute, directory: options.directory, run: async () => {
const enabledResponse = await routineUiStep("enable_trigger", async () => {
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}/triggers`, { waitUntil: "domcontentloaded" });
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}`, { waitUntil: "domcontentloaded" });
return enableRoutineScheduleTrigger(page, triggerRoute);
});
if (enabledResponse.status() !== 200) throw new JourneyError("failed", "routine_schedule_enable_failed");
@@ -159,7 +139,8 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
|| enabledTrigger.enabled !== true || !Number.isFinite(enabledAt)) throw new JourneyError("failed", "routine_schedule_enable_receipt_missing");
await expect.poll(async () => (await readTrigger()).enabled).toBe(true);
const first = await waitFor(options.deadlineAt, runs, rows => rows.length > 0 && Boolean(rows[0]?.linkedIssueId), "scheduled_invocation_missing");
await routineUiStep("pause_trigger", () => page.getByRole("button", { name: "Pause trigger", exact: true }).click());
const pausedResponse = await routineUiStep("pause_trigger", () => setRoutineScheduleEnabled(page, triggerRoute, false));
if (pausedResponse.status() !== 200) throw new JourneyError("failed", "routine_schedule_pause_failed");
await expect.poll(async () => (await readTrigger()).enabled).toBe(false);
pausedAt = performance.now();
const task = await readObserved<ScheduledTask & { title: string }>(`/api/issues/${first[0]!.linkedIssueId}`);
@@ -205,7 +186,7 @@ export async function runScheduledRoutine(context: JourneyContext, session: Targ
check("routine-result-attributed", Object.values(matches).every(Boolean));
if (typeof state.currentIssue.identifier !== "string" || !state.currentIssue.identifier) throw new JourneyError("failed", "routine_task_identifier_missing");
await routineUiStep("open_history", async () => {
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}/runs`, { waitUntil: "domcontentloaded" });
await page.goto(`${api.origin}/${company.issuePrefix}/routines/${routine.id}`, { waitUntil: "domcontentloaded" });
await page.reload();
await expect(page.getByRole("link", { name: state.currentIssue.identifier, exact: false }).first()).toBeVisible();
});
@@ -0,0 +1,106 @@
import assert from "node:assert/strict";
import path from "node:path";
import { existsSync } from "node:fs";
import { createRequire } from "node:module";
import { fileURLToPath } from "node:url";
import { build } from "esbuild";
import { chromium } from "@playwright/test";
import { fillRoutineCreateForm, enableRoutineScheduleTrigger, setRoutineScheduleEnabled } from "./routine-schedule-ui.ts";
// Render the production form, entity pickers, schedule rows and Radix primitives.
// Only unrelated display/editor boundaries are replaced. No app, provider or QA
// credential is needed. The full journey retains independent API readback/grades.
const root = fileURLToPath(new URL("../../../", import.meta.url));
const uiRoot = path.join(root, "ui");
const uiRequire = createRequire(path.join(uiRoot, "package.json"));
const stubs = {
"@/components/AgentAvatar": "export const AgentAvatar = () => null;",
"@/components/Identity": "export const deriveInitials = name => name.slice(0, 2);",
"@/lib/utils": "export const cn = (...values) => values.filter(Boolean).join(' ');",
"../lib/utils": "export const cn = (...values) => values.filter(Boolean).join(' ');",
"@/lib/router": "export const Link = ({to, children, ...props}) => <a href={to} {...props}>{children}</a>;",
"@/components/MarkdownBody": "export const MarkdownBody = () => null;",
"@/components/AgentActionButtons": "export const RunButton = () => null;",
"@/components/TaskSummaryList": "export const TaskSummaryList = () => null;",
"@/components/MarkdownEditor": `export const MarkdownEditor = ({value, onChange, ariaLabel}) =>
<textarea aria-label={ariaLabel} value={value} onChange={event => onChange(event.target.value)} />;`,
"@/components/RoutineVariablesEditor": "export const RoutineVariablesEditor = () => null;",
"@/components/environment-variables-editor": "export const EnvironmentVariablesEditor = () => null;",
"@/components/ScheduleEditor": `export const ScheduleEditor = () => null;
export const describeSchedule = () => 'Every minute';`,
};
const compiled = await build({
absWorkingDir: root,
stdin: { resolveDir: uiRoot, loader: "tsx", contents: `
import React, { useState } from 'react';
import { createRoot } from 'react-dom/client';
import { RoutineEditDialog, EMPTY_ROUTINE_FORM_DRAFT } from './src/components/routine-page/RoutineEditDialog';
import { RoutinePage } from './src/components/routine-page/RoutinePage';
const agent = { id: 'owned-agent', name: 'Owned QA agent' };
const project = { id: 'owned-project', name: 'Owned QA project' };
function Form() { return <RoutineEditDialog mode="create" open initial={EMPTY_ROUTINE_FORM_DRAFT}
onOpenChange={() => {}} agents={[{id:'other-agent',name:'Other agent'},agent]}
projects={[{id:'other-project',name:'Other project'},project]} people={[]} secrets={[]}
onSave={draft => { window.saved = draft; window.saves++; }} />; }
function Detail() {
const [enabled,setEnabled] = useState(false);
const routine = { id:'owned-routine', title:'Schedule control', status:'active', assigneeAgentId:agent.id,
description:'', variables:[], env:null, triggers:[{id:'owned-trigger',kind:'schedule',enabled,
cronExpression:'* * * * *',timezone:'America/Chicago'}] };
return <RoutinePage routine={routine} agent={agent} project={project} history={[]} responsibilities={[]}
onEdit={() => {}} onSaveSchedule={() => {}} onRemoveSchedule={() => {}}
onSetTriggerPaused={async (id, paused) => { await fetch('/api/routine-triggers/'+id,
{method:'PATCH',headers:{'Content-Type':'application/json'},body:JSON.stringify({enabled:!paused})}); setEnabled(!paused); }} />;
}
window.saves=0; window.show = mode => createRoot(document.getElementById('root')).render(mode==='form'?<Form/>:<Detail/>);
` },
bundle: true, write: false, format: "iife", jsx: "automatic",
plugins: [{ name: "unrelated-ui-boundaries", setup(builder) {
builder.onResolve({ filter: /.*/ }, args => {
// React is owned by ui, not by the repository root in an isolated pnpm install.
if (/^react(?:-dom)?(?:\/|$)/.test(args.path)) return { path: uiRequire.resolve(args.path) };
if (stubs[args.path]) return { path: args.path, namespace: "fixture" };
if (args.path.startsWith("@/")) {
const base = path.join(root, "ui/src", args.path.slice(2));
return { path: [base, base+".ts", base+".tsx"].find(existsSync) ?? base };
}
});
builder.onLoad({ filter: /.*/, namespace: "fixture" }, args => ({ contents: stubs[args.path], loader: "tsx", resolveDir: uiRoot }));
} }],
});
const browser = await chromium.launch({ headless: true,
...(process.env.BROWSER_EXECUTABLE_PATH ? { executablePath: process.env.BROWSER_EXECUTABLE_PATH } : {}) });
try {
const page = await browser.newPage();
page.setDefaultTimeout(1500);
await page.route('https://routine.fixture/**', route => route.fulfill({contentType:'text/html',body:'<div id="root"></div>'}));
const mount = async mode => { await page.goto('https://routine.fixture/'); await page.addScriptTag({content:compiled.outputFiles[0].text}); await page.evaluate(mode => window.show(mode),mode); };
await mount('form');
const input = {title:'Scheduled check',agentName:'Owned QA agent',projectName:'Owned QA project',prompt:'Save the exact scheduled result.'};
await fillRoutineCreateForm(page,input);
await page.getByRole('button',{name:'Create routine',exact:true}).click();
const saved = await page.evaluate(() => ({draft:window.saved,count:window.saves}));
assert.equal(saved.count,1);
assert.equal(saved.draft.title,input.title);
assert.equal(saved.draft.assigneeAgentId,'owned-agent');
assert.equal(saved.draft.projectId,'owned-project');
assert.equal(saved.draft.description,input.prompt);
assert.equal(saved.draft.schedule,null,'creation must not start a schedule');
await mount('form');
await assert.rejects(fillRoutineCreateForm(page,{...input,agentName:'Missing agent'}));
assert.equal(await page.evaluate(() => window.saves),0,'a missing agent cannot submit or silently use another owner');
await mount('form');
await assert.rejects(fillRoutineCreateForm(page,{...input,projectName:'Missing project'}));
assert.equal(await page.evaluate(() => window.saves),0,'a missing project cannot silently select another project');
await mount('detail');
const patches=[];
await page.route('https://routine.fixture/api/routine-triggers/*',async route => {
patches.push({path:new URL(route.request().url()).pathname,body:route.request().postDataJSON()});
await route.fulfill({contentType:'application/json',body:JSON.stringify({id:'owned-trigger',enabled:patches.at(-1).body.enabled})});
});
assert.equal((await enableRoutineScheduleTrigger(page,'/api/routine-triggers/owned-trigger')).status(),200);
assert.equal((await setRoutineScheduleEnabled(page,'/api/routine-triggers/owned-trigger',false)).status(),200);
assert.deepEqual(patches,[{path:'/api/routine-triggers/owned-trigger',body:{enabled:true}},
{path:'/api/routine-triggers/owned-trigger',body:{enabled:false}}]);
console.log('Production routine form, exact owner/project, missing agent/project refusal and schedule resume/pause passed.');
} finally { await browser.close(); }
@@ -0,0 +1,34 @@
import { type Page } from "@playwright/test";
import { fillTaskPrompt, withBrowserEvent } from "../user-actions.js";
/** Use the production form's labels and explicitly open each independent picker. */
export async function fillRoutineCreateForm(page: Page, input: {
title: string; agentName: string; projectName: string; prompt: string;
}) {
const dialog = page.getByRole("dialog");
await dialog.getByRole("textbox", { name: "Title", exact: true }).fill(input.title);
// Focus is idempotent: InlineEntitySelector opens on focus, while a click
// can close a picker that keyboard focus has already opened.
await dialog.getByRole("button", { name: "Choose an agent", exact: true }).focus();
await dialog.getByPlaceholder("Search agents…", { exact: true }).fill(input.agentName);
await dialog.getByRole("button", { name: input.agentName, exact: true }).click();
await dialog.getByRole("button", { name: "No project", exact: true }).focus();
await dialog.getByPlaceholder("Search projects…", { exact: true }).fill(input.projectName);
await dialog.getByRole("button", { name: input.projectName, exact: true }).click();
await fillTaskPrompt(dialog.getByRole("textbox", { name: "Instructions", exact: true }), input.prompt);
}
/** The fixture owns exactly one schedule; use its normal page popover. */
export async function setRoutineScheduleEnabled(
page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string, enabled: boolean,
) {
await page.getByRole("button", { name: /^Change schedule:/ }).click();
return withBrowserEvent(
() => page.waitForResponse(response => response.request().method() === "PATCH"
&& new URL(response.url()).pathname === triggerRoute),
() => page.getByRole("button", { name: enabled ? "Resume" : "Pause", exact: true }).click());
}
export async function enableRoutineScheduleTrigger(page: Pick<Page, "getByRole" | "waitForResponse">, triggerRoute: string) {
return setRoutineScheduleEnabled(page, triggerRoute, true);
}
@@ -36,6 +36,12 @@ export function dependencyNewAgentRuns(runs: Row[], startingRuns: Row[]) {
const priorIds = new Set(startingRuns.map(run => run.id));
return runs.filter(run => !priorIds.has(run.id));
}
export function dependencyRunProjectionsAgree(point: DependencyPoint, startingRuns: Row[], expectedRun?: Row) {
const newRuns = dependencyNewAgentRuns(point.agentRuns, startingRuns);
return point.dependentRuns.length === 1 && newRuns.length === 1
&& runFacts(point.dependentRuns[0]!) === runFacts(newRuns[0]!)
&& (!expectedRun || runFacts(point.dependentRuns[0]!) === runFacts(expectedRun));
}
export function dependencyRunIssueId(run: Row) {
const ids = [run.issueId, run.nativeIssueId, run.contextSnapshot?.issueId, run.contextSnapshot?.taskId].filter(value => value != null);
return ids.length && ids.every(nonempty) && new Set(ids).size === 1 ? ids[0] as string : undefined;
@@ -32,7 +32,14 @@ blocker completion audit. No agent work is permitted on the human-owned blocker.
The case requires `company`, `board-user`, `task-write`, and `agent`. It declares
one work run, uses the existing bounded case budget, and shares the original
campaign deadline. The native agent must have nonblank provider and model
campaign deadline.
The task and agent run reads can straddle completion. The completion wait requires
both projections to agree on the same run facts before saving the finished point.
After reopening, it applies the same settled check: done task, one succeeded and
committed run, agreeing projections, saved document and revision, and no active locks.
The reopened run facts must also match the already-settled finished run.
It uses the original deadline and does not replace either independent observation.
The native agent must have nonblank provider and model
identifiers before any observation read or task creation. An incomplete execution
identity returns `unsupported` without task or agent work.
It saves the agent's starting run history and retains those
@@ -1,3 +1,4 @@
import { AsyncLocalStorage } from "node:async_hooks";
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
@@ -20,12 +21,25 @@ vi.mock("@playwright/test", () => ({ expect: Object.assign((locator: any) => ({
import { taskDependencyResume } from "./task-dependency-resume.js";
interface FixtureOptions { priorRuns?: number; unrelatedActivity?: number; ownedActivity?: number; agentActivity?: number; missingActivity?: boolean; activePrior?: boolean;
closedPanel?: "properties" | "toggle"; missingProperty?: boolean; missingStatusChoice?: boolean }
laggingAgentReads?: number; reopenedLaggingAgentReads?: number; reopenedStale?: "task-run" | "both-runs" | "task-status" | "document" | "locks" | "native-phase" | "run-facts"; reopenedStaleReads?: number; closedPanel?: "properties" | "toggle"; missingProperty?: boolean; missingStatusChoice?: boolean }
async function fixture(premature = false, options: FixtureOptions = {}) {
const directory = await mkdtemp(path.join(os.tmpdir(), "dependency-flow-"));
const f = dependencyEvidenceFixture(), s = f.scope;
const blocker = { ...f.created.blocker }, dependent = { ...f.created.dependent };
const actions: string[] = [], owned: any[] = [], writes: unknown[] = [], reads: string[] = [];
const projection = new AsyncLocalStorage<"task" | "agent">();
const agentReads = { finished: 0, reopened: 0 };
const detailReads: Array<{ projection: string; stage: string; status: string }> = [];
let reopened = false;
const staleReads: Record<string, number> = {};
const stale = (key: string) => reopened && (staleReads[key] = (staleReads[key] ?? 0) + 1) <= (options.reopenedStaleReads ?? 0);
// Carry the list's projection through both summary normalization and detail mapping.
// The concurrent detail requests use the same URL; call order must not identify them.
const projectedRows = (rows: any[], source: "task" | "agent"): any[] => {
Object.defineProperty(rows, "map", { value: (callback: (...args: any[]) => any) =>
projectedRows(Array.prototype.map.call(rows, (...args: any[]) => projection.run(source, () => callback(...args))), source) });
return rows;
};
let completed = false, assigned = false, panelOpen = !options.closedPanel;
const reference = () => /review reference is ([a-f0-9]{32})/.exec(blocker.description)?.[1];
const output = () => JSON.stringify({ reference: reference(), blockerIdentifier: s.blockerIdentifier });
@@ -89,23 +103,45 @@ async function fixture(premature = false, options: FixtureOptions = {}) {
},
getByPlaceholder(name: string) { return locator(name); },
getByTestId(name: string) { return locator(name); },
async goto(url: string) { actions.push(`goto:${url}`); }, async reload() { actions.push("reload"); },
async goto(url: string) { actions.push(`goto:${url}`); }, async reload() { actions.push("reload"); if (completed) reopened = true; },
};
const api: any = { origin: "https://qa.example.test", async get(route: string) {
reads.push(route);
if (route === `/api/issues/${s.blockerId}`) return structuredClone(blocker);
if (route === `/api/issues/${s.dependentId}`) return structuredClone(dependent);
if (route === `/api/issues/${s.dependentId}`) {
const task = structuredClone(dependent);
if (options.reopenedStale === "task-status" && stale("task-status")) task.status = "in_progress";
if (options.reopenedStale === "locks" && stale("locks")) task.executionRunId = "run";
return task;
}
if (route === `/api/issues/${s.blockerId}/runs`) return [];
if (route === `/api/issues/${s.dependentId}/runs`) return runs().map(r => ({ runId: r.id }));
if (route.includes("/heartbeat-runs?")) return [...runs(), ...structuredClone(priorRuns)];
if (route === "/api/heartbeat-runs/run") return runs()[0];
if (route === `/api/issues/${s.dependentId}/runs`) return projectedRows(runs().map(r => ({ runId: r.id })), "task");
if (route.includes("/heartbeat-runs?")) return projectedRows([...runs(), ...structuredClone(priorRuns)], "agent");
if (route === "/api/heartbeat-runs/run") {
const run = runs()[0], source = projection.getStore(), stage = reopened ? "reopened" : "finished";
if (!source) throw new Error("run_detail_projection_missing");
if (source === "agent") {
agentReads[stage]++;
const lag = reopened ? options.reopenedLaggingAgentReads : options.laggingAgentReads;
if (agentReads[stage] <= (lag ?? 0)) run.status = "running";
}
if ((options.reopenedStale === "both-runs" || options.reopenedStale === "task-run" && source === "task")
&& stale(source)) run.status = "running";
if (options.reopenedStale === "native-phase" && stale(source)) run.nativePhase = "running";
if (options.reopenedStale === "run-facts" && stale(source)) run.startedAt = "2019-12-31T23:59:00Z";
detailReads.push({ projection: source, stage, status: run.status });
return run;
}
if (route === `/api/issues/${s.blockerId}/activity`) return completed ? structuredClone(f.reopened.activity) : [];
if (route === `/api/issues/${s.dependentId}/activity`) return activity(options.ownedActivity ?? 0, s.dependentId);
if (route === `/api/companies/${s.companyId}/activity?agentId=${s.agentId}&limit=500`) {
return options.missingActivity ? undefined : activity(options.agentActivity ?? 0, "prior-task", s.agentId);
}
if (route === `/api/companies/${s.companyId}/activity?limit=500`) return activity(options.unrelatedActivity ?? 0, "unrelated-task").slice(0, 500);
if (route === `/api/issues/${s.dependentId}/documents`) return completed ? [taskDocument()] : [];
if (route === `/api/issues/${s.dependentId}/documents`) {
if (options.reopenedStale === "document" && stale("document")) return [];
return completed ? [taskDocument()] : [];
}
if (route.endsWith("/documents/dependency-proof")) return taskDocument();
if (route.endsWith("/revisions/revision")) return revision();
throw new Error(`unexpected_read:${route}`);
@@ -115,7 +151,7 @@ async function fixture(premature = false, options: FixtureOptions = {}) {
capabilities: ["company", "board-user", "task-write", "agent"], agent: { id: s.agentId, name: "Fixture agent", provider: s.provider, model: s.model, runtimeMode: "native" } } as JourneyContext;
const session = { own: vi.fn(async resource => { owned.push(resource); }) } as unknown as TargetSession;
const evidence = { checks: [] } as unknown as JourneyEvidence;
return { directory, context, session, evidence, actions, owned, writes, reads };
return { directory, context, session, evidence, actions, owned, writes, reads, detailReads, staleReads };
}
afterEach(() => { vi.useRealTimers(); controls.create.mockReset(); });
describe("dependency browser flow orchestration", () => {
@@ -206,6 +242,7 @@ describe("dependency browser flow orchestration", () => {
});
it.each([
["empty history", {}],
["agent detail still running after task detail completed", { laggingAgentReads: 2 }],
["completed earlier campaign runs", { priorRuns: 3 }],
["more than 100 earlier campaign runs", { priorRuns: 150 }],
["more than 500 unrelated company events", { unrelatedActivity: 800 }],
@@ -218,6 +255,10 @@ describe("dependency browser flow orchestration", () => {
{ deadlineAt: Date.now() + 60_000, directory: f.directory });
await vi.advanceTimersByTimeAsync(11_000); await operation;
expect(f.evidence.checks).toHaveLength(8); expect(f.evidence.checks.every(check => check.passed)).toBe(true);
if ("laggingAgentReads" in options) {
expect(f.detailReads.filter(read => read.projection === "agent" && read.status === "running")).toHaveLength(options.laggingAgentReads);
expect(f.detailReads.filter(read => read.projection === "task").every(read => read.status === "succeeded")).toBe(true);
}
expect(f.writes).toEqual([]);
expect(f.actions.indexOf("click:Blocked")).toBeLessThan(f.actions.indexOf("click:agent-choice"));
expect(f.actions.indexOf("click:agent-choice")).toBeLessThan(f.actions.indexOf("click:Done"));
@@ -235,6 +276,65 @@ describe("dependency browser flow orchestration", () => {
expect(f.reads).not.toContain("/api/companies/company/activity?limit=500");
} finally { await rm(f.directory, { recursive: true, force: true }); }
});
it.each([2, Infinity])("waits for reopened-only agent lag (%s reads) within the original deadline", async lag => {
const f = await fixture(false, { reopenedLaggingAgentReads: lag });
vi.useFakeTimers(); vi.setSystemTime(new Date("2020-01-01T00:00:00Z"));
const startedAt = Date.now();
try {
const operation = taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
{ deadlineAt: startedAt + 13_000, directory: f.directory });
const outcome = lag === Infinity
? expect(operation).rejects.toMatchObject({ code: "dependency_reopen_deadline" })
: expect(operation).resolves.toBeUndefined();
await vi.advanceTimersByTimeAsync(13_000); await outcome;
const saved = JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"));
expect(saved.finished.dependentRuns[0].status).toBe("succeeded");
expect(saved.finished.agentRuns[0].status).toBe("succeeded");
expect(f.detailReads.filter(read => read.projection === "task").every(read => read.status === "succeeded")).toBe(true);
expect(f.detailReads.filter(read => read.projection === "agent" && read.stage === "reopened" && read.status === "running")).toHaveLength(lag === Infinity ? 3 : lag);
expect(saved.reopened.agentRuns[0].status).toBe(lag === Infinity ? "running" : "succeeded");
expect(f.evidence.checks).toHaveLength(lag === Infinity ? 0 : 8);
expect(f.evidence.checks.every(check => check.passed)).toBe(true);
expect(f.writes).toEqual([]);
} finally { await rm(f.directory, { recursive: true, force: true }); }
});
it.each((["task-run", "both-runs", "task-status", "document", "locks", "native-phase", "run-facts"] as const)
.flatMap(stale => [2, Infinity].map(lag => ({ stale, lag }))))(
"waits for reopened $stale staleness ($lag reads) within the original deadline", async ({ stale, lag }) => {
const f = await fixture(false, { reopenedStale: stale, reopenedStaleReads: lag });
vi.useFakeTimers(); vi.setSystemTime(new Date("2020-01-01T00:00:00Z"));
try {
const operation = taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
{ deadlineAt: Date.now() + 13_000, directory: f.directory });
const outcome = lag === Infinity
? expect(operation).rejects.toMatchObject({ code: "dependency_reopen_deadline" })
: expect(operation).resolves.toBeUndefined();
await vi.advanceTimersByTimeAsync(13_000); await outcome;
const saved = JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"));
expect(saved.finished.dependentRuns[0].status).toBe("succeeded");
expect(saved.finished.agentRuns[0].status).toBe("succeeded");
expect(Object.values(f.staleReads)).not.toHaveLength(0);
expect(Object.values(f.staleReads).every(count => count === 3)).toBe(true);
expect(f.evidence.checks).toHaveLength(lag === Infinity ? 0 : 8);
expect(f.evidence.checks.every(check => check.passed)).toBe(true);
expect(saved.stage).toBe(lag === Infinity ? "reopen_result" : "complete");
expect(f.writes).toEqual([]);
} finally { await rm(f.directory, { recursive: true, force: true }); }
});
it("keeps a permanently conflicting agent projection failed at the original deadline", async () => {
const f = await fixture(false, { laggingAgentReads: Infinity });
vi.useFakeTimers(); vi.setSystemTime(new Date("2020-01-01T00:00:00Z"));
try {
const operation = expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
{ deadlineAt: Date.now() + 13_000, directory: f.directory })).rejects.toMatchObject({ code: "dependency_resume_deadline" });
await vi.advanceTimersByTimeAsync(13_000); await operation;
const saved = JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"));
expect(saved.finished.dependentRuns[0].status).toBe("succeeded");
expect(saved.finished.agentRuns[0].status).toBe("running");
expect(f.evidence.checks).toEqual([]);
expect(f.writes).toEqual([]);
} finally { await rm(f.directory, { recursive: true, force: true }); }
});
it.each(["properties", "toggle"] as const)("opens a closed properties pane through its %s control before linking", async closedPanel => {
const f = await fixture(false, { closedPanel }); vi.useFakeTimers(); vi.setSystemTime(new Date("2020-01-01T00:00:00Z"));
try {
@@ -7,7 +7,7 @@ import { HEARTBEAT_RUN_LIST_MAX_LIMIT } from "../../../packages/shared/src/const
import { createTaskThroughUi } from "../user-actions.js";
import { createObservedReader } from "./observation-read.js";
import { openDocumentAuthoring } from "./task-document-flow.js";
import { DEPENDENCY_IDLE_MS, dependencyNewAgentRuns, gradeTaskDependencyResume, type DependencyEvidence, type DependencyPoint, type DependencyScope } from "./task-dependency-resume-evidence.js";
import { DEPENDENCY_IDLE_MS, dependencyNewAgentRuns, dependencyRunProjectionsAgree, gradeTaskDependencyResume, type DependencyEvidence, type DependencyPoint, type DependencyScope } from "./task-dependency-resume-evidence.js";
import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js";
type Row = Record<string, any>;
@@ -189,24 +189,32 @@ export async function taskDependencyResume(context: JourneyContext, session: Tar
await setStatus(context, "Done");
await expect.poll(async () => (await read.get<Row>(`/api/issues/${blocker.issueId}`)).status).toBe("done");
observations.released = await observe();
const settled = (point: DependencyPoint | undefined, expectedRun?: Row): point is DependencyPoint => Boolean(point
&& point.dependent.status === "done" && point.dependentRuns.length === 1
&& point.dependentRuns[0]?.status === "succeeded" && point.dependentRuns[0]?.nativePhase === "committed"
&& point.document && point.revision && dependencyRunProjectionsAgree(point, startingRuns, expectedRun)
&& !point.dependent.executionRunId && !point.dependent.checkoutRunId);
stage = "await_automatic_resume";
while (Date.now() < options.deadlineAt) {
const point = await observe(); observations.finished = point;
if (point.dependent.status === "done" && point.dependentRuns.length === 1 && point.dependentRuns[0]?.status === "succeeded"
&& point.dependentRuns[0]?.nativePhase === "committed" && point.document && point.revision
&& !point.dependent.executionRunId && !point.dependent.checkoutRunId) break;
if (settled(point)) break;
await new Promise(resolve => setTimeout(resolve, 1000));
}
if (!observations.finished || observations.finished.dependent.status !== "done" || observations.finished.dependentRuns[0]?.status !== "succeeded"
|| observations.finished.dependentRuns[0]?.nativePhase !== "committed" || !observations.finished.document || !observations.finished.revision) {
throw new JourneyError("failed", "dependency_resume_deadline");
}
if (!settled(observations.finished)) throw new JourneyError("failed", "dependency_resume_deadline");
const finishedRun = observations.finished.dependentRuns[0]!;
stage = "reopen_result";
await page.goto(url(dependentSaved.identifier ?? dependent.issueId), { waitUntil: "domcontentloaded" });
await page.reload(); await openDocumentAuthoring(context);
const document = page.locator(`#document-${documentKey}`);
await expect(document).toContainText(reference);
observations.reopened = await observe();
while (!settled(observations.reopened, finishedRun)) {
const remaining = options.deadlineAt - Date.now();
if (remaining <= 0) throw new JourneyError("failed", "dependency_reopen_deadline");
await new Promise(resolve => setTimeout(resolve, Math.min(1000, remaining)));
if (Date.now() >= options.deadlineAt) throw new JourneyError("failed", "dependency_reopen_deadline");
observations.reopened = await observe();
}
observations.reopened.resultVisible = await document.isVisible() && (await document.textContent())?.includes(reference) === true;
const checks = gradeTaskDependencyResume({ ...observations, scope } as DependencyEvidence);
evidence.checks.push(...checks);
+112 -10
View File
@@ -7,13 +7,115 @@ import { fileURLToPath } from "node:url";
const root = fileURLToPath(new URL("../../", import.meta.url));
const vitest = path.join(root, "node_modules/vitest/vitest.mjs");
const prefix = "[runner-e2e:unit]";
const args = process.argv.slice(2);
if (args[0] === "--") args.shift();
const NODE_TEST_FILES = [
"tests/runner-e2e/product-regression-testops.test.mjs",
"tests/runner-e2e/reliability-testops.test.mjs",
"tests/runner-e2e/artifact-budget.test.mjs",
"tests/runner-e2e/native-completion-checks.test.mjs",
"tests/runner-e2e/native-completion-git-source.test.mjs",
"tests/runner-e2e/native-completion-source-contract.test.mjs",
"tests/runner-e2e/chat-feature-testops-api.test.mjs",
"tests/runner-e2e/chat-feature-testops-cli.test.mjs",
"tests/runner-e2e/chat-feature-testops-results.test.mjs",
"tests/runner-e2e/testops-chat-reporter.test.mjs",
"tests/runner-e2e/chat-feature-testops-retained-verification.node-test.mjs",
"tests/runner-e2e/chat-completion-testops-api.test.mjs",
"tests/runner-e2e/chat-completion-testops-contract.test.mjs",
"tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs",
"tests/runner-e2e/chat-full-catalog-testops-reconcile.test.mjs",
"tests/runner-e2e/chat-full-catalog-testops-adapter.test.mjs",
"tests/runner-e2e/chat-catalog-testops-streaming.test.mjs",
];
function failUsage(message) {
console.error(`${prefix} ${message}`);
process.exit(1);
}
function parseIntArg(raw, flag, min) {
const parsed = Number(raw);
if (raw === undefined || raw.trim() === "" || !Number.isInteger(parsed) || parsed < min) {
failUsage(`${flag} must be an integer >= ${min}. Received ${JSON.stringify(raw)}.`);
}
return parsed;
}
function parseArgs(argv) {
const rawArgs = [...argv];
if (rawArgs[0] === "--") rawArgs.shift();
let shardIndex = null;
let shardCount = null;
let dryRun = false;
const passthrough = [];
for (let i = 0; i < rawArgs.length; i += 1) {
const arg = rawArgs[i];
if (arg === "--dry-run") {
dryRun = true;
continue;
}
if (arg === "--shard-index") {
shardIndex = parseIntArg(rawArgs[i + 1], arg, 0);
i += 1;
continue;
}
if (arg.startsWith("--shard-index=")) {
shardIndex = parseIntArg(arg.slice("--shard-index=".length), "--shard-index", 0);
continue;
}
if (arg === "--shard-count") {
shardCount = parseIntArg(rawArgs[i + 1], arg, 1);
i += 1;
continue;
}
if (arg.startsWith("--shard-count=")) {
shardCount = parseIntArg(arg.slice("--shard-count=".length), "--shard-count", 1);
continue;
}
passthrough.push(arg);
}
if ((shardIndex === null) !== (shardCount === null)) {
failUsage("--shard-index and --shard-count must be provided together.");
}
if (shardIndex !== null && shardIndex >= shardCount) {
failUsage(`--shard-index must be less than --shard-count. Received ${shardIndex} of ${shardCount}.`);
}
if (shardIndex !== null && passthrough.some((arg) => arg === "--shard" || arg.startsWith("--shard="))) {
failUsage("--shard cannot be combined with --shard-index/--shard-count.");
}
return { shardIndex, shardCount, dryRun, passthrough };
}
const { shardIndex, shardCount, dryRun, passthrough } = parseArgs(process.argv.slice(2));
if (!existsSync(vitest)) {
console.error(`${prefix} launcher/environment failure: Vitest is not installed. Run pnpm install before validation.`);
process.exit(2);
}
const vitestShardArgs = shardCount !== null && shardCount > 1
? [`--shard=${shardIndex + 1}/${shardCount}`]
: [];
const nodeTestFiles = shardCount !== null && shardCount > 1
? NODE_TEST_FILES.filter((_, index) => index % shardCount === shardIndex)
: [...NODE_TEST_FILES];
const vitestArgs = ["run", "--config", "tests/runner-e2e/vitest.config.ts", ...vitestShardArgs, ...passthrough];
if (dryRun) {
console.log(JSON.stringify({
shardIndex,
shardCount,
vitestShard: vitestShardArgs[0] ?? null,
vitestArgs,
nodeTestFiles,
}, null, 2));
process.exit(0);
}
// Load after the check: a missing install must still report the launcher failure.
const { invocationEnv } = await import(new URL("../../scripts/ci-profile/record.mjs", import.meta.url).href);
@@ -22,17 +124,17 @@ delete env.NODE_PATH;
delete env.NODE_OPTIONS;
env.NODE_COMPILE_CACHE ??= path.join(tmpdir(), "paperclip-runner-e2e-compile-cache");
for (const [name, command] of [
const steps = [
// Server modules under test import the built plugin SDK (and shared) package.
["Plugin build dependencies", ["scripts/ensure-plugin-build-deps.mjs"]],
["Vitest", [vitest, "run", "--config", "tests/runner-e2e/vitest.config.ts", ...args]],
["Vitest", [vitest, ...vitestArgs]],
// The wrapper adds the CI profiling reporter when PAPERCLIP_CI_PROFILE is set.
["Node tests", ["scripts/ci-profile/node-test.mjs", "tests/runner-e2e/product-regression-testops.test.mjs", "tests/runner-e2e/reliability-testops.test.mjs", "tests/runner-e2e/artifact-budget.test.mjs", "tests/runner-e2e/native-completion-checks.test.mjs",
"tests/runner-e2e/native-completion-git-source.test.mjs", "tests/runner-e2e/native-completion-source-contract.test.mjs",
"tests/runner-e2e/chat-feature-testops-api.test.mjs", "tests/runner-e2e/chat-feature-testops-cli.test.mjs", "tests/runner-e2e/chat-feature-testops-results.test.mjs", "tests/runner-e2e/testops-chat-reporter.test.mjs", "tests/runner-e2e/chat-feature-testops-retained-verification.node-test.mjs",
"tests/runner-e2e/chat-completion-testops-api.test.mjs", "tests/runner-e2e/chat-completion-testops-contract.test.mjs",
"tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs", "tests/runner-e2e/chat-full-catalog-testops-reconcile.test.mjs", "tests/runner-e2e/chat-full-catalog-testops-adapter.test.mjs", "tests/runner-e2e/chat-catalog-testops-streaming.test.mjs"]],
]) {
...(nodeTestFiles.length > 0
? [["Node tests", ["scripts/ci-profile/node-test.mjs", ...nodeTestFiles]]]
: []),
];
for (const [name, command] of steps) {
const result = spawnSync(process.execPath, command, {
cwd: root, env: name === "Vitest" ? invocationEnv("vitest", env) : env, stdio: "inherit",
});
@@ -270,8 +270,8 @@
"packages/shared/src/gitignore-runtime.test.ts": "e334ab0eca8faeab5807171983ec9102a3f1c734",
"packages/shared/src/google-sign-in-deployment.test.ts": "7f0ee05e9adaec48ed71c67e2b0e8364b0d1bdb2",
"packages/shared/src/google-sign-in-deployment.ts": "2e4e4cc3c24347642e20c91186581e1dce81d740",
"packages/shared/src/google-workspace-connectors.test.ts": "26316900a50e5ab384e0dcf9c45a2bb4abc0830d",
"packages/shared/src/google-workspace-connectors.ts": "88d942d1e66d7facc68cf8645f665cdc80c8c005",
"packages/shared/src/google-workspace-connectors.test.ts": "b9948b508bcb7a27c0dcea974edee314164686e5",
"packages/shared/src/google-workspace-connectors.ts": "270fbd40c0f96e8f4140c880a2c36a3150d4b9aa",
"packages/shared/src/google-workspace-setup-links.test.ts": "d86428b26e74e54ab2902d1a14c0f06f562de775",
"packages/shared/src/grok-bot.ts": "9de68f00e7926c397729ff62bf8e277f5a41c525",
"packages/shared/src/heartbeat-inbox.ts": "227dc89705c20460ca02194091cb162e11503186",
+61 -2
View File
@@ -37,8 +37,10 @@ it.skipIf(process.env.PAPERCLIP_UNIT_BOUNDARY_PROBE === "1")("runs the documente
expect(preloads.some(record => record.argv.some(arg => /pnpm(?:\.c?js)?$/.test(arg)))).toBe(true);
expect(preloads.some(record => record.argv[1]?.endsWith("/run-unit.mjs")
&& record.nodePath?.split(path.delimiter).includes(foreignModules))).toBe(true);
expect(preloads.every(record => !/vitest|tinypool|\.test\.(?:ts|mjs)$/.test(record.argv[1] ?? "")
&& !record.execArgv.includes("--test"))).toBe(true);
expect(preloads.every(record => {
const target = record.argv[1] ? path.relative(root, record.argv[1]) : "";
return !/vitest|tinypool|\.test\.(?:ts|mjs)$/.test(target) && !record.execArgv.includes("--test");
})).toBe(true);
} finally {
rmSync(directory, { recursive: true, force: true });
}
@@ -58,3 +60,60 @@ it("reports a missing test runner as a launcher/environment failure before any p
rmSync(directory, { recursive: true, force: true });
}
});
it("shards Vitest and node:test suites into a complete, non-overlapping cover", () => {
const launcher = path.join(root, "tests/runner-e2e/run-unit.mjs");
const dryRun = (args) => {
const result = spawnSync(process.execPath, [launcher, ...args, "--dry-run"], {
cwd: root,
encoding: "utf8",
timeout: 5000,
});
expect(result.status, result.stderr).toBe(0);
return JSON.parse(result.stdout);
};
const unsharded = dryRun([]);
expect(unsharded.vitestShard).toBeNull();
expect(unsharded.nodeTestFiles.length).toBeGreaterThan(0);
const shardCount = 4;
const shards = Array.from({ length: shardCount }, (_, index) =>
dryRun(["--shard-index", String(index), "--shard-count", String(shardCount)]),
);
expect(shards.map((s) => s.vitestShard)).toEqual(["--shard=1/4", "--shard=2/4", "--shard=3/4", "--shard=4/4"]);
for (let i = 0; i < shardCount; i += 1) {
expect(shards[i].vitestArgs).toContain(`--shard=${i + 1}/4`);
expect(shards[i].vitestArgs).not.toContain("--shard-index");
expect(shards[i].vitestArgs).not.toContain("--shard-count");
}
const combinedNodeTests = shards.flatMap((s) => s.nodeTestFiles);
expect(new Set(combinedNodeTests).size).toBe(combinedNodeTests.length);
expect([...combinedNodeTests].sort()).toEqual([...unsharded.nodeTestFiles].sort());
// Supports `=` flag form and leading `--` separator used by `pnpm run`.
const eqShard = dryRun(["--", "--shard-index=2", "--shard-count=4"]);
expect(eqShard).toEqual(shards[2]);
// Over-sharded trailing shards get an empty node:test list rather than duplicating files.
const emptyNodeShard = dryRun(["--shard-index", "20", "--shard-count", "25"]);
expect(emptyNodeShard.nodeTestFiles).toEqual([]);
expect(emptyNodeShard.vitestShard).toBe("--shard=21/25");
// Invalid or conflicting shard arguments fail fast with exit code 1.
for (const badArgs of [
["--shard-index", "0"],
["--shard-count", "4"],
["--shard-index", "4", "--shard-count", "4"],
["--shard-index", "-1", "--shard-count", "4"],
["--shard-index", "0", "--shard-count", "0"],
["--shard-index", "0", "--shard-count", "4", "--shard=1/4"],
]) {
const failed = spawnSync(process.execPath, [launcher, ...badArgs, "--dry-run"], {
cwd: root,
encoding: "utf8",
timeout: 5000,
});
expect(failed.status, `expected failure for ${badArgs.join(" ")}`).toBe(1);
}
});
+8
View File
@@ -1,12 +1,20 @@
import { availableParallelism } from "node:os";
import { fileURLToPath } from "node:url";
import { configDefaults, defineConfig } from "vitest/config";
const pendingDependabotLock = process.env.PAPERCLIP_CI_PR_AUTHOR === "dependabot[bot]";
// Thread workers reuse the main process and V8 compile cache across the 699
// support test files while keeping strict per-file isolation (`isolate: true`)
// for the 100+ suites using `vi.mock`. Scale to 4 workers on 4-core runners
// (vs Vitest's default `cpus - 1 = 3` forks) and 7 workers on 8-core runners.
const maxWorkers = Math.min(7, Math.max(1, availableParallelism()));
export default defineConfig({
root: import.meta.dirname,
test: {
name: "runner-e2e-support",
pool: "threads",
maxWorkers,
// CI profiling records per-test timings, like the root and Runner package configs.
...(process.env.PAPERCLIP_CI_PROFILE === "true"
? { reporters: [...configDefaults.reporters, fileURLToPath(new URL("../../scripts/ci-profile/vitest-reporter.mjs", import.meta.url))] }