mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-25 16:14:26 +01:00
## Thinking Path > - Paperclip lets people manage AI agents and their work. > - A blocked task must start once after its blocker is complete. > - The dependency journey checks this through task and agent run reads. > - These independent reads can see the same run at different stages of completion. > - The collector can stop while the agent read still says `running`. > - This pull request waits for both reads to agree before it saves the finished and reopened points. > - The test can then measure the completed work with the existing strict rules. ## Linked Issues or Issue Description **What happened?** The dependency journey can report `dependency_one_automatic_resume` after one correct automatic run. Its completion wait accepts the task run as `succeeded` while the agent run read still says `running`. A later read agrees, but the saved finished point remains split. **Expected behavior** Wait for matching task and agent run facts within the existing campaign deadline. Keep the two observations independent. Fail if they never agree. **Steps to reproduce** Use the flow fixture to return a completed task run and a lagging agent run detail. Run the new `agent detail still running after task detail completed` case against the old collector. It fails with `dependency_one_automatic_resume`. **Paperclip version or commit** Base: `3ca9b6d471e100fe248c650f30453db4d3bc55fb`. Related: #21732 added valid wake producers. That repair is already present and does not address this read timing error. ## What Changed - Compare task and agent run facts with the same normalized facts used by the grader. - Require agreement before the collector ends its completion wait and after it reopens the result. - Tag fixture projections explicitly, with separate agent lag counters before and after reopening. - Share the full settled predicate between both waits; agreeing stale reads cannot count as completion. - Add temporary and permanent cases for agent lag, task-only and agreeing stale run views, task status, missing document, active locks and native phase. - Document the completion wait. Keep the grader, run budget and deadline unchanged. ## Verification - Red: the new lagging-read regression fails on the base collector with `dependency_one_automatic_resume`. - Green: three focused dependency suites pass, 126 tests. This includes permanent disagreement, duplicate or unrelated runs, early execution, history and output checks. - Command: `node /tmp/pap5740-test-tools/node_modules/vitest/vitest.mjs run --config /tmp/pap5740-test-tools/vitest.config.mjs`. The temporary config selects `tests/runner-e2e/product-journeys/task-dependency-resume*.test.ts`. Tools: Vitest 5.0.3, Playwright 1.62.1 and Zod 4. - `pnpm verify` could not run: the managed Git storage guard rejects `git ls-files` with `paperclip_git_storage_limit`. CI must supply broader checks. - No new paid journey was run. Staging acceptance remains open. No reviewed harness pin was changed. - Follow-up commit: `16bb94c256769fe76b014e865259b742b35773ea`. The reopened-only regression fails on the prior commit with `dependency_one_automatic_resume`; it passes after this repair. - Second follow-up: `45d60118fb36fd1f426e088f263d04c91484cfee`. Ten of twelve new stale-state cases fail on `16bb94c`; all pass after sharing the settled predicate. - Exact finished-run binding: `24d7b2f67a9f51ac6d996211f651a92772ff2a55`. Both reopened projections must match the normalized saved finished-run facts. Two additional agreeing-but-different run-facts cases fail before this change and pass afterward. - CI and Greptile passed on `16bb94c`; reviews also cleared `45d6011`. Fresh CI and reviews are pending on `24d7b2f`. ## Risks Low risk. A mismatch now uses the remaining campaign wait rather than reaching the grader early. Permanent disagreement still fails at the deadline. This change does not start another agent run, alter production state, replace either independent read, or relax the grader. ## Model Used OpenAI GPT-6 through Codex, with reasoning and code execution. The runtime did not expose a more specific model ID. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [ ] All Paperclip CI gates are green - [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge --------- Co-authored-by: Paperclip <noreply@paperclip.ing>
387 lines
28 KiB
TypeScript
387 lines
28 KiB
TypeScript
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";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { JourneyError, type JourneyContext, type JourneyEvidence, type TargetSession } from "./types.js";
|
|
import { dependencyEvidenceFixture } from "./task-dependency-resume-fixture.js";
|
|
import * as observedReader from "./observation-read.js";
|
|
|
|
const controls = vi.hoisted(() => ({ create: vi.fn() }));
|
|
vi.mock("../user-actions.js", () => ({ createTaskThroughUi: (...args: unknown[]) => controls.create(...args) }));
|
|
vi.mock("./task-document-flow.js", () => ({ openDocumentAuthoring: vi.fn(async () => {}) }));
|
|
vi.mock("@playwright/test", () => ({ expect: Object.assign((locator: any) => ({
|
|
async toBeVisible() { expect(await locator.isVisible()).toBe(true); },
|
|
async toBeInViewport() { expect(await locator.isVisible()).toBe(true); },
|
|
async toContainText(text: string) { expect(await locator.textContent()).toContain(text); },
|
|
}), { poll: (read: () => Promise<unknown>) => ({
|
|
async toBe(value: unknown) { expect(await read()).toBe(value); },
|
|
async toEqual(value: unknown) { expect(await read()).toEqual(value); },
|
|
}) }) }));
|
|
import { taskDependencyResume } from "./task-dependency-resume.js";
|
|
|
|
interface FixtureOptions { priorRuns?: number; unrelatedActivity?: number; ownedActivity?: number; agentActivity?: number; missingActivity?: boolean; activePrior?: 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 });
|
|
const runs = () => assigned && (completed || premature) ? [structuredClone(f.finished.dependentRuns[0]!)] : [];
|
|
const priorRuns = Array.from({ length: options.priorRuns ?? 0 }, (_, i) => ({ ...structuredClone(f.finished.agentRuns[0]!),
|
|
id: `prior-${i}`, nativeIssueId: `prior-task-${i}`, contextSnapshot: { issueId: `prior-task-${i}` },
|
|
startedAt: "2019-12-31T23:00:00Z", status: options.activePrior ? "running" : i % 2 ? "failed" : "succeeded" }));
|
|
const activity = (count: number, entityId: string, agentId?: string) => Array.from({ length: count }, (_, i) => ({
|
|
id: `${entityId}-activity-${i}`, companyId: s.companyId, entityType: "issue", entityId, agentId,
|
|
actorType: agentId ? "agent" : "user", actorId: agentId ?? s.userId, action: "issue.observed" }));
|
|
const taskDocument = () => ({ ...f.finished.document, body: output() });
|
|
const revision = () => ({ ...f.finished.revision, body: output() });
|
|
controls.create.mockImplementation(async (input: any) => {
|
|
await input.beforeDispatch?.();
|
|
const row = input.title.includes(" blocker ") ? blocker : dependent;
|
|
Object.assign(row, { title: input.title, description: input.prompt });
|
|
actions.push(`create:${row.id}`);
|
|
return { issueId: row.id, submittedAtMs: Date.now() };
|
|
});
|
|
const locator = (key: string): any => ({
|
|
key,
|
|
filter(value: any) {
|
|
if (key === '[data-slot="popover-content"]' && value?.has) {
|
|
return locator(options.missingStatusChoice ? "missing-status-choice" : value.has.key);
|
|
}
|
|
return this;
|
|
}, first() { return this; }, last() { return this; },
|
|
locator() { return this; },
|
|
getByRole(_role: string, options?: any) { return locator(options?.name ? String(options.name) : key); },
|
|
async isVisible() {
|
|
if (key.includes("data-property-row")) return panelOpen && !options.missingProperty;
|
|
if (key === "Toggle side panel") return !panelOpen && options.closedPanel === "toggle";
|
|
if (key.includes("Show properties")) return !panelOpen && options.closedPanel === "properties";
|
|
if (key === "Open a new tab" || key === "/^Properties/") return false;
|
|
return true;
|
|
},
|
|
async scrollIntoViewIfNeeded() { actions.push(`scroll:${key}`); },
|
|
async fill(value: string) { actions.push(`fill:${key}:${value}`); },
|
|
async click() {
|
|
actions.push(`click:${key}`);
|
|
if (key === "Toggle side panel" || key.includes("Show properties")) panelOpen = true;
|
|
if (key === "missing-status-choice") throw new Error("missing_status_choice");
|
|
if (key === "blocker-choice") dependent.blockedByIssueIds = [blocker.id];
|
|
if (key === "Blocked") dependent.status = "blocked";
|
|
if (key === "agent-choice") { assigned = true; dependent.assigneeAgentId = s.agentId; dependent.assigneeUserId = null; }
|
|
if (key === "Done") {
|
|
completed = true; blocker.status = "done"; blocker.completedAt = "2020-01-01T00:00:20.000Z";
|
|
dependent.status = "done";
|
|
}
|
|
},
|
|
async textContent() { return output(); },
|
|
});
|
|
const page: any = {
|
|
locator(selector: string) { return locator(selector); },
|
|
getByRole(_role: string, options?: any) {
|
|
if (_role === "button" && options?.exact && ["Blocked", "Done"].includes(options.name)) return locator("missing-status-choice");
|
|
const l = locator(options?.name ? String(options.name) : "buttons");
|
|
l.filter = (options: any) => options?.hasText === blocker.title ? locator("blocker-choice")
|
|
: options?.hasText === "Fixture agent" ? locator("agent-choice") : l;
|
|
return l;
|
|
},
|
|
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"); 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}`) {
|
|
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 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`) {
|
|
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}`);
|
|
}, async post(...args: unknown[]) { writes.push(args); throw new Error("unexpected_mutation"); },
|
|
async patch(...args: unknown[]) { writes.push(args); throw new Error("unexpected_mutation"); } };
|
|
const context = { page, api, company: { id: s.companyId, issuePrefix: "QA" }, user: { id: s.userId }, environmentId: s.environmentId,
|
|
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, detailReads, staleReads };
|
|
}
|
|
afterEach(() => { vi.useRealTimers(); controls.create.mockReset(); });
|
|
describe("dependency browser flow orchestration", () => {
|
|
const evidenceFiles = ["task-dependency-observations.json", "observation-read-failures.json"] as const;
|
|
const writerFaults = ["observations", "reads", "both"] as const;
|
|
const obstructWriters = async (directory: string, fault: typeof writerFaults[number]) => {
|
|
const names = fault === "both" ? [...evidenceFiles] : [evidenceFiles[fault === "observations" ? 0 : 1]];
|
|
await Promise.all(names.map(name => mkdir(path.join(directory, name))));
|
|
return names;
|
|
};
|
|
it.each(writerFaults.flatMap(fault => (["unsupported", "failed"] as const).map(outcome => [fault, outcome] as const)))(
|
|
"preserves the original %s writer failure outcome %s and attempts both evidence files", async (fault, outcome) => {
|
|
const f = await fixture(), blocked = await obstructWriters(f.directory, fault);
|
|
const logging = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
const original = Object.freeze(new JourneyError("failed", "dependency_observation_control_failed"));
|
|
if (outcome === "unsupported") f.context.agent!.provider = "";
|
|
else vi.spyOn(f.context.api, "get").mockRejectedValue(original);
|
|
try {
|
|
const operation = taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory });
|
|
if (outcome === "unsupported") await expect(operation).rejects.toMatchObject({ outcome, code: "dependency_execution_identity_unavailable" });
|
|
else await expect(operation).rejects.toBe(original);
|
|
for (const name of evidenceFiles.filter(name => !blocked.includes(name))) {
|
|
expect(JSON.parse(await readFile(path.join(f.directory, name), "utf8"))).toBeTypeOf("object");
|
|
}
|
|
expect(logging).toHaveBeenCalledWith("dependency_evidence_preservation_failed", blocked);
|
|
expect(JSON.stringify(logging.mock.calls)).not.toContain(f.directory);
|
|
expect(f.actions).toEqual([]); expect(f.owned).toEqual([]); expect(f.writes).toEqual([]);
|
|
} finally { logging.mockRestore(); await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it.each(["unsupported", "failed"] as const)("awaits the other evidence file when the read writer throws synchronously after %s", async outcome => {
|
|
const f = await fixture(), createReader = observedReader.createObservedReader;
|
|
const original = Object.freeze(new JourneyError("failed", "dependency_observation_control_failed"));
|
|
const failingWrite = vi.fn(() => { throw new Error("private writer diagnostic"); });
|
|
const reader = vi.spyOn(observedReader, "createObservedReader").mockImplementation((...args) => ({
|
|
...createReader(...args), preserve: failingWrite,
|
|
}));
|
|
const logging = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
if (outcome === "unsupported") f.context.agent!.model = "";
|
|
else vi.spyOn(f.context.api, "get").mockRejectedValue(original);
|
|
try {
|
|
const operation = taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory });
|
|
if (outcome === "unsupported") await expect(operation).rejects.toMatchObject({ outcome, code: "dependency_execution_identity_unavailable" });
|
|
else await expect(operation).rejects.toBe(original);
|
|
expect(failingWrite).toHaveBeenCalledOnce();
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"))).toHaveProperty("stage",
|
|
outcome === "unsupported" ? "prerequisites" : "observe_starting_runs");
|
|
expect(logging).toHaveBeenCalledWith("dependency_evidence_preservation_failed", ["observation-read-failures.json"]);
|
|
expect(JSON.stringify(logging.mock.calls)).not.toContain("private writer diagnostic");
|
|
} finally { logging.mockRestore(); reader.mockRestore(); await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it.each(writerFaults)("fails a successful journey when its %s evidence writer fails", async fault => {
|
|
const f = await fixture(), blocked = await obstructWriters(f.directory, fault);
|
|
const logging = vi.spyOn(console, "error").mockImplementation(() => {});
|
|
vi.useFakeTimers(); vi.setSystemTime(new Date("2020-01-01T00:00:00Z"));
|
|
try {
|
|
const rejection = expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory })).rejects.toMatchObject({
|
|
outcome: "failed", code: "dependency_evidence_preservation_failed",
|
|
});
|
|
await vi.advanceTimersByTimeAsync(11_000); await rejection;
|
|
expect(f.evidence.checks).toHaveLength(8); expect(f.evidence.checks.every(check => check.passed)).toBe(true);
|
|
expect(logging).toHaveBeenCalledWith("dependency_evidence_preservation_failed", blocked);
|
|
for (const name of evidenceFiles.filter(name => !blocked.includes(name))) {
|
|
expect(JSON.parse(await readFile(path.join(f.directory, name), "utf8"))).toBeTypeOf("object");
|
|
}
|
|
expect(f.writes).toEqual([]);
|
|
} finally { logging.mockRestore(); await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it.each((["provider", "model"] as const).flatMap(field => [
|
|
[field, "missing", undefined], [field, "null", null], [field, "empty", ""], [field, "blank", " \t "],
|
|
] as const))("rejects a %s identity that is %s before observation or task work", async (field, _kind, value) => {
|
|
const f = await fixture();
|
|
Object.assign(f.context.agent!, { [field]: value });
|
|
const get = vi.spyOn(f.context.api, "get").mockRejectedValue(new Error("preflight_read_attempted"));
|
|
try {
|
|
await expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory })).rejects.toMatchObject({
|
|
outcome: "unsupported", code: "dependency_execution_identity_unavailable",
|
|
});
|
|
expect(get).not.toHaveBeenCalled(); expect(controls.create).not.toHaveBeenCalled();
|
|
expect(f.actions).toEqual([]); expect(f.owned).toEqual([]); expect(f.writes).toEqual([]);
|
|
expect(f.evidence.checks).toEqual([]);
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"))).toHaveProperty("stage", "prerequisites");
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "observation-read-failures.json"), "utf8"))).toEqual({ failures: [] });
|
|
} finally { await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
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 }],
|
|
["more than 500 owned task events", { ownedActivity: 600 }],
|
|
["prior agent events", { priorRuns: 2, agentActivity: 300 }],
|
|
] as const)("uses browser actions with %s and never writes output through API observations", async (_name, options) => {
|
|
const f = await fixture(false, options); 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() + 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"));
|
|
expect(f.owned).toEqual(expect.arrayContaining([
|
|
expect.objectContaining({ kind: "issue", id: "blocker", journeyId: "task-dependency-resume" }),
|
|
expect.objectContaining({ kind: "issue", id: "dependent", journeyId: "task-dependency-resume" }),
|
|
]));
|
|
const saved = JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"));
|
|
expect(saved.stage).toBe("complete"); expect(saved.scope.prompt).not.toContain(saved.scope.reference);
|
|
expect(saved.waiting.at(-1).observedAt - saved.waiting[0].observedAt).toBeGreaterThanOrEqual(10_000);
|
|
expect(saved.startingAgentRuns).toHaveLength("priorRuns" in options ? options.priorRuns : 0);
|
|
expect(saved.reopened.agentRuns).toHaveLength(saved.startingAgentRuns.length + 1);
|
|
expect(f.reads.some(route => route.startsWith("/api/heartbeat-runs/prior-"))).toBe(false);
|
|
expect(f.reads).toContain("/api/issues/blocker/activity"); expect(f.reads).toContain("/api/issues/dependent/activity");
|
|
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 {
|
|
const operation = taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ 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);
|
|
const opener = f.actions.findIndex(action => action.startsWith("click:") && (action.includes("Show properties") || action === "click:Toggle side panel"));
|
|
expect(opener).toBeGreaterThanOrEqual(0); expect(opener).toBeLessThan(f.actions.indexOf("click:blocker-choice"));
|
|
expect(f.actions.some(action => action.startsWith("scroll:[data-property-row]:not([inert] *):not([aria-hidden=\"true\"] *)"))).toBe(true);
|
|
expect(f.writes).toEqual([]);
|
|
} finally { await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it.each([
|
|
["missing property", { missingProperty: true }, "link_blocker"],
|
|
["missing matching status glyph", { missingStatusChoice: true }, "set_dependent_blocked"],
|
|
] as const)("fails closed on %s before agent assignment or blocker completion", async (_name, options, stage) => {
|
|
const f = await fixture(false, options);
|
|
try {
|
|
await expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory })).rejects.toThrow();
|
|
expect(f.actions).not.toContain("click:agent-choice"); expect(f.actions).not.toContain("click:Done"); expect(f.writes).toEqual([]);
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"))).toHaveProperty("stage", stage);
|
|
} finally { await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it.each([
|
|
["truncated agent activity", { agentActivity: 500 }, "dependency_activity_coverage_unavailable"],
|
|
["missing agent activity", { missingActivity: true }, "dependency_activity_coverage_unavailable"],
|
|
["active earlier work", { priorRuns: 1, activePrior: true }, "dependency_starting_agent_not_idle"],
|
|
["saturated run history", { priorRuns: 1000 }, "dependency_run_coverage_unavailable"],
|
|
] as const)("rejects %s before completing the blocker", async (_name, options, code) => {
|
|
const f = await fixture(false, options);
|
|
try {
|
|
await expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory })).rejects.toThrow(code);
|
|
expect(f.actions).not.toContain("click:Done"); expect(f.writes).toEqual([]);
|
|
} finally { await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
it("premature work fails before the browser completes the blocker and preserves its observations", async () => {
|
|
const f = await fixture(true);
|
|
try {
|
|
await expect(taskDependencyResume(f.context, f.session, "journey-123-abcdef01", f.evidence,
|
|
{ deadlineAt: Date.now() + 60_000, directory: f.directory })).rejects.toThrow("dependency_ran_before_blocker_completed");
|
|
expect(f.actions).not.toContain("click:Done"); expect(f.writes).toEqual([]);
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "task-dependency-observations.json"), "utf8"))).toHaveProperty("stage", "observe_blocked_wait");
|
|
expect(JSON.parse(await readFile(path.join(f.directory, "observation-read-failures.json"), "utf8"))).toEqual({ failures: [] });
|
|
} finally { await rm(f.directory, { recursive: true, force: true }); }
|
|
});
|
|
});
|