Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ede428bff2 | |||
| 6850826abe |
@@ -1,8 +1,8 @@
|
||||
import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { createMemoryStore } from "@ocas/core";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { createMemoryStore } from "@ocas/core";
|
||||
import { storeBuiltinDetail } from "../src/detail.js";
|
||||
import { appendSessionTurn, initSessionDir } from "../src/session.js";
|
||||
import type { BuiltinTurnPayload } from "../src/types.js";
|
||||
|
||||
@@ -1,51 +1,51 @@
|
||||
import { mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { describe, it, expect, beforeAll, afterAll } from "vitest";
|
||||
import { readFileTool } from "../src/tools/read-file.js";
|
||||
import { writeFile, mkdir, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
const testDir = join(tmpdir(), `read-file-test-${Date.now()}`);
|
||||
const ctx = { cwd: testDir, storageRoot: testDir };
|
||||
|
||||
beforeAll(async () => {
|
||||
await mkdir(testDir, { recursive: true });
|
||||
await writeFile(join(testDir, "hello.txt"), "hello world", "utf8");
|
||||
await mkdir(testDir, { recursive: true });
|
||||
await writeFile(join(testDir, "hello.txt"), "hello world", "utf8");
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("readFileTool", () => {
|
||||
it("reads a file successfully", async () => {
|
||||
const result = await readFileTool.execute({ path: "hello.txt" }, ctx);
|
||||
expect(result).toBe("hello world");
|
||||
});
|
||||
it("reads a file successfully", async () => {
|
||||
const result = await readFileTool.execute({ path: "hello.txt" }, ctx);
|
||||
expect(result).toBe("hello world");
|
||||
});
|
||||
|
||||
it("returns error for non-existent file", async () => {
|
||||
const result = await readFileTool.execute({ path: "nope.txt" }, ctx);
|
||||
expect(result).toMatch(/^Error:/);
|
||||
});
|
||||
it("returns error for non-existent file", async () => {
|
||||
const result = await readFileTool.execute({ path: "nope.txt" }, ctx);
|
||||
expect(result).toMatch(/^Error:/);
|
||||
});
|
||||
|
||||
it("returns error for directory", async () => {
|
||||
const result = await readFileTool.execute({ path: "." }, ctx);
|
||||
expect(result).toBe("Error: not a file");
|
||||
});
|
||||
it("returns error for directory", async () => {
|
||||
const result = await readFileTool.execute({ path: "." }, ctx);
|
||||
expect(result).toBe("Error: not a file");
|
||||
});
|
||||
|
||||
it("returns error when path is not a string", async () => {
|
||||
const result = await readFileTool.execute({ path: 123 }, ctx);
|
||||
expect(result).toBe("Error: path must be a string");
|
||||
});
|
||||
it("returns error when path is not a string", async () => {
|
||||
const result = await readFileTool.execute({ path: 123 }, ctx);
|
||||
expect(result).toBe("Error: path must be a string");
|
||||
});
|
||||
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await readFileTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: path must be a string");
|
||||
});
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await readFileTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: path must be a string");
|
||||
});
|
||||
|
||||
it("returns error for file exceeding 512KB limit", async () => {
|
||||
const bigFile = join(testDir, "big.txt");
|
||||
await writeFile(bigFile, Buffer.alloc(512 * 1024 + 1, 65));
|
||||
const result = await readFileTool.execute({ path: "big.txt" }, ctx);
|
||||
expect(result).toMatch(/Error:.*limit/);
|
||||
});
|
||||
it("returns error for file exceeding 512KB limit", async () => {
|
||||
const bigFile = join(testDir, "big.txt");
|
||||
await writeFile(bigFile, Buffer.alloc(512 * 1024 + 1, 65));
|
||||
const result = await readFileTool.execute({ path: "big.txt" }, ctx);
|
||||
expect(result).toMatch(/Error:.*limit/);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
import { tmpdir } from "node:os";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { runCommandTool } from "../src/tools/run-command.js";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
const ctx = { cwd: tmpdir(), storageRoot: tmpdir() };
|
||||
|
||||
describe("runCommandTool", () => {
|
||||
it("runs echo command and checks stdout", async () => {
|
||||
const result = await runCommandTool.execute({ command: "echo hello" }, ctx);
|
||||
expect(result).toContain("hello");
|
||||
expect(result).toContain("stdout");
|
||||
});
|
||||
it("runs echo command and checks stdout", async () => {
|
||||
const result = await runCommandTool.execute({ command: "echo hello" }, ctx);
|
||||
expect(result).toContain("hello");
|
||||
expect(result).toContain("stdout");
|
||||
});
|
||||
|
||||
it("returns exit code", async () => {
|
||||
const result = await runCommandTool.execute({ command: "exit 0" }, ctx);
|
||||
expect(result).toContain("exit_code: 0");
|
||||
});
|
||||
it("returns exit code", async () => {
|
||||
const result = await runCommandTool.execute({ command: "exit 0" }, ctx);
|
||||
expect(result).toContain("exit_code: 0");
|
||||
});
|
||||
|
||||
it("returns non-zero exit code", async () => {
|
||||
const result = await runCommandTool.execute({ command: "exit 42" }, ctx);
|
||||
expect(result).toContain("exit_code: 42");
|
||||
});
|
||||
it("returns non-zero exit code", async () => {
|
||||
const result = await runCommandTool.execute({ command: "exit 42" }, ctx);
|
||||
expect(result).toContain("exit_code: 42");
|
||||
});
|
||||
|
||||
it("returns error when command is not a string", async () => {
|
||||
const result = await runCommandTool.execute({ command: 123 }, ctx);
|
||||
expect(result).toBe("Error: command must be a string");
|
||||
});
|
||||
it("returns error when command is not a string", async () => {
|
||||
const result = await runCommandTool.execute({ command: 123 }, ctx);
|
||||
expect(result).toBe("Error: command must be a string");
|
||||
});
|
||||
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await runCommandTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: command must be a string");
|
||||
});
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await runCommandTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: command must be a string");
|
||||
});
|
||||
|
||||
it("custom cwd works", async () => {
|
||||
const result = await runCommandTool.execute({ command: "pwd", cwd: "/tmp" }, ctx);
|
||||
expect(result).toContain("/tmp");
|
||||
});
|
||||
it("custom cwd works", async () => {
|
||||
const result = await runCommandTool.execute({ command: "pwd", cwd: "/tmp" }, ctx);
|
||||
expect(result).toContain("/tmp");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -3,13 +3,13 @@ import { mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import type { BuiltinTurnPayload } from "../src/types.js";
|
||||
import {
|
||||
appendSessionTurn,
|
||||
initSessionDir,
|
||||
readSessionTurns,
|
||||
removeSession,
|
||||
} from "../src/session.js";
|
||||
import type { BuiltinTurnPayload } from "../src/types.js";
|
||||
|
||||
describe("session", () => {
|
||||
let storageRoot: string;
|
||||
|
||||
@@ -1,43 +1,43 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { afterAll, describe, expect, it } from "vitest";
|
||||
import { describe, it, expect, afterAll } from "vitest";
|
||||
import { writeFileTool } from "../src/tools/write-file.js";
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
|
||||
const testDir = join(tmpdir(), `write-file-test-${Date.now()}`);
|
||||
const ctx = { cwd: testDir, storageRoot: testDir };
|
||||
|
||||
afterAll(async () => {
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
await rm(testDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
describe("writeFileTool", () => {
|
||||
it("writes file successfully", async () => {
|
||||
const result = await writeFileTool.execute({ path: "out.txt", content: "hi" }, ctx);
|
||||
expect(result).toMatch(/Wrote 2 bytes/);
|
||||
const content = await readFile(join(testDir, "out.txt"), "utf8");
|
||||
expect(content).toBe("hi");
|
||||
});
|
||||
it("writes file successfully", async () => {
|
||||
const result = await writeFileTool.execute({ path: "out.txt", content: "hi" }, ctx);
|
||||
expect(result).toMatch(/Wrote 2 bytes/);
|
||||
const content = await readFile(join(testDir, "out.txt"), "utf8");
|
||||
expect(content).toBe("hi");
|
||||
});
|
||||
|
||||
it("creates parent directories", async () => {
|
||||
const result = await writeFileTool.execute({ path: "a/b/c.txt", content: "nested" }, ctx);
|
||||
expect(result).toMatch(/Wrote/);
|
||||
const content = await readFile(join(testDir, "a/b/c.txt"), "utf8");
|
||||
expect(content).toBe("nested");
|
||||
});
|
||||
it("creates parent directories", async () => {
|
||||
const result = await writeFileTool.execute({ path: "a/b/c.txt", content: "nested" }, ctx);
|
||||
expect(result).toMatch(/Wrote/);
|
||||
const content = await readFile(join(testDir, "a/b/c.txt"), "utf8");
|
||||
expect(content).toBe("nested");
|
||||
});
|
||||
|
||||
it("returns error when path is not a string", async () => {
|
||||
const result = await writeFileTool.execute({ path: 123, content: "x" }, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
it("returns error when path is not a string", async () => {
|
||||
const result = await writeFileTool.execute({ path: 123, content: "x" }, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
|
||||
it("returns error when content is not a string", async () => {
|
||||
const result = await writeFileTool.execute({ path: "x.txt", content: 42 }, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
it("returns error when content is not a string", async () => {
|
||||
const result = await writeFileTool.execute({ path: "x.txt", content: 42 }, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await writeFileTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
it("returns error when args is null", async () => {
|
||||
const result = await writeFileTool.execute(null, ctx);
|
||||
expect(result).toBe("Error: path and content must be strings");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,13 @@ import type { CasRef, ThreadId } from "@united-workforce/protocol";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createMarker, deleteMarker } from "../background/index.js";
|
||||
import { cmdThreadList, cmdThreadShow, cmdThreadStart } from "../commands/thread.js";
|
||||
import { completeThread, createUwfStore, loadActiveThreads, setThread } from "../store.js";
|
||||
import {
|
||||
addHistoryEntry,
|
||||
createUwfStore,
|
||||
deleteThread,
|
||||
loadAllThreads,
|
||||
setThread,
|
||||
} from "../store.js";
|
||||
|
||||
const OUTPUT_SCHEMA = {
|
||||
type: "object" as const,
|
||||
@@ -169,7 +175,7 @@ async function insertStepNode(
|
||||
outputPayload: Record<string, unknown>,
|
||||
): Promise<void> {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const index = loadActiveThreads(uwf.varStore);
|
||||
const index = loadAllThreads(uwf.varStore);
|
||||
const headEntry = index[threadId];
|
||||
if (headEntry === undefined) throw new Error(`thread ${threadId} not in index`);
|
||||
const head = headEntry.head;
|
||||
@@ -200,13 +206,7 @@ async function insertStepNode(
|
||||
assembledPrompt: null,
|
||||
})) as CasRef;
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head: stepHash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
setThread(uwf.varStore, threadId, { head: stepHash, suspendedRole: null, suspendMessage: null });
|
||||
}
|
||||
|
||||
describe("currentRole field", () => {
|
||||
@@ -282,12 +282,19 @@ describe("currentRole field", () => {
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const { thread, workflow } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const tid = thread as ThreadId;
|
||||
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
loadActiveThreads(uwfForIndex.varStore)[tid]!.head;
|
||||
completeThread(uwfForIndex.varStore, tid, "completed");
|
||||
const head = loadAllThreads(uwfForIndex.varStore)[tid]!.head;
|
||||
deleteThread(uwfForIndex.varStore, tid);
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: tid,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, tid);
|
||||
expect(result.status).toBe("completed");
|
||||
@@ -303,12 +310,19 @@ describe("currentRole field", () => {
|
||||
try {
|
||||
const wf = join(tmpDir, "test-current-role.yaml");
|
||||
await writeFile(wf, SIMPLE_WORKFLOW_YAML, "utf8");
|
||||
const { thread } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const { thread, workflow } = await cmdThreadStart(storageRoot, wf, "test", tmpDir);
|
||||
const tid = thread as ThreadId;
|
||||
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
loadActiveThreads(uwfForIndex.varStore)[tid]!.head;
|
||||
completeThread(uwfForIndex.varStore, tid, "cancelled");
|
||||
const head = loadAllThreads(uwfForIndex.varStore)[tid]!.head;
|
||||
deleteThread(uwfForIndex.varStore, tid);
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: tid,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, tid);
|
||||
expect(result.status).toBe("cancelled");
|
||||
@@ -361,8 +375,15 @@ describe("currentRole field", () => {
|
||||
const comp = await cmdThreadStart(storageRoot, wf, "completed", tmpDir);
|
||||
const compId = comp.thread as ThreadId;
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
const _compHead = loadActiveThreads(uwfForIndex.varStore)[compId]!.head;
|
||||
completeThread(uwfForIndex.varStore, compId, "completed");
|
||||
const compHead = loadAllThreads(uwfForIndex.varStore)[compId]!.head;
|
||||
deleteThread(uwfForIndex.varStore, compId);
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: compId,
|
||||
workflow: comp.workflow,
|
||||
head: compHead,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
const list = await cmdThreadList(storageRoot, null, null, null, 0, 100);
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ import { afterEach, beforeAll, beforeEach, describe, expect, test } from "vitest
|
||||
import { stringify } from "yaml";
|
||||
import { cmdThreadStart } from "../commands/thread.js";
|
||||
import { cmdWorkflowAdd } from "../commands/workflow.js";
|
||||
import { createUwfStore, getThread } from "../store.js";
|
||||
import { createUwfStore, findHistoryEntry, getThread } from "../store.js";
|
||||
|
||||
// ── paths ──────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -106,13 +106,9 @@ async function addWorkflow(workflowFixture: string, workflowName: string): Promi
|
||||
|
||||
type ExecResult = { stdout: string; stderr: string; exitCode: number };
|
||||
|
||||
function runExec(threadId: string, count: number | null = null): ExecResult {
|
||||
const args = [CLI_PATH, "thread", "exec", threadId];
|
||||
if (count !== null) {
|
||||
args.push("--count", String(count));
|
||||
}
|
||||
function runExec(threadId: string): ExecResult {
|
||||
try {
|
||||
const stdout = execFileSync(process.execPath, args, {
|
||||
const stdout = execFileSync(process.execPath, [CLI_PATH, "thread", "exec", threadId], {
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, UWF_HOME: uwfHome, OCAS_HOME: casDir },
|
||||
@@ -130,38 +126,11 @@ function runExec(threadId: string, count: number | null = null): ExecResult {
|
||||
}
|
||||
}
|
||||
|
||||
/** Invoke `uwf thread resume <threadId> -p <prompt>` through the built CLI. */
|
||||
function runResume(threadId: string, prompt: string): ExecResult {
|
||||
try {
|
||||
const stdout = execFileSync(
|
||||
process.execPath,
|
||||
[CLI_PATH, "thread", "resume", threadId, "-p", prompt],
|
||||
{
|
||||
encoding: "utf8",
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
env: { ...process.env, UWF_HOME: uwfHome, OCAS_HOME: casDir },
|
||||
cwd: tmpDir,
|
||||
timeout: 30000,
|
||||
},
|
||||
);
|
||||
return { stdout, stderr: "", exitCode: 0 };
|
||||
} catch (e: unknown) {
|
||||
const err = e as NodeJS.ErrnoException & {
|
||||
stdout?: string;
|
||||
stderr?: string;
|
||||
status?: number;
|
||||
};
|
||||
return { stdout: err.stdout ?? "", stderr: err.stderr ?? "", exitCode: err.status ?? 1 };
|
||||
}
|
||||
}
|
||||
|
||||
type StepOutputJson = {
|
||||
thread: string;
|
||||
head: string;
|
||||
status: string;
|
||||
currentRole: string | null;
|
||||
suspendedRole: string | null;
|
||||
suspendMessage: string | null;
|
||||
done: boolean;
|
||||
};
|
||||
|
||||
@@ -233,12 +202,12 @@ describe("E2E mock-agent: full uwf pipeline", () => {
|
||||
const startNode = store.cas.get(startHash as CasRef);
|
||||
expect((startNode!.payload as StartNodePayload).workflow).toBe(workflowHash);
|
||||
|
||||
// Thread is completed: status changed to "completed", head updated.
|
||||
// Thread is completed: removed from active index, present in history.
|
||||
const uwf = await createUwfStore(uwfHome);
|
||||
const finalEntry = getThread(uwf.varStore, threadId);
|
||||
expect(finalEntry).not.toBeNull();
|
||||
expect(finalEntry!.status).toBe("completed");
|
||||
expect(finalEntry!.head).toBe(step2.head);
|
||||
expect(getThread(uwf.varStore, threadId)).toBeNull();
|
||||
const hist = findHistoryEntry(uwf.varStore, threadId);
|
||||
expect(hist).not.toBeNull();
|
||||
expect(hist!.head).toBe(step2.head);
|
||||
});
|
||||
|
||||
test("2. branching workflow loops developer→reviewer→developer→reviewer→$END", async () => {
|
||||
@@ -294,9 +263,8 @@ describe("E2E mock-agent: full uwf pipeline", () => {
|
||||
expect(getStatus(store, n4.output)).toBe("approved");
|
||||
|
||||
const uwf = await createUwfStore(uwfHome);
|
||||
const finalEntry = getThread(uwf.varStore, threadId);
|
||||
expect(finalEntry).not.toBeNull();
|
||||
expect(finalEntry!.status).toBe("completed");
|
||||
expect(getThread(uwf.varStore, threadId)).toBeNull();
|
||||
expect(findHistoryEntry(uwf.varStore, threadId)).not.toBeNull();
|
||||
});
|
||||
|
||||
test("3. role mismatch in mock data makes the agent exit with an error", async () => {
|
||||
@@ -319,164 +287,7 @@ describe("E2E mock-agent: full uwf pipeline", () => {
|
||||
|
||||
// The thread remains active (no step node was written for the failed step).
|
||||
const uwf = await createUwfStore(uwfHome);
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry!.status).not.toBe("completed");
|
||||
expect(entry!.head).toBe(step1.head);
|
||||
});
|
||||
|
||||
test("4. planner $SUSPEND then resume re-runs planner and reaches $END", async () => {
|
||||
await writeMockConfig("e2e-suspend.mock.yaml");
|
||||
const workflowHash = await addWorkflow("e2e-suspend.workflow.yaml", "test-suspend");
|
||||
|
||||
const start = await cmdThreadStart(uwfHome, workflowHash, "Analyze the task", uwfHome, tmpDir);
|
||||
const threadId = start.thread;
|
||||
|
||||
// Step 1 → planner emits insufficient_info → thread suspends.
|
||||
const step1 = execStep(threadId);
|
||||
expect(step1.status).toBe("suspended");
|
||||
expect(step1.done).toBe(false);
|
||||
expect(step1.currentRole).toBeNull();
|
||||
expect(step1.suspendedRole).toBe("planner");
|
||||
expect(step1.suspendMessage).toBe("Need more info: missing requirements");
|
||||
|
||||
// Thread index entry reflects the suspension with rendered metadata.
|
||||
const suspendedEntry = getThread((await createUwfStore(uwfHome)).varStore, threadId);
|
||||
expect(suspendedEntry).not.toBeNull();
|
||||
expect(suspendedEntry!.status).toBe("suspended");
|
||||
expect(suspendedEntry!.suspendedRole).toBe("planner");
|
||||
expect(suspendedEntry!.suspendMessage).toBe("Need more info: missing requirements");
|
||||
|
||||
// Resume re-runs the planner role; the second scripted step is `ready` → $END.
|
||||
const resume = runResume(threadId, "Here are the requirements");
|
||||
expect(resume.exitCode).toBe(0);
|
||||
const resumeOut = JSON.parse(resume.stdout.trim()) as StepOutputJson;
|
||||
expect(resumeOut.status).toBe("completed");
|
||||
expect(resumeOut.done).toBe(true);
|
||||
expect(resumeOut.currentRole).toBeNull();
|
||||
expect(resumeOut.suspendedRole).toBeNull();
|
||||
|
||||
// CAS chain: suspended planner step → resumed planner step.
|
||||
const store = await openStore(casDir);
|
||||
const s1 = getStepNode(store, step1.head);
|
||||
const s2 = getStepNode(store, resumeOut.head);
|
||||
expect(s1.role).toBe("planner");
|
||||
expect(s2.role).toBe("planner");
|
||||
expect(s2.prev).toBe(step1.head);
|
||||
expect(getStatus(store, s1.output)).toBe("insufficient_info");
|
||||
expect(getStatus(store, s2.output)).toBe("ready");
|
||||
|
||||
const finalEntry = getThread((await createUwfStore(uwfHome)).varStore, threadId);
|
||||
expect(finalEntry).not.toBeNull();
|
||||
expect(finalEntry!.status).toBe("completed");
|
||||
expect(finalEntry!.head).toBe(resumeOut.head);
|
||||
});
|
||||
|
||||
test("5. --count 3 runs the whole linear pipeline in one invocation", async () => {
|
||||
await writeMockConfig("e2e-count.mock.yaml");
|
||||
const workflowHash = await addWorkflow("e2e-count.workflow.yaml", "test-count");
|
||||
|
||||
const start = await cmdThreadStart(uwfHome, workflowHash, "Ship the feature", uwfHome, tmpDir);
|
||||
const threadId = start.thread;
|
||||
|
||||
// Single invocation with --count 3 → moderator drives analyst → developer → reviewer → $END.
|
||||
const { stdout, stderr, exitCode } = runExec(threadId, 3);
|
||||
expect(exitCode, `stderr: ${stderr}`).toBe(0);
|
||||
|
||||
// Multi-step exec emits a JSON array (one entry per executed step).
|
||||
const results = JSON.parse(stdout.trim()) as StepOutputJson[];
|
||||
expect(Array.isArray(results)).toBe(true);
|
||||
expect(results).toHaveLength(3);
|
||||
|
||||
expect(results[0].status).toBe("idle");
|
||||
expect(results[0].currentRole).toBe("developer");
|
||||
expect(results[1].status).toBe("idle");
|
||||
expect(results[1].currentRole).toBe("reviewer");
|
||||
expect(results[2].status).toBe("completed");
|
||||
expect(results[2].done).toBe(true);
|
||||
|
||||
// Verify the CAS chain holds 3 step nodes in the correct order.
|
||||
const store = await openStore(casDir);
|
||||
const n1 = getStepNode(store, results[0].head);
|
||||
const n2 = getStepNode(store, results[1].head);
|
||||
const n3 = getStepNode(store, results[2].head);
|
||||
expect([n1.role, n2.role, n3.role]).toEqual(["analyst", "developer", "reviewer"]);
|
||||
expect(n1.prev).toBeNull();
|
||||
expect(n2.prev).toBe(results[0].head);
|
||||
expect(n3.prev).toBe(results[1].head);
|
||||
expect(new Set([n1.start, n2.start, n3.start]).size).toBe(1);
|
||||
|
||||
const finalEntry = getThread((await createUwfStore(uwfHome)).varStore, threadId);
|
||||
expect(finalEntry).not.toBeNull();
|
||||
expect(finalEntry!.status).toBe("completed");
|
||||
expect(finalEntry!.head).toBe(results[2].head);
|
||||
});
|
||||
|
||||
test("6. mustache edge prompt renders planner variables into the worker step", async () => {
|
||||
await writeMockConfig("e2e-mustache.mock.yaml");
|
||||
const workflowHash = await addWorkflow("e2e-mustache.workflow.yaml", "test-mustache");
|
||||
|
||||
const start = await cmdThreadStart(uwfHome, workflowHash, "Plan the task", uwfHome, tmpDir);
|
||||
const threadId = start.thread;
|
||||
|
||||
// Step 1 → planner emits branch + repoPath.
|
||||
const step1 = execStep(threadId);
|
||||
expect(step1.status).toBe("idle");
|
||||
expect(step1.currentRole).toBe("worker");
|
||||
|
||||
// Step 2 → worker; the moderator renders the templated edge prompt before spawning it.
|
||||
const step2 = execStep(threadId);
|
||||
expect(step2.done).toBe(true);
|
||||
expect(step2.status).toBe("completed");
|
||||
|
||||
const store = await openStore(casDir);
|
||||
const plannerStep = getStepNode(store, step1.head);
|
||||
expect(getStatus(store, plannerStep.output)).toBe("ready");
|
||||
|
||||
// The worker step's edgePrompt is the mustache-rendered template.
|
||||
const workerStep = getStepNode(store, step2.head);
|
||||
expect(workerStep.role).toBe("worker");
|
||||
expect(workerStep.edgePrompt).toContain("fix/42-auth");
|
||||
expect(workerStep.edgePrompt).toContain("/tmp/my-repo");
|
||||
expect(workerStep.edgePrompt).toBe("Work on branch fix/42-auth in /tmp/my-repo");
|
||||
});
|
||||
|
||||
test("7. completed thread can be resumed (衔尾蛇: end → start)", async () => {
|
||||
// Reuse the suspend workflow (planner with ready → $END), but mock data
|
||||
// goes straight to ready on first run, then ready again after resume.
|
||||
await writeMockConfig("e2e-completed-resume.mock.yaml");
|
||||
const workflowHash = await addWorkflow("e2e-suspend.workflow.yaml", "test-suspend");
|
||||
|
||||
const start = await cmdThreadStart(uwfHome, workflowHash, "Do the work", uwfHome, tmpDir);
|
||||
const threadId = start.thread;
|
||||
|
||||
// Step 1: planner outputs ready → $END → thread completed.
|
||||
const step1 = execStep(threadId);
|
||||
expect(step1.done).toBe(true);
|
||||
expect(step1.status).toBe("completed");
|
||||
|
||||
const uwf1 = await createUwfStore(uwfHome);
|
||||
const entry1 = getThread(uwf1.varStore, threadId);
|
||||
expect(entry1).not.toBeNull();
|
||||
expect(entry1!.status).toBe("completed");
|
||||
|
||||
// Resume the completed thread — should re-evaluate $START → planner.
|
||||
const resumeResult = runResume(threadId, "Additional context for round 2");
|
||||
expect(resumeResult.exitCode).toBe(0);
|
||||
|
||||
// After resume step, planner ran again (step index 1 in mock) → ready → $END.
|
||||
const uwf2 = await createUwfStore(uwfHome);
|
||||
const entry2 = getThread(uwf2.varStore, threadId);
|
||||
expect(entry2).not.toBeNull();
|
||||
expect(entry2!.status).toBe("completed");
|
||||
// Head should have advanced (not the same as step1).
|
||||
expect(entry2!.head).not.toBe(step1.head);
|
||||
|
||||
// CAS chain: step2.prev === step1 head (chain is preserved across resume).
|
||||
const store = await openStore(casDir);
|
||||
const resumeOutput = JSON.parse(resumeResult.stdout.trim());
|
||||
const step2Node = getStepNode(store, resumeOutput.head);
|
||||
expect(step2Node.role).toBe("planner");
|
||||
expect(step2Node.prev).toBe(step1.head);
|
||||
expect(getThread(uwf.varStore, threadId)).not.toBeNull();
|
||||
expect(getThread(uwf.varStore, threadId)!.head).toBe(step1.head);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
steps:
|
||||
# Step 0: planner → ready → $END (thread completes)
|
||||
- role: planner
|
||||
output: |
|
||||
---
|
||||
$status: ready
|
||||
---
|
||||
Initial plan complete.
|
||||
# Step 1: after resume, planner runs again from $START → ready → $END again
|
||||
- role: planner
|
||||
output: |
|
||||
---
|
||||
$status: ready
|
||||
---
|
||||
Revised plan after resume.
|
||||
@@ -1,19 +0,0 @@
|
||||
steps:
|
||||
- role: analyst
|
||||
output: |
|
||||
---
|
||||
$status: analyzed
|
||||
---
|
||||
Analysis complete.
|
||||
- role: developer
|
||||
output: |
|
||||
---
|
||||
$status: implemented
|
||||
---
|
||||
Implementation complete.
|
||||
- role: reviewer
|
||||
output: |
|
||||
---
|
||||
$status: approved
|
||||
---
|
||||
Approved.
|
||||
@@ -1,45 +0,0 @@
|
||||
name: test-count
|
||||
description: 3-step linear pipeline (analyst -> developer -> reviewer -> $END)
|
||||
roles:
|
||||
analyst:
|
||||
description: Analyzes the task
|
||||
goal: Analyze the task
|
||||
capabilities: []
|
||||
procedure: Analyze it
|
||||
output: Output the analysis and set $status to analyzed
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: analyzed }
|
||||
required: [$status]
|
||||
developer:
|
||||
description: Implements the change
|
||||
goal: Implement the change
|
||||
capabilities: []
|
||||
procedure: Write code
|
||||
output: Output the implementation and set $status to implemented
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: implemented }
|
||||
required: [$status]
|
||||
reviewer:
|
||||
description: Reviews the change
|
||||
goal: Review the change
|
||||
capabilities: []
|
||||
procedure: Review code
|
||||
output: Approve and set $status to approved
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: approved }
|
||||
required: [$status]
|
||||
graph:
|
||||
$START:
|
||||
_: { role: analyst, prompt: 'Analyze the task' }
|
||||
analyst:
|
||||
analyzed: { role: developer, prompt: 'Implement the change' }
|
||||
developer:
|
||||
implemented: { role: reviewer, prompt: 'Review the change' }
|
||||
reviewer:
|
||||
approved: { role: '$END', prompt: 'Done' }
|
||||
@@ -1,15 +0,0 @@
|
||||
steps:
|
||||
- role: planner
|
||||
output: |
|
||||
---
|
||||
$status: ready
|
||||
branch: fix/42-auth
|
||||
repoPath: /tmp/my-repo
|
||||
---
|
||||
Planned the work.
|
||||
- role: worker
|
||||
output: |
|
||||
---
|
||||
$status: done
|
||||
---
|
||||
Work complete.
|
||||
@@ -1,34 +0,0 @@
|
||||
name: test-mustache
|
||||
description: Planner emits template variables consumed by the worker edge prompt
|
||||
roles:
|
||||
planner:
|
||||
description: Plans work and emits branch + repo path
|
||||
goal: Plan the task
|
||||
capabilities: []
|
||||
procedure: Decide the branch and repo path
|
||||
output: Set $status to ready and emit branch and repoPath
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: ready }
|
||||
branch: { type: string }
|
||||
repoPath: { type: string }
|
||||
required: [$status, branch, repoPath]
|
||||
worker:
|
||||
description: Works on the planned branch
|
||||
goal: Do the work
|
||||
capabilities: []
|
||||
procedure: Do it
|
||||
output: Output the result and set $status to done
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: done }
|
||||
required: [$status]
|
||||
graph:
|
||||
$START:
|
||||
_: { role: planner, prompt: 'Plan the task' }
|
||||
planner:
|
||||
ready: { role: worker, prompt: 'Work on branch {{{branch}}} in {{{repoPath}}}' }
|
||||
worker:
|
||||
done: { role: '$END', prompt: 'Complete' }
|
||||
@@ -1,14 +0,0 @@
|
||||
steps:
|
||||
- role: planner
|
||||
output: |
|
||||
---
|
||||
$status: insufficient_info
|
||||
reason: missing requirements
|
||||
---
|
||||
I need more information before I can plan this.
|
||||
- role: planner
|
||||
output: |
|
||||
---
|
||||
$status: ready
|
||||
---
|
||||
I now have what I need. Ready to proceed.
|
||||
@@ -1,24 +0,0 @@
|
||||
name: test-suspend
|
||||
description: Planner can suspend for more info or finish when ready
|
||||
roles:
|
||||
planner:
|
||||
description: Plans work and may request more info
|
||||
goal: Analyze the task
|
||||
capabilities: []
|
||||
procedure: Analyze the task and decide if more info is needed
|
||||
output: Set $status to insufficient_info (with reason) or ready
|
||||
frontmatter:
|
||||
oneOf:
|
||||
- properties:
|
||||
$status: { const: insufficient_info }
|
||||
reason: { type: string }
|
||||
required: [$status, reason]
|
||||
- properties:
|
||||
$status: { const: ready }
|
||||
required: [$status]
|
||||
graph:
|
||||
$START:
|
||||
_: { role: planner, prompt: 'Analyze the task' }
|
||||
planner:
|
||||
insufficient_info: { role: '$SUSPEND', prompt: 'Need more info: {{{reason}}}' }
|
||||
ready: { role: '$END', prompt: 'Done' }
|
||||
@@ -4,7 +4,7 @@ import { join } from "node:path";
|
||||
import { type CasRef, createThreadIndexEntry, type ThreadId } from "@united-workforce/protocol";
|
||||
import { afterEach, beforeEach, describe, expect, test } from "vitest";
|
||||
import { resolveHeadHash } from "../commands/shared.js";
|
||||
import { completeThread, createUwfStore, setThread } from "../store.js";
|
||||
import { addHistoryEntry, createUwfStore, setThread } from "../store.js";
|
||||
|
||||
let tmpDir: string;
|
||||
|
||||
@@ -31,13 +31,19 @@ describe("resolveHeadHash", () => {
|
||||
expect(result).toBe(headHash);
|
||||
});
|
||||
|
||||
test("finds completed thread", async () => {
|
||||
test("falls back to history variable when thread not in active index", async () => {
|
||||
const threadId = "01JTEST0000000000000000002" as ThreadId;
|
||||
const workflowHash = "workflow_hash_789" as CasRef;
|
||||
|
||||
const uwf = await createUwfStore(tmpDir);
|
||||
const headHash = (await uwf.store.cas.put(uwf.schemas.text, "completed-head")) as CasRef;
|
||||
setThread(uwf.varStore, threadId, createThreadIndexEntry(headHash));
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: headHash,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
|
||||
const result = await resolveHeadHash(tmpDir, threadId);
|
||||
|
||||
@@ -48,36 +54,58 @@ describe("resolveHeadHash", () => {
|
||||
// calls fail() which does process.exit(1), terminating the test runner.
|
||||
// The error behavior is tested in integration tests below via CLI invocation.
|
||||
|
||||
test("prioritizes active thread", async () => {
|
||||
test("prioritizes active thread over history when thread exists in both", async () => {
|
||||
const threadId = "01JTEST0000000000000000004" as ThreadId;
|
||||
const workflowHash = "workflow_hash_xyz" as CasRef;
|
||||
|
||||
const uwf = await createUwfStore(tmpDir);
|
||||
const activeHead = (await uwf.store.cas.put(uwf.schemas.text, "active-v2")) as CasRef;
|
||||
const historicalHash = (await uwf.store.cas.put(uwf.schemas.text, "historical-v1")) as CasRef;
|
||||
setThread(uwf.varStore, threadId, createThreadIndexEntry(activeHead));
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: historicalHash,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
|
||||
const result = await resolveHeadHash(tmpDir, threadId);
|
||||
|
||||
// Should return the active head
|
||||
// Should return the active head, not the historical one
|
||||
expect(result).toBe(activeHead);
|
||||
});
|
||||
|
||||
test("finds thread from multiple completed threads", async () => {
|
||||
test("finds thread from multiple history entries", async () => {
|
||||
const threadId1 = "01JTEST0000000000000000005" as ThreadId;
|
||||
const threadId2 = "01JTEST0000000000000000006" as ThreadId;
|
||||
const threadId3 = "01JTEST0000000000000000007" as ThreadId;
|
||||
const workflowHash = "workflow_hash_abc" as CasRef;
|
||||
const uwf = await createUwfStore(tmpDir);
|
||||
const hash1 = (await uwf.store.cas.put(uwf.schemas.text, "hash-thread1")) as CasRef;
|
||||
const hash2 = (await uwf.store.cas.put(uwf.schemas.text, "hash-thread2")) as CasRef;
|
||||
const hash3 = (await uwf.store.cas.put(uwf.schemas.text, "hash-thread3")) as CasRef;
|
||||
|
||||
setThread(uwf.varStore, threadId1, createThreadIndexEntry(hash1));
|
||||
completeThread(uwf.varStore, threadId1, "completed");
|
||||
|
||||
setThread(uwf.varStore, threadId2, createThreadIndexEntry(hash2));
|
||||
completeThread(uwf.varStore, threadId2, "completed");
|
||||
|
||||
setThread(uwf.varStore, threadId3, createThreadIndexEntry(hash3));
|
||||
completeThread(uwf.varStore, threadId3, "completed");
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId1,
|
||||
workflow: workflowHash,
|
||||
head: hash1,
|
||||
completedAt: Date.now() - 2000,
|
||||
reason: null,
|
||||
});
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId2,
|
||||
workflow: workflowHash,
|
||||
head: hash2,
|
||||
completedAt: Date.now() - 1000,
|
||||
reason: null,
|
||||
});
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId3,
|
||||
workflow: workflowHash,
|
||||
head: hash3,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
|
||||
const result = await resolveHeadHash(tmpDir, threadId2);
|
||||
|
||||
|
||||
@@ -226,15 +226,19 @@ describe("Global CAS directory", () => {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const threadId = "thread-123" as ThreadId;
|
||||
const headHash = await uwf.store.cas.put(uwf.schemas.text, "history-head");
|
||||
const { completeThread, setThread, getThread } = await import("../store.js");
|
||||
const { createThreadIndexEntry } = await import("@united-workforce/protocol");
|
||||
const { addHistoryEntry, findHistoryEntry } = await import("../store.js");
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: "workflow-456",
|
||||
head: headHash,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
setThread(uwf.varStore, threadId, createThreadIndexEntry(headHash));
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
const entry = findHistoryEntry(uwf.varStore, threadId);
|
||||
expect(entry?.thread).toBe(threadId);
|
||||
expect(entry?.workflow).toBe("workflow-456");
|
||||
expect(entry?.head).toBe(headHash);
|
||||
expect(entry?.status).toBe("completed");
|
||||
|
||||
const { access } = await import("node:fs/promises");
|
||||
await access(join(globalCasDir, "vars"));
|
||||
@@ -270,12 +274,15 @@ describe("Global CAS directory", () => {
|
||||
);
|
||||
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const { getThread } = await import("../store.js");
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.head).toBe(headHash);
|
||||
expect(entry?.status).toBe("cancelled");
|
||||
expect(entry?.completedAt).toBe(completedAt);
|
||||
const { findHistoryEntry } = await import("../store.js");
|
||||
const entry = findHistoryEntry(uwf.varStore, threadId);
|
||||
expect(entry).toEqual({
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: headHash,
|
||||
completedAt,
|
||||
reason: "cancelled",
|
||||
});
|
||||
|
||||
await expect(access(historyPath)).rejects.toThrow();
|
||||
const migratedContent = await readFile(`${historyPath}.migrated`, "utf8");
|
||||
|
||||
@@ -1,235 +0,0 @@
|
||||
import { mkdir, mkdtemp } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CasRef, ThreadId } from "@united-workforce/protocol";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
completeThread,
|
||||
createUwfStore,
|
||||
getThread,
|
||||
loadActiveThreads,
|
||||
loadHistoryThreads,
|
||||
setThread,
|
||||
} from "../store.js";
|
||||
|
||||
async function makeUwfStore(storageRoot: string) {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
process.env.OCAS_HOME = casDir;
|
||||
return createUwfStore(storageRoot);
|
||||
}
|
||||
|
||||
async function seedThreadHead(
|
||||
uwf: Awaited<ReturnType<typeof createUwfStore>>,
|
||||
label: string,
|
||||
): Promise<CasRef> {
|
||||
return (await uwf.store.cas.put(uwf.schemas.text, label)) as CasRef;
|
||||
}
|
||||
|
||||
describe("unified thread storage", () => {
|
||||
test("loadActiveThreads excludes completed threads", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-active-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
|
||||
const threadId1 = "01JTEST000000000000ACTIVE1" as ThreadId;
|
||||
const threadId2 = "01JTEST000000000000ACTIVE2" as ThreadId;
|
||||
const head1 = await seedThreadHead(uwf, "active-head");
|
||||
const head2 = await seedThreadHead(uwf, "completed-head");
|
||||
|
||||
setThread(uwf.varStore, threadId1, {
|
||||
head: head1,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
setThread(uwf.varStore, threadId2, {
|
||||
head: head2,
|
||||
status: "completed",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: Date.now(),
|
||||
});
|
||||
|
||||
const active = loadActiveThreads(uwf.varStore);
|
||||
expect(Object.keys(active)).toHaveLength(1);
|
||||
expect(active[threadId1]).toBeDefined();
|
||||
expect(active[threadId2]).toBeUndefined();
|
||||
});
|
||||
|
||||
test("loadActiveThreads excludes cancelled threads", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-active-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
|
||||
const threadId1 = "01JTEST000000000000ACTIVE3" as ThreadId;
|
||||
const threadId2 = "01JTEST000000000000ACTIVE4" as ThreadId;
|
||||
const head1 = await seedThreadHead(uwf, "active-head");
|
||||
const head2 = await seedThreadHead(uwf, "cancelled-head");
|
||||
|
||||
setThread(uwf.varStore, threadId1, {
|
||||
head: head1,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
setThread(uwf.varStore, threadId2, {
|
||||
head: head2,
|
||||
status: "cancelled",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: Date.now(),
|
||||
});
|
||||
|
||||
const active = loadActiveThreads(uwf.varStore);
|
||||
expect(Object.keys(active)).toHaveLength(1);
|
||||
expect(active[threadId1]).toBeDefined();
|
||||
expect(active[threadId2]).toBeUndefined();
|
||||
});
|
||||
|
||||
test("loadHistoryThreads only returns completed and cancelled", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-history-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
|
||||
const threadId1 = "01JTEST000000000000HISTOR1" as ThreadId;
|
||||
const threadId2 = "01JTEST000000000000HISTOR2" as ThreadId;
|
||||
const threadId3 = "01JTEST000000000000HISTOR3" as ThreadId;
|
||||
const head1 = await seedThreadHead(uwf, "active-head");
|
||||
const head2 = await seedThreadHead(uwf, "completed-head");
|
||||
const head3 = await seedThreadHead(uwf, "cancelled-head");
|
||||
|
||||
setThread(uwf.varStore, threadId1, {
|
||||
head: head1,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
setThread(uwf.varStore, threadId2, {
|
||||
head: head2,
|
||||
status: "completed",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: Date.now(),
|
||||
});
|
||||
|
||||
setThread(uwf.varStore, threadId3, {
|
||||
head: head3,
|
||||
status: "cancelled",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: Date.now(),
|
||||
});
|
||||
|
||||
const history = loadHistoryThreads(uwf.varStore);
|
||||
expect(Object.keys(history)).toHaveLength(2);
|
||||
expect(history[threadId1]).toBeUndefined();
|
||||
expect(history[threadId2]).toBeDefined();
|
||||
expect(history[threadId3]).toBeDefined();
|
||||
});
|
||||
|
||||
test("completeThread marks thread as completed", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-complete-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const threadId = "01JTEST000000000000COMPLE1" as ThreadId;
|
||||
const head = await seedThreadHead(uwf, "active-head");
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("completed");
|
||||
expect(entry?.completedAt).toBeDefined();
|
||||
expect(entry?.completedAt).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("completeThread marks thread as cancelled", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-complete-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const threadId = "01JTEST000000000000COMPLE2" as ThreadId;
|
||||
const head = await seedThreadHead(uwf, "active-head");
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
completeThread(uwf.varStore, threadId, "cancelled");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("cancelled");
|
||||
expect(entry?.completedAt).toBeDefined();
|
||||
expect(entry?.completedAt).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("completeThread clears suspend metadata", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-complete-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const threadId = "01JTEST000000000000COMPLE3" as ThreadId;
|
||||
const head = await seedThreadHead(uwf, "suspended-head");
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head,
|
||||
status: "suspended",
|
||||
suspendedRole: "test-role",
|
||||
suspendMessage: "test message",
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("completed");
|
||||
expect(entry?.suspendedRole).toBeNull();
|
||||
expect(entry?.suspendMessage).toBeNull();
|
||||
});
|
||||
|
||||
test("completeThread handles non-existent thread gracefully", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-complete-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const threadId = "01JTEST000000000000NOEXIST" as ThreadId;
|
||||
|
||||
// Should not throw
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).toBeNull();
|
||||
});
|
||||
|
||||
test("status and completedAt tags are persisted and loaded", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-tags-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const threadId = "01JTEST000000000000TAGTEST" as ThreadId;
|
||||
const head = await seedThreadHead(uwf, "test-head");
|
||||
const now = Date.now();
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head,
|
||||
status: "completed",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: now,
|
||||
});
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("completed");
|
||||
expect(entry?.completedAt).toBe(now);
|
||||
});
|
||||
});
|
||||
@@ -3,13 +3,7 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import type { CasRef, ThreadId } from "@united-workforce/protocol";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
completeThread,
|
||||
createUwfStore,
|
||||
getThread,
|
||||
loadHistoryThreads,
|
||||
setThread,
|
||||
} from "../store.js";
|
||||
import { addHistoryEntry, createUwfStore, loadAllHistory } from "../store.js";
|
||||
|
||||
async function makeUwfStore(storageRoot: string) {
|
||||
const casDir = join(storageRoot, "cas");
|
||||
@@ -26,113 +20,88 @@ async function seedHistoryHead(
|
||||
}
|
||||
|
||||
describe("thread cancel status", () => {
|
||||
test("cancelled thread has status 'cancelled'", async () => {
|
||||
test("cancelled history entry has reason 'cancelled'", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-cancel-test-"));
|
||||
const threadId = "01JTEST000000000000CANCEL1" as ThreadId;
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const head = await seedHistoryHead(uwf, "cancelled-head");
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: "test-workflow",
|
||||
head,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
});
|
||||
|
||||
completeThread(uwf.varStore, threadId, "cancelled");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("cancelled");
|
||||
const history = loadAllHistory(uwf.varStore);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0]?.reason).toBe("cancelled");
|
||||
});
|
||||
|
||||
test("completed thread has status 'completed'", async () => {
|
||||
test("completed history entry has reason 'completed'", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-cancel-test-"));
|
||||
const threadId = "01JTEST000000000000CANCEL2" as ThreadId;
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const head = await seedHistoryHead(uwf, "completed-head");
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: "test-workflow",
|
||||
head,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
expect(entry).not.toBeNull();
|
||||
expect(entry?.status).toBe("completed");
|
||||
const history = loadAllHistory(uwf.varStore);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0]?.reason).toBe("completed");
|
||||
});
|
||||
|
||||
test("loadHistoryThreads returns completed and cancelled", async () => {
|
||||
test("history entry with null reason is stored as completed", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-cancel-test-"));
|
||||
const threadId = "01JTEST000000000000CANCEL3" as ThreadId;
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const head = await seedHistoryHead(uwf, "legacy-head");
|
||||
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: "test-workflow",
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
|
||||
const history = loadAllHistory(uwf.varStore);
|
||||
expect(history).toHaveLength(1);
|
||||
expect(history[0]?.reason).toBe("completed");
|
||||
});
|
||||
|
||||
test("mixed completed and cancelled entries preserve distinct reasons", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-cancel-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const head1 = await seedHistoryHead(uwf, "head1");
|
||||
const head2 = await seedHistoryHead(uwf, "head2");
|
||||
|
||||
const threadId1 = "01JTEST000000000000CANCEL4" as ThreadId;
|
||||
setThread(uwf.varStore, threadId1, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: "01JTEST000000000000CANCEL4" as ThreadId,
|
||||
workflow: "test-workflow",
|
||||
head: head1,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
completeThread(uwf.varStore, threadId1, "completed");
|
||||
|
||||
const threadId2 = "01JTEST000000000000CANCEL5" as ThreadId;
|
||||
setThread(uwf.varStore, threadId2, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: "01JTEST000000000000CANCEL5" as ThreadId,
|
||||
workflow: "test-workflow",
|
||||
head: head2,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
});
|
||||
completeThread(uwf.varStore, threadId2, "cancelled");
|
||||
|
||||
const history = loadHistoryThreads(uwf.varStore);
|
||||
expect(Object.keys(history)).toHaveLength(2);
|
||||
const statuses = Object.values(history)
|
||||
.map((entry) => entry.status)
|
||||
.sort();
|
||||
expect(statuses).toEqual(["cancelled", "completed"]);
|
||||
});
|
||||
|
||||
test("mixed completed and cancelled entries preserve distinct statuses", async () => {
|
||||
const tmpDir = await mkdtemp(join(tmpdir(), "uwf-cancel-test-"));
|
||||
const uwf = await makeUwfStore(tmpDir);
|
||||
const head1 = await seedHistoryHead(uwf, "head1");
|
||||
const head2 = await seedHistoryHead(uwf, "head2");
|
||||
|
||||
const threadId1 = "01JTEST000000000000CANCEL6" as ThreadId;
|
||||
setThread(uwf.varStore, threadId1, {
|
||||
head: head1,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId1, "completed");
|
||||
|
||||
const threadId2 = "01JTEST000000000000CANCEL7" as ThreadId;
|
||||
setThread(uwf.varStore, threadId2, {
|
||||
head: head2,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId2, "cancelled");
|
||||
|
||||
const history = loadHistoryThreads(uwf.varStore);
|
||||
expect(Object.keys(history)).toHaveLength(2);
|
||||
const statuses = Object.values(history)
|
||||
.map((entry) => entry.status)
|
||||
.sort();
|
||||
expect(statuses).toEqual(["cancelled", "completed"]);
|
||||
const history = loadAllHistory(uwf.varStore);
|
||||
expect(history).toHaveLength(2);
|
||||
const reasons = history.map((entry) => entry.reason).sort();
|
||||
expect(reasons).toEqual(["cancelled", "completed"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,8 +10,9 @@ import { cmdThreadList } from "../commands/thread.js";
|
||||
import { parseTimeInput } from "../commands/thread-time-parser.js";
|
||||
import type { UwfStore } from "../store.js";
|
||||
import {
|
||||
completeThread as completeThreadInStore,
|
||||
addHistoryEntry,
|
||||
createUwfStore,
|
||||
deleteThread,
|
||||
loadAllThreads,
|
||||
setThread,
|
||||
} from "../store.js";
|
||||
@@ -72,11 +73,18 @@ async function markThreadRunning(storageRoot: string, threadId: ThreadId, workfl
|
||||
async function completeThread(
|
||||
storageRoot: string,
|
||||
threadId: ThreadId,
|
||||
_workflowHash: CasRef,
|
||||
_headHash: CasRef,
|
||||
workflowHash: CasRef,
|
||||
headHash: CasRef,
|
||||
) {
|
||||
const uwfIdx = await createUwfStore(storageRoot);
|
||||
completeThreadInStore(uwfIdx.varStore, threadId, "completed");
|
||||
deleteThread(uwfIdx.varStore, threadId);
|
||||
addHistoryEntry(uwfIdx.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: headHash,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
}
|
||||
|
||||
// ── test setup ────────────────────────────────────────────────────────────────
|
||||
@@ -492,10 +500,8 @@ describe("edge cases", () => {
|
||||
)) as CasRef;
|
||||
index["INVALID_ULID_FORMAT_HERE" as ThreadId] = {
|
||||
head: placeholderHead,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
};
|
||||
for (const [tid, ent] of Object.entries(index)) {
|
||||
setThread(uwfIdx.varStore, tid as ThreadId, ent);
|
||||
|
||||
@@ -118,10 +118,8 @@ async function setupSuspendedThread(mode: MockAgentMode): Promise<{
|
||||
await seedThreads(tmpDir, {
|
||||
[THREAD_ID]: {
|
||||
head: stepHash,
|
||||
status: "suspended",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: SUSPEND_MESSAGE,
|
||||
completedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
@@ -249,7 +247,7 @@ describe("uwf thread resume", () => {
|
||||
|
||||
const result = runUwf(["thread", "resume", THREAD_ID], casDir);
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(result.stderr).toContain("thread cannot be resumed");
|
||||
expect(result.stderr).toContain("thread is not suspended");
|
||||
});
|
||||
|
||||
test("resume suspended thread executes step and becomes idle", async () => {
|
||||
@@ -349,10 +347,8 @@ describe("uwf thread resume", () => {
|
||||
const uwfAfterFirst = await createUwfStore(tmpDir);
|
||||
expect(getThread(uwfAfterFirst.varStore, THREAD_ID)).toEqual({
|
||||
head: firstResume.head,
|
||||
status: "suspended",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: SUSPEND_MESSAGE,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
const { mockAgentPath: okMockAgentPath } = await setupOkMockAgent(
|
||||
@@ -448,266 +444,3 @@ echo '${adapterJson}'
|
||||
|
||||
return { mockAgentPath };
|
||||
}
|
||||
|
||||
describe("uwf thread resume - completed threads", () => {
|
||||
test("resume completed thread starts from $START role", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
const store = await openStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
const outputSchemaHash = await putSchema(store, OUTPUT_SCHEMA);
|
||||
|
||||
const workflowHash = await store.cas.put(schemas.workflow, {
|
||||
name: "test-completed-resume",
|
||||
description: "completed thread resume test",
|
||||
roles: {
|
||||
worker: {
|
||||
description: "Worker role",
|
||||
goal: "Work",
|
||||
capabilities: [],
|
||||
procedure: "work",
|
||||
output: "result",
|
||||
frontmatter: outputSchemaHash,
|
||||
},
|
||||
reviewer: {
|
||||
description: "Reviewer role",
|
||||
goal: "Review",
|
||||
capabilities: [],
|
||||
procedure: "review",
|
||||
output: "result",
|
||||
frontmatter: outputSchemaHash,
|
||||
},
|
||||
},
|
||||
graph: {
|
||||
$START: { _: { role: "worker", prompt: "Start work", location: null } },
|
||||
worker: { _: { role: "reviewer", prompt: "Review the work", location: null } },
|
||||
reviewer: { _: { role: "$END", prompt: "Done", location: null } },
|
||||
},
|
||||
});
|
||||
|
||||
const startHash = await store.cas.put(schemas.startNode, {
|
||||
workflow: workflowHash,
|
||||
prompt: "Initial task",
|
||||
cwd: tmpDir,
|
||||
});
|
||||
|
||||
process.env.OCAS_HOME = casDir;
|
||||
|
||||
const workerOutputHash = await store.cas.put(outputSchemaHash, { $status: "_" });
|
||||
const reviewerOutputHash = await store.cas.put(outputSchemaHash, { $status: "_" });
|
||||
const detailHash = await store.cas.put(schemas.text, "mock detail");
|
||||
|
||||
const workerStepHash = await store.cas.put(schemas.stepNode, {
|
||||
start: startHash,
|
||||
prev: null,
|
||||
role: "worker",
|
||||
output: workerOutputHash,
|
||||
detail: detailHash,
|
||||
agent: "uwf-mock",
|
||||
edgePrompt: "Start work",
|
||||
startedAtMs: 1716600000000,
|
||||
completedAtMs: 1716600001000,
|
||||
cwd: tmpDir,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const reviewerStepHash = await store.cas.put(schemas.stepNode, {
|
||||
start: startHash,
|
||||
prev: workerStepHash,
|
||||
role: "reviewer",
|
||||
output: reviewerOutputHash,
|
||||
detail: detailHash,
|
||||
agent: "uwf-mock",
|
||||
edgePrompt: "Review the work",
|
||||
startedAtMs: 1716600001000,
|
||||
completedAtMs: 1716600002000,
|
||||
cwd: tmpDir,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
await seedThreads(tmpDir, {
|
||||
[THREAD_ID]: {
|
||||
head: reviewerStepHash,
|
||||
status: "completed",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: 1716600002000,
|
||||
},
|
||||
});
|
||||
|
||||
// Verify the status was actually set
|
||||
const { createUwfStore, getThread } = await import("../store.js");
|
||||
const verifyUwf = await createUwfStore(tmpDir);
|
||||
const verifyEntry = getThread(verifyUwf.varStore, THREAD_ID);
|
||||
// biome-ignore lint/suspicious/noConsole: test debugging
|
||||
console.log("Seeded entry status:", verifyEntry?.status);
|
||||
// biome-ignore lint/suspicious/noConsole: test debugging
|
||||
console.log("Seeded entry:", JSON.stringify(verifyEntry, null, 2));
|
||||
|
||||
const promptCapturePath = join(tmpDir, "captured-prompt-completed.txt");
|
||||
const mockAgentPath = join(tmpDir, "mock-agent-completed.sh");
|
||||
|
||||
const newWorkerStepHash = await store.cas.put(schemas.stepNode, {
|
||||
start: startHash,
|
||||
prev: reviewerStepHash,
|
||||
role: "worker",
|
||||
output: workerOutputHash,
|
||||
detail: detailHash,
|
||||
agent: "uwf-mock",
|
||||
edgePrompt: "Start work",
|
||||
startedAtMs: 1716600003000,
|
||||
completedAtMs: 1716600004000,
|
||||
cwd: tmpDir,
|
||||
assembledPrompt: null,
|
||||
});
|
||||
|
||||
const adapterJson = JSON.stringify({
|
||||
stepHash: newWorkerStepHash,
|
||||
detailHash,
|
||||
role: "worker",
|
||||
frontmatter: { $status: "_" },
|
||||
body: "",
|
||||
startedAtMs: 1716600003000,
|
||||
completedAtMs: 1716600004000,
|
||||
});
|
||||
|
||||
await writeFile(
|
||||
mockAgentPath,
|
||||
`#!/bin/sh
|
||||
prompt=""
|
||||
while [ $# -gt 0 ]; do
|
||||
if [ "$1" = "--prompt" ]; then
|
||||
prompt="$2"
|
||||
shift 2
|
||||
else
|
||||
shift
|
||||
fi
|
||||
done
|
||||
printf '%s' "$prompt" > '${promptCapturePath}'
|
||||
echo '${adapterJson}'
|
||||
`,
|
||||
{ mode: 0o755 },
|
||||
);
|
||||
|
||||
const configPath = join(tmpDir, "config.yaml");
|
||||
await writeFile(
|
||||
configPath,
|
||||
`defaultAgent: uwf-hermes\ndefaultModel: test-model\nagentOverrides: null\nagents: {}\nproviders: {}\nmodels: {}\n`,
|
||||
);
|
||||
|
||||
const result = runUwf(
|
||||
["thread", "resume", THREAD_ID, "-p", "Additional context", "--agent", mockAgentPath],
|
||||
casDir,
|
||||
);
|
||||
|
||||
if (result.status !== 0) {
|
||||
// biome-ignore lint/suspicious/noConsole: test debugging
|
||||
console.error("Command failed:", result.stderr);
|
||||
}
|
||||
|
||||
expect(result.status).toBe(0);
|
||||
|
||||
const cliOutput = JSON.parse(result.stdout.trim());
|
||||
expect(cliOutput.status).toBe("idle");
|
||||
expect(cliOutput.currentRole).toBe("reviewer");
|
||||
expect(cliOutput.done).toBe(false);
|
||||
|
||||
const capturedPrompt = await readFile(promptCapturePath, "utf8");
|
||||
expect(capturedPrompt).toContain("Previous run completed");
|
||||
expect(capturedPrompt).toContain("Additional context");
|
||||
|
||||
const storeModule = await import("../store.js");
|
||||
const uwf2 = await storeModule.createUwfStore(tmpDir);
|
||||
const entry2 = storeModule.getThread(uwf2.varStore, THREAD_ID);
|
||||
expect(entry2?.status).toBe("idle");
|
||||
expect(entry2?.completedAt).toBeNull();
|
||||
});
|
||||
|
||||
test("resume cancelled thread returns error", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
const store = await openStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
|
||||
const workflowHash = await store.cas.put(schemas.workflow, {
|
||||
name: "cancelled-workflow",
|
||||
description: "cancelled thread",
|
||||
roles: {
|
||||
worker: {
|
||||
description: "Worker",
|
||||
goal: "Work",
|
||||
capabilities: [],
|
||||
procedure: "work",
|
||||
output: "result",
|
||||
frontmatter: await putSchema(store, OUTPUT_SCHEMA),
|
||||
},
|
||||
},
|
||||
graph: {
|
||||
$START: { _: { role: "worker", prompt: "Start", location: null } },
|
||||
worker: { _: { role: "$END", prompt: "Done", location: null } },
|
||||
},
|
||||
});
|
||||
|
||||
const startHash = await store.cas.put(schemas.startNode, {
|
||||
workflow: workflowHash,
|
||||
prompt: "task",
|
||||
cwd: tmpDir,
|
||||
});
|
||||
|
||||
process.env.OCAS_HOME = casDir;
|
||||
await seedThreads(tmpDir, {
|
||||
[THREAD_ID]: {
|
||||
head: startHash,
|
||||
status: "cancelled",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
},
|
||||
});
|
||||
|
||||
const result = runUwf(["thread", "resume", THREAD_ID], casDir);
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(result.stderr).toContain("thread cannot be resumed");
|
||||
expect(result.stderr).toContain("cancelled");
|
||||
});
|
||||
|
||||
test("resume idle thread returns error", async () => {
|
||||
const casDir = join(tmpDir, "cas");
|
||||
await mkdir(casDir, { recursive: true });
|
||||
const store = await openStore(casDir);
|
||||
const schemas = await registerUwfSchemas(store);
|
||||
|
||||
const workflowHash = await store.cas.put(schemas.workflow, {
|
||||
name: "idle-workflow",
|
||||
description: "idle thread",
|
||||
roles: {
|
||||
worker: {
|
||||
description: "Worker",
|
||||
goal: "Work",
|
||||
capabilities: [],
|
||||
procedure: "work",
|
||||
output: "result",
|
||||
frontmatter: await putSchema(store, OUTPUT_SCHEMA),
|
||||
},
|
||||
},
|
||||
graph: {
|
||||
$START: { _: { role: "worker", prompt: "Start", location: null } },
|
||||
worker: { _: { role: "$END", prompt: "Done", location: null } },
|
||||
},
|
||||
});
|
||||
|
||||
const startHash = await store.cas.put(schemas.startNode, {
|
||||
workflow: workflowHash,
|
||||
prompt: "task",
|
||||
cwd: tmpDir,
|
||||
});
|
||||
|
||||
process.env.OCAS_HOME = casDir;
|
||||
await seedThreads(tmpDir, { [THREAD_ID]: startHash });
|
||||
|
||||
const result = runUwf(["thread", "resume", THREAD_ID], casDir);
|
||||
expect(result.status).not.toBe(0);
|
||||
expect(result.stderr).toContain("thread cannot be resumed");
|
||||
expect(result.stderr).toContain("idle");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,13 @@ import type { CasRef, ThreadId } from "@united-workforce/protocol";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createMarker, deleteMarker } from "../background/index.js";
|
||||
import { cmdThreadShow, cmdThreadStart } from "../commands/thread.js";
|
||||
import { completeThread, createUwfStore, loadAllThreads, setThread } from "../store.js";
|
||||
import {
|
||||
addHistoryEntry,
|
||||
createUwfStore,
|
||||
deleteThread,
|
||||
loadAllThreads,
|
||||
setThread,
|
||||
} from "../store.js";
|
||||
|
||||
const OUTPUT_SCHEMA = {
|
||||
type: "object" as const,
|
||||
@@ -112,13 +118,7 @@ async function insertStepNode(
|
||||
assembledPrompt: null,
|
||||
})) as CasRef;
|
||||
|
||||
setThread(uwf.varStore, threadId, {
|
||||
head: stepHash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
setThread(uwf.varStore, threadId, { head: stepHash, suspendedRole: null, suspendMessage: null });
|
||||
}
|
||||
|
||||
describe("thread show status field", () => {
|
||||
@@ -200,7 +200,7 @@ describe("thread show status field", () => {
|
||||
// Create a thread
|
||||
const startResult = await cmdThreadStart(storageRoot, workflowPath, "test prompt", tmpDir);
|
||||
const threadId = startResult.thread as ThreadId;
|
||||
const _workflow = startResult.workflow;
|
||||
const workflow = startResult.workflow;
|
||||
|
||||
// Get the head hash before moving to history
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
@@ -208,7 +208,15 @@ describe("thread show status field", () => {
|
||||
const head = index[threadId]!.head;
|
||||
if (!head) throw new Error("Thread not found in index");
|
||||
|
||||
completeThread(uwfForIndex.varStore, threadId, "completed");
|
||||
deleteThread(uwfForIndex.varStore, threadId);
|
||||
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, threadId);
|
||||
|
||||
@@ -229,7 +237,7 @@ describe("thread show status field", () => {
|
||||
// Create a thread
|
||||
const startResult = await cmdThreadStart(storageRoot, workflowPath, "test prompt", tmpDir);
|
||||
const threadId = startResult.thread as ThreadId;
|
||||
const _workflow = startResult.workflow;
|
||||
const workflow = startResult.workflow;
|
||||
|
||||
// Get the head hash before moving to history
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
@@ -237,7 +245,15 @@ describe("thread show status field", () => {
|
||||
const head = index[threadId]!.head;
|
||||
if (!head) throw new Error("Thread not found in index");
|
||||
|
||||
completeThread(uwfForIndex.varStore, threadId, "cancelled");
|
||||
deleteThread(uwfForIndex.varStore, threadId);
|
||||
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, threadId);
|
||||
|
||||
@@ -258,7 +274,7 @@ describe("thread show status field", () => {
|
||||
// Create a thread
|
||||
const startResult = await cmdThreadStart(storageRoot, workflowPath, "test prompt", tmpDir);
|
||||
const threadId = startResult.thread as ThreadId;
|
||||
const _workflow = startResult.workflow;
|
||||
const workflow = startResult.workflow;
|
||||
|
||||
// Get the head hash before moving to history
|
||||
const uwfForIndex = await createUwfStore(storageRoot);
|
||||
@@ -266,7 +282,15 @@ describe("thread show status field", () => {
|
||||
const head = index[threadId]!.head;
|
||||
if (!head) throw new Error("Thread not found in index");
|
||||
|
||||
completeThread(uwfForIndex.varStore, threadId, "completed");
|
||||
deleteThread(uwfForIndex.varStore, threadId);
|
||||
|
||||
addHistoryEntry(uwfForIndex.varStore, {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
|
||||
const result = await cmdThreadShow(storageRoot, threadId);
|
||||
|
||||
|
||||
@@ -160,10 +160,8 @@ describe("suspend step CAS chain and threads.yaml metadata", () => {
|
||||
const threadEntry = getThread(uwf.varStore, threadId);
|
||||
expect(threadEntry).toEqual({
|
||||
head: stepHash,
|
||||
status: "suspended",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: "Please clarify: Which API?",
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
const showResult = await cmdThreadShow(tmpDir, threadId);
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
THREAD_READ_DEFAULT_QUOTA,
|
||||
} from "../commands/thread.js";
|
||||
import type { UwfStore } from "../store.js";
|
||||
import { completeThread, createUwfStore, setThread } from "../store.js";
|
||||
import { addHistoryEntry, createUwfStore } from "../store.js";
|
||||
import { seedThreads } from "./thread-test-helpers.js";
|
||||
|
||||
// ── schemas used in tests ────────────────────────────────────────────────────
|
||||
@@ -745,14 +745,13 @@ describe("cmdStepList with completed threads", () => {
|
||||
const threadId = "01JTEST0000000000000000A2" as ThreadId;
|
||||
// Thread is NOT in active index (simulating completed thread)
|
||||
// But it IS in history variable store
|
||||
setThread(uwf.varStore, threadId, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: step2Hash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const result = await cmdStepList(tmpDir, threadId);
|
||||
|
||||
@@ -873,15 +872,14 @@ describe("cmdStepShow with completed threads", () => {
|
||||
|
||||
const threadId = "01JTEST0000000000000000B2" as ThreadId;
|
||||
// Thread is NOT in active index
|
||||
// But it IS in the unified store with completed status
|
||||
setThread(uwf.varStore, threadId, {
|
||||
// But it IS in history variable store
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: stepHash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const result = await cmdStepShow(tmpDir, stepHash);
|
||||
|
||||
@@ -936,15 +934,15 @@ describe("cmdThreadRead with completed threads", () => {
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000000C1" as ThreadId;
|
||||
// Thread is in store with completed status
|
||||
setThread(uwf.varStore, threadId, {
|
||||
// Thread is NOT in active index
|
||||
// But it IS in history variable store
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: stepHash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const markdown = await cmdThreadRead(tmpDir, threadId, THREAD_READ_DEFAULT_QUOTA, null, false);
|
||||
|
||||
@@ -1000,14 +998,13 @@ describe("cmdThreadRead with completed threads", () => {
|
||||
});
|
||||
|
||||
const threadId = "01JTEST0000000000000000C2" as ThreadId;
|
||||
setThread(uwf.varStore, threadId, {
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow: workflowHash,
|
||||
head: step3Hash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
completedAt: Date.now(),
|
||||
reason: null,
|
||||
});
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
|
||||
const markdown = await cmdThreadRead(
|
||||
tmpDir,
|
||||
|
||||
@@ -6,7 +6,7 @@ import type {
|
||||
StepNodePayload,
|
||||
ThreadId,
|
||||
} from "@united-workforce/protocol";
|
||||
import { createUwfStore, getThread, type UwfStore } from "../store.js";
|
||||
import { createUwfStore, findHistoryEntry, getThread, type UwfStore } from "../store.js";
|
||||
|
||||
type ChainState = {
|
||||
startHash: CasRef;
|
||||
@@ -207,6 +207,10 @@ async function resolveHeadHash(storageRoot: string, threadId: ThreadId): Promise
|
||||
if (entry !== null) {
|
||||
return entry.head;
|
||||
}
|
||||
const hist = findHistoryEntry(uwf.varStore, threadId);
|
||||
if (hist !== null) {
|
||||
return hist.head;
|
||||
}
|
||||
fail(`thread not found: ${threadId}`);
|
||||
}
|
||||
|
||||
|
||||
@@ -114,10 +114,8 @@ export async function cmdStepFork(
|
||||
const newThreadId = generateUlid(Date.now()) as ThreadId;
|
||||
setThread(uwf.varStore, newThreadId, {
|
||||
head: stepHash,
|
||||
status: "idle",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: null,
|
||||
});
|
||||
|
||||
return {
|
||||
|
||||
+108
-113
@@ -38,14 +38,17 @@ import { createMarker, deleteMarker, isThreadRunning } from "../background/index
|
||||
import { createIncludeTag } from "../include.js";
|
||||
import { evaluate, isSuspendResult } from "../moderator/index.js";
|
||||
import {
|
||||
completeThread,
|
||||
addHistoryEntry,
|
||||
createUwfStore,
|
||||
deleteThread,
|
||||
findHistoryEntry,
|
||||
getThread,
|
||||
loadActiveThreads,
|
||||
loadHistoryThreads,
|
||||
loadAllHistory,
|
||||
loadAllThreads,
|
||||
loadWorkflowRegistry,
|
||||
resolveWorkflowHash,
|
||||
setThread,
|
||||
type ThreadHistoryLine,
|
||||
type UwfStore,
|
||||
} from "../store.js";
|
||||
import { checkWorkflowFilenameConsistency, isCasRef, parseWorkflowPayload } from "../validate.js";
|
||||
@@ -482,55 +485,61 @@ export async function cmdThreadShow(
|
||||
): Promise<ThreadShowOutput> {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const entry = getThread(uwf.varStore, threadId);
|
||||
if (entry === null) {
|
||||
fail(`thread not found: ${threadId}`);
|
||||
}
|
||||
if (entry !== null) {
|
||||
const activeHead = entry.head;
|
||||
const workflow = resolveWorkflowFromHead(uwf, activeHead);
|
||||
if (workflow === null) {
|
||||
fail(`failed to resolve workflow from head: ${activeHead}`);
|
||||
}
|
||||
|
||||
const activeHead = entry.head;
|
||||
const workflow = resolveWorkflowFromHead(uwf, activeHead);
|
||||
if (workflow === null) {
|
||||
fail(`failed to resolve workflow from head: ${activeHead}`);
|
||||
}
|
||||
const status = await resolveActiveThreadStatus(
|
||||
storageRoot,
|
||||
threadId,
|
||||
uwf,
|
||||
activeHead,
|
||||
workflow,
|
||||
);
|
||||
const currentRole = resolveCurrentRole(uwf, activeHead, workflow);
|
||||
const suspendFields = resolveSuspendFieldsForShow(entry, status, uwf, activeHead, workflow);
|
||||
|
||||
const hint =
|
||||
status === "suspended"
|
||||
? `Thread is suspended. Resume with: uwf thread resume ${threadId}`
|
||||
: null;
|
||||
|
||||
// Determine if this is a completed/cancelled thread
|
||||
if (entry.status === "completed" || entry.status === "cancelled") {
|
||||
const hint = null;
|
||||
return {
|
||||
workflow,
|
||||
thread: threadId,
|
||||
head: activeHead,
|
||||
status: entry.status,
|
||||
currentRole: null,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
done: true,
|
||||
status,
|
||||
currentRole,
|
||||
suspendedRole: suspendFields.suspendedRole,
|
||||
suspendMessage: suspendFields.suspendMessage,
|
||||
done: false,
|
||||
background: null,
|
||||
hint,
|
||||
};
|
||||
}
|
||||
|
||||
// Active thread
|
||||
const status = await resolveActiveThreadStatus(storageRoot, threadId, uwf, activeHead, workflow);
|
||||
const currentRole = resolveCurrentRole(uwf, activeHead, workflow);
|
||||
const suspendFields = resolveSuspendFieldsForShow(entry, status, uwf, activeHead, workflow);
|
||||
const hist = findHistoryEntry(uwf.varStore, threadId);
|
||||
if (hist !== null) {
|
||||
const status: ThreadStatus = hist.reason === "cancelled" ? "cancelled" : "completed";
|
||||
|
||||
const hint =
|
||||
status === "suspended"
|
||||
? `Thread is suspended. Resume with: uwf thread resume ${threadId}`
|
||||
: null;
|
||||
return {
|
||||
workflow: hist.workflow,
|
||||
thread: threadId,
|
||||
head: hist.head,
|
||||
status,
|
||||
currentRole: null,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
done: true,
|
||||
background: null,
|
||||
hint: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
workflow,
|
||||
thread: threadId,
|
||||
head: activeHead,
|
||||
status,
|
||||
currentRole,
|
||||
suspendedRole: suspendFields.suspendedRole,
|
||||
suspendMessage: suspendFields.suspendMessage,
|
||||
done: false,
|
||||
background: null,
|
||||
hint,
|
||||
};
|
||||
fail(`thread not found: ${threadId}`);
|
||||
}
|
||||
|
||||
export type ThreadListItemWithStatus = ThreadListItem & {
|
||||
@@ -585,20 +594,19 @@ async function collectActiveThreads(
|
||||
}
|
||||
|
||||
function collectCompletedThreads(
|
||||
uwf: UwfStore,
|
||||
varStore: VarStore,
|
||||
activeIds: Set<ThreadId>,
|
||||
): ThreadListItemWithStatus[] {
|
||||
const items: ThreadListItemWithStatus[] = [];
|
||||
const history = loadHistoryThreads(uwf.varStore);
|
||||
const history = loadAllHistory(varStore);
|
||||
const seen = new Set<ThreadId>(); // Deduplication (issue #470)
|
||||
for (const [threadId, entry] of Object.entries(history)) {
|
||||
if (!activeIds.has(threadId as ThreadId) && !seen.has(threadId as ThreadId)) {
|
||||
seen.add(threadId as ThreadId);
|
||||
const status = entry.status;
|
||||
const workflow = resolveWorkflowFromHead(uwf, entry.head);
|
||||
for (const entry of history) {
|
||||
if (!activeIds.has(entry.thread) && !seen.has(entry.thread)) {
|
||||
seen.add(entry.thread);
|
||||
const status = entry.reason === "cancelled" ? "cancelled" : "completed";
|
||||
items.push({
|
||||
thread: threadId as ThreadId,
|
||||
workflow: workflow ?? "",
|
||||
thread: entry.thread,
|
||||
workflow: entry.workflow,
|
||||
head: entry.head,
|
||||
status,
|
||||
currentRole: null,
|
||||
@@ -651,7 +659,7 @@ export async function cmdThreadList(
|
||||
take: number | null,
|
||||
): Promise<ThreadListItemWithStatus[]> {
|
||||
const uwf = await createUwfStore(storageRoot);
|
||||
const index = loadActiveThreads(uwf.varStore);
|
||||
const index = loadAllThreads(uwf.varStore);
|
||||
|
||||
// Collect active threads
|
||||
let items = await collectActiveThreads(storageRoot, uwf, index);
|
||||
@@ -663,7 +671,7 @@ export async function cmdThreadList(
|
||||
statusFilter.includes("cancelled");
|
||||
if (includeCompleted) {
|
||||
const activeIds = new Set(items.map((i) => i.thread));
|
||||
const completedItems = collectCompletedThreads(uwf, activeIds);
|
||||
const completedItems = collectCompletedThreads(uwf.varStore, activeIds);
|
||||
items = items.concat(completedItems);
|
||||
}
|
||||
|
||||
@@ -1027,11 +1035,17 @@ function spawnAgent(
|
||||
return obj as unknown as AdapterOutput;
|
||||
}
|
||||
|
||||
function archiveThread(uwf: UwfStore, threadId: ThreadId, _workflow: CasRef, _head: CasRef): void {
|
||||
completeThread(uwf.varStore, threadId, "completed");
|
||||
function archiveThread(uwf: UwfStore, threadId: ThreadId, workflow: CasRef, head: CasRef): void {
|
||||
deleteThread(uwf.varStore, threadId);
|
||||
addHistoryEntry(uwf.varStore, {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "completed",
|
||||
});
|
||||
}
|
||||
|
||||
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: orchestration function with inherent branching
|
||||
export async function cmdThreadResume(
|
||||
storageRoot: string,
|
||||
threadId: ThreadId,
|
||||
@@ -1053,78 +1067,40 @@ export async function cmdThreadResume(
|
||||
const chain = walkChain(uwf, headHash);
|
||||
const workflowHash = chain.start.workflow;
|
||||
|
||||
// Check entry.status first for completed/cancelled (like in cmdThreadShow)
|
||||
let status: ThreadStatus;
|
||||
if (entry.status === "completed" || entry.status === "cancelled") {
|
||||
status = entry.status;
|
||||
} else {
|
||||
status = await resolveActiveThreadStatus(storageRoot, threadId, uwf, headHash, workflowHash);
|
||||
const status = await resolveActiveThreadStatus(
|
||||
storageRoot,
|
||||
threadId,
|
||||
uwf,
|
||||
headHash,
|
||||
workflowHash,
|
||||
);
|
||||
if (status !== "suspended") {
|
||||
fail(`thread is not suspended: ${threadId} (status: ${status})`);
|
||||
}
|
||||
|
||||
if (status !== "suspended" && status !== "completed") {
|
||||
fail(`thread cannot be resumed: ${threadId} (status: ${status})`);
|
||||
const suspendFields = resolveSuspendFieldsForShow(entry, status, uwf, headHash, workflowHash);
|
||||
if (suspendFields.suspendedRole === null) {
|
||||
fail(`thread is suspended but suspendedRole is missing: ${threadId}`);
|
||||
}
|
||||
if (suspendFields.suspendMessage === null) {
|
||||
fail(`thread is suspended but suspendMessage is missing: ${threadId}`);
|
||||
}
|
||||
|
||||
const resumePrompt = buildResumePrompt(suspendFields.suspendMessage, supplement);
|
||||
const plog = createProcessLogger({
|
||||
storageRoot,
|
||||
context: { thread: threadId, workflow: workflowHash },
|
||||
});
|
||||
|
||||
if (status === "suspended") {
|
||||
const suspendFields = resolveSuspendFieldsForShow(entry, status, uwf, headHash, workflowHash);
|
||||
if (suspendFields.suspendedRole === null) {
|
||||
fail(`thread is suspended but suspendedRole is missing: ${threadId}`);
|
||||
}
|
||||
if (suspendFields.suspendMessage === null) {
|
||||
fail(`thread is suspended but suspendMessage is missing: ${threadId}`);
|
||||
}
|
||||
|
||||
const resumePrompt = buildResumePrompt(suspendFields.suspendMessage, supplement);
|
||||
|
||||
plog.log(
|
||||
PL_THREAD_RESUME,
|
||||
`resume role=${suspendFields.suspendedRole} supplement=${supplement !== null}`,
|
||||
null,
|
||||
);
|
||||
|
||||
return cmdThreadStepOnce(storageRoot, threadId, agentOverride, plog, {
|
||||
role: suspendFields.suspendedRole,
|
||||
prompt: resumePrompt,
|
||||
});
|
||||
}
|
||||
|
||||
// status === "completed"
|
||||
const workflow = loadWorkflowPayload(uwf, workflowHash);
|
||||
const startResult = evaluate(workflow.graph, START_ROLE, {});
|
||||
if (!startResult.ok) {
|
||||
fail(`failed to evaluate $START: ${startResult.error.message}`);
|
||||
}
|
||||
if (isSuspendResult(startResult.value)) {
|
||||
fail("workflow cannot start with $SUSPEND");
|
||||
}
|
||||
if (startResult.value.role === END_ROLE) {
|
||||
fail("workflow cannot start with $END");
|
||||
}
|
||||
|
||||
const startRole = startResult.value.role;
|
||||
const completedPromptPrefix = "Previous run completed. Resuming with additional context.";
|
||||
const completedResumePrompt =
|
||||
supplement !== null && supplement !== ""
|
||||
? `${completedPromptPrefix}\n\n${supplement}`
|
||||
: completedPromptPrefix;
|
||||
|
||||
const updatedEntry = { ...entry, status: "idle" as const, completedAt: null };
|
||||
setThread(uwf.varStore, threadId, updatedEntry);
|
||||
|
||||
plog.log(
|
||||
PL_THREAD_RESUME,
|
||||
`resume completed role=${startRole} supplement=${supplement !== null}`,
|
||||
`resume role=${suspendFields.suspendedRole} supplement=${supplement !== null}`,
|
||||
null,
|
||||
);
|
||||
|
||||
return cmdThreadStepOnce(storageRoot, threadId, agentOverride, plog, {
|
||||
role: startRole,
|
||||
prompt: completedResumePrompt,
|
||||
role: suspendFields.suspendedRole,
|
||||
prompt: resumePrompt,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1273,7 +1249,7 @@ function resolveResumeStepTarget(
|
||||
}
|
||||
|
||||
async function resolveModeratorStepTarget(
|
||||
_storageRoot: string,
|
||||
storageRoot: string,
|
||||
threadId: ThreadId,
|
||||
entry: ThreadIndexEntry,
|
||||
headHash: CasRef,
|
||||
@@ -1342,7 +1318,7 @@ async function resolveModeratorStepTarget(
|
||||
}
|
||||
|
||||
async function finalizeAgentStep(
|
||||
_storageRoot: string,
|
||||
storageRoot: string,
|
||||
threadId: ThreadId,
|
||||
workflowHash: CasRef,
|
||||
workflow: WorkflowPayload,
|
||||
@@ -1474,6 +1450,10 @@ async function resolveHeadHash(storageRoot: string, threadId: ThreadId): Promise
|
||||
if (entry !== null) {
|
||||
return entry.head;
|
||||
}
|
||||
const hist = findHistoryEntry(uwf.varStore, threadId);
|
||||
if (hist !== null) {
|
||||
return hist.head;
|
||||
}
|
||||
fail(`thread not found: ${threadId}`);
|
||||
}
|
||||
|
||||
@@ -1553,6 +1533,7 @@ export async function cmdThreadCancel(
|
||||
if (entry === null) {
|
||||
fail(`thread not active: ${threadId}`);
|
||||
}
|
||||
const head = entry.head;
|
||||
|
||||
// Check if thread is running in background and terminate it
|
||||
const runningMarker = await isThreadRunning(storageRoot, threadId);
|
||||
@@ -1565,7 +1546,21 @@ export async function cmdThreadCancel(
|
||||
await deleteMarker(storageRoot, threadId);
|
||||
}
|
||||
|
||||
completeThread(uwf.varStore, threadId, "cancelled");
|
||||
const workflow = resolveWorkflowFromHead(uwf, head);
|
||||
if (workflow === null) {
|
||||
fail(`failed to resolve workflow from head: ${head}`);
|
||||
}
|
||||
|
||||
deleteThread(uwf.varStore, threadId);
|
||||
|
||||
const historyEntry: ThreadHistoryLine = {
|
||||
thread: threadId,
|
||||
workflow,
|
||||
head,
|
||||
completedAt: Date.now(),
|
||||
reason: "cancelled",
|
||||
};
|
||||
addHistoryEntry(uwf.varStore, historyEntry);
|
||||
|
||||
return { thread: threadId, cancelled: true };
|
||||
}
|
||||
|
||||
+56
-94
@@ -6,7 +6,13 @@ import { join } from "node:path";
|
||||
|
||||
import { bootstrap, type Hash, type Store, type VarStore } from "@ocas/core";
|
||||
import { createFsStore, createSqliteVarStore } from "@ocas/fs";
|
||||
import type { CasRef, ThreadId, ThreadIndexEntry, ThreadsIndex } from "@united-workforce/protocol";
|
||||
import type {
|
||||
CasRef,
|
||||
ThreadId,
|
||||
ThreadIndexEntry,
|
||||
ThreadListItem,
|
||||
ThreadsIndex,
|
||||
} from "@united-workforce/protocol";
|
||||
import { parseThreadsIndex } from "@united-workforce/protocol";
|
||||
import { parse } from "yaml";
|
||||
|
||||
@@ -20,6 +26,9 @@ export const REGISTRY_VAR_PREFIX = "@uwf/registry/";
|
||||
/** Variable name prefix for active thread entries (`@uwf/thread/<thread-id>`). */
|
||||
export const THREAD_VAR_PREFIX = "@uwf/thread/";
|
||||
|
||||
/** Variable name prefix for completed/cancelled thread history (`@uwf/history/<thread-id>`). */
|
||||
export const HISTORY_VAR_PREFIX = "@uwf/history/";
|
||||
|
||||
/** A workflow entry discovered from the project-local .workflows/ directory. */
|
||||
export type ProjectWorkflowEntry = {
|
||||
/** Workflow name (from YAML `name` field, equals filename stem). */
|
||||
@@ -147,6 +156,11 @@ export function getThreadsPath(storageRoot: string): string {
|
||||
return join(storageRoot, "threads.yaml");
|
||||
}
|
||||
|
||||
export type ThreadHistoryLine = ThreadListItem & {
|
||||
completedAt: number;
|
||||
reason: "completed" | "cancelled" | null;
|
||||
};
|
||||
|
||||
export type UwfStore = {
|
||||
storageRoot: string;
|
||||
store: Store;
|
||||
@@ -165,7 +179,6 @@ export async function createUwfStore(storageRoot: string): Promise<UwfStore> {
|
||||
await migrateWorkflowRegistryIfNeeded(storageRoot, varStore);
|
||||
await migrateThreadsIndexIfNeeded(storageRoot, varStore);
|
||||
await migrateHistoryIfNeeded(storageRoot, varStore);
|
||||
migrateHistoryVarsToThreadVars(varStore);
|
||||
return { storageRoot, store, schemas, varStore };
|
||||
}
|
||||
|
||||
@@ -286,10 +299,8 @@ function threadVarName(threadId: ThreadId): string {
|
||||
function entryFromVariable(v: { value: string; tags: Record<string, string> }): ThreadIndexEntry {
|
||||
return {
|
||||
head: v.value as CasRef,
|
||||
status: (v.tags.status ?? "idle") as ThreadIndexEntry["status"],
|
||||
suspendedRole: v.tags.suspendedRole ?? null,
|
||||
suspendMessage: v.tags.suspendMessage ?? null,
|
||||
completedAt: v.tags.completedAt !== undefined ? Number(v.tags.completedAt) : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -320,74 +331,21 @@ export function setThread(varStore: VarStore, threadId: ThreadId, entry: ThreadI
|
||||
// Head CAS nodes may use different schemas (StartNode vs StepNode) — clear all variants first.
|
||||
varStore.remove(name);
|
||||
const tags: Record<string, string> = {};
|
||||
if (entry.status !== "idle") {
|
||||
tags.status = entry.status;
|
||||
}
|
||||
if (entry.suspendedRole !== null) {
|
||||
tags.suspendedRole = entry.suspendedRole;
|
||||
}
|
||||
if (entry.suspendMessage !== null) {
|
||||
tags.suspendMessage = entry.suspendMessage;
|
||||
}
|
||||
if (entry.completedAt !== null) {
|
||||
tags.completedAt = String(entry.completedAt);
|
||||
}
|
||||
varStore.set(name, entry.head, { tags });
|
||||
}
|
||||
|
||||
/** Load only active threads (status not in completed/cancelled). */
|
||||
export function loadActiveThreads(varStore: VarStore): ThreadsIndex {
|
||||
const all = loadAllThreads(varStore);
|
||||
const active: ThreadsIndex = {};
|
||||
for (const [threadId, entry] of Object.entries(all)) {
|
||||
if (entry.status !== "completed" && entry.status !== "cancelled") {
|
||||
active[threadId as ThreadId] = entry;
|
||||
}
|
||||
}
|
||||
return active;
|
||||
/** Remove an active thread entry (on complete/cancel). */
|
||||
export function deleteThread(varStore: VarStore, threadId: ThreadId): void {
|
||||
varStore.remove(threadVarName(threadId));
|
||||
}
|
||||
|
||||
/** Load only completed/cancelled threads (history). */
|
||||
export function loadHistoryThreads(varStore: VarStore): ThreadsIndex {
|
||||
const all = loadAllThreads(varStore);
|
||||
const history: ThreadsIndex = {};
|
||||
for (const [threadId, entry] of Object.entries(all)) {
|
||||
if (entry.status === "completed" || entry.status === "cancelled") {
|
||||
history[threadId as ThreadId] = entry;
|
||||
}
|
||||
}
|
||||
return history;
|
||||
}
|
||||
|
||||
/** Complete a thread by marking it completed or cancelled. */
|
||||
export function completeThread(
|
||||
varStore: VarStore,
|
||||
threadId: ThreadId,
|
||||
reason: "completed" | "cancelled",
|
||||
): void {
|
||||
const entry = getThread(varStore, threadId);
|
||||
if (entry === null) {
|
||||
return;
|
||||
}
|
||||
const completed = {
|
||||
head: entry.head,
|
||||
status: reason,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: Date.now(),
|
||||
} as ThreadIndexEntry;
|
||||
setThread(varStore, threadId, completed);
|
||||
}
|
||||
|
||||
type LegacyHistoryEntry = {
|
||||
thread: ThreadId;
|
||||
workflow: CasRef;
|
||||
head: CasRef;
|
||||
completedAt: number;
|
||||
reason: "completed" | "cancelled" | null;
|
||||
};
|
||||
|
||||
function parseLegacyHistoryJsonlLine(trimmed: string): LegacyHistoryEntry | null {
|
||||
function parseHistoryJsonlLine(trimmed: string): ThreadHistoryLine | null {
|
||||
let raw: unknown;
|
||||
try {
|
||||
raw = JSON.parse(trimmed) as unknown;
|
||||
@@ -421,7 +379,7 @@ function parseLegacyHistoryJsonlLine(trimmed: string): LegacyHistoryEntry | null
|
||||
return null;
|
||||
}
|
||||
|
||||
/** One-time migration: `~/.uwf/history.jsonl` → `@uwf/thread/*` variables with status tags. */
|
||||
/** One-time migration: `~/.uwf/history.jsonl` → `@uwf/history/*` variables. */
|
||||
export async function migrateHistoryIfNeeded(
|
||||
storageRoot: string,
|
||||
varStore: VarStore,
|
||||
@@ -437,43 +395,47 @@ export async function migrateHistoryIfNeeded(
|
||||
if (trimmed === "") {
|
||||
continue;
|
||||
}
|
||||
const entry = parseLegacyHistoryJsonlLine(trimmed);
|
||||
const entry = parseHistoryJsonlLine(trimmed);
|
||||
if (entry !== null) {
|
||||
const status = entry.reason === "cancelled" ? "cancelled" : "completed";
|
||||
const threadEntry: ThreadIndexEntry = {
|
||||
head: entry.head,
|
||||
status: status as ThreadIndexEntry["status"],
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt: entry.completedAt,
|
||||
};
|
||||
setThread(varStore, entry.thread, threadEntry);
|
||||
addHistoryEntry(varStore, entry);
|
||||
}
|
||||
}
|
||||
|
||||
await rename(path, `${path}.migrated`);
|
||||
}
|
||||
|
||||
/** Migrate `@uwf/history/*` variables to `@uwf/thread/*` with status tags. */
|
||||
export function migrateHistoryVarsToThreadVars(varStore: VarStore): void {
|
||||
const LEGACY_HISTORY_VAR_PREFIX = "@uwf/history/";
|
||||
const vars = varStore.list({ namePrefix: LEGACY_HISTORY_VAR_PREFIX });
|
||||
|
||||
for (const v of vars) {
|
||||
const threadId = v.name.slice(LEGACY_HISTORY_VAR_PREFIX.length) as ThreadId;
|
||||
const reason = v.tags.reason;
|
||||
const status = reason === "cancelled" ? "cancelled" : "completed";
|
||||
const completedAt = Number(v.tags.completedAt ?? Date.now());
|
||||
|
||||
const threadEntry: ThreadIndexEntry = {
|
||||
head: v.value as CasRef,
|
||||
status: status as ThreadIndexEntry["status"],
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
completedAt,
|
||||
};
|
||||
|
||||
setThread(varStore, threadId, threadEntry);
|
||||
varStore.remove(v.name);
|
||||
}
|
||||
export function loadAllHistory(varStore: VarStore): ThreadHistoryLine[] {
|
||||
const vars = varStore.list({ namePrefix: HISTORY_VAR_PREFIX });
|
||||
return vars.map((v) => ({
|
||||
thread: v.name.slice(HISTORY_VAR_PREFIX.length) as ThreadId,
|
||||
workflow: v.tags.workflow ?? "",
|
||||
head: v.value as CasRef,
|
||||
completedAt: Number(v.tags.completedAt ?? "0"),
|
||||
reason: v.tags.reason === "completed" || v.tags.reason === "cancelled" ? v.tags.reason : null,
|
||||
}));
|
||||
}
|
||||
|
||||
export function findHistoryEntry(varStore: VarStore, threadId: ThreadId): ThreadHistoryLine | null {
|
||||
const vars = varStore.list({ namePrefix: `${HISTORY_VAR_PREFIX}${threadId}` });
|
||||
const v = vars.find((entry) => entry.name === `${HISTORY_VAR_PREFIX}${threadId}`);
|
||||
if (v === undefined) {
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
thread: threadId,
|
||||
workflow: v.tags.workflow ?? "",
|
||||
head: v.value as CasRef,
|
||||
completedAt: Number(v.tags.completedAt ?? "0"),
|
||||
reason: v.tags.reason === "completed" || v.tags.reason === "cancelled" ? v.tags.reason : null,
|
||||
};
|
||||
}
|
||||
|
||||
export function addHistoryEntry(varStore: VarStore, entry: ThreadHistoryLine): void {
|
||||
varStore.set(`${HISTORY_VAR_PREFIX}${entry.thread}`, entry.head, {
|
||||
tags: {
|
||||
workflow: entry.workflow,
|
||||
completedAt: String(entry.completedAt),
|
||||
reason: entry.reason ?? "completed",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -96,7 +96,6 @@ export function checkWorkflowFilenameConsistency(
|
||||
}
|
||||
|
||||
/** Validate YAML-parsed workflow document shape (outputSchema may be inline JSON Schema). */
|
||||
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: validation function with many field checks
|
||||
export function parseWorkflowPayload(raw: unknown): WorkflowPayload | null {
|
||||
if (!isRecord(raw)) {
|
||||
return null;
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import {
|
||||
createThreadIndexEntry,
|
||||
markThreadCompleted,
|
||||
markThreadSuspended,
|
||||
normalizeThreadIndexEntry,
|
||||
parseThreadsIndex,
|
||||
@@ -17,8 +16,6 @@ describe("thread-index", () => {
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -32,40 +29,6 @@ describe("thread-index", () => {
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: "Please clarify: Which API?",
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizeThreadIndexEntry preserves status and completedAt from new data", () => {
|
||||
const entry = normalizeThreadIndexEntry({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "completed",
|
||||
completedAt: 1234567890,
|
||||
});
|
||||
expect(entry).toEqual({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "completed",
|
||||
completedAt: 1234567890,
|
||||
});
|
||||
});
|
||||
|
||||
test("normalizeThreadIndexEntry defaults status=idle, completedAt=null for old data", () => {
|
||||
const entry = normalizeThreadIndexEntry({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
});
|
||||
expect(entry).toEqual({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -84,24 +47,10 @@ describe("thread-index", () => {
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: "Please clarify: Which API?",
|
||||
status: "suspended",
|
||||
});
|
||||
});
|
||||
|
||||
test("serialize completed entry as object", () => {
|
||||
const entry = markThreadCompleted(
|
||||
createThreadIndexEntry("0123456789ABC"),
|
||||
"completed",
|
||||
1234567890,
|
||||
);
|
||||
expect(serializeThreadIndexEntry(entry)).toEqual({
|
||||
head: "0123456789ABC",
|
||||
status: "completed",
|
||||
completedAt: 1234567890,
|
||||
});
|
||||
});
|
||||
|
||||
test("updateThreadHead clears suspend metadata and resets status to idle", () => {
|
||||
test("updateThreadHead clears suspend metadata", () => {
|
||||
const suspended = markThreadSuspended(
|
||||
createThreadIndexEntry("OLDHEAD0123456"),
|
||||
"worker",
|
||||
@@ -112,44 +61,6 @@ describe("thread-index", () => {
|
||||
head: "NEWHEAD01234567",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("markThreadSuspended sets status to suspended", () => {
|
||||
const entry = createThreadIndexEntry("0123456789ABC");
|
||||
const suspended = markThreadSuspended(entry, "worker", "Waiting for input");
|
||||
expect(suspended).toEqual({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: "worker",
|
||||
suspendMessage: "Waiting for input",
|
||||
status: "suspended",
|
||||
completedAt: null,
|
||||
});
|
||||
});
|
||||
|
||||
test("markThreadCompleted sets status and completedAt", () => {
|
||||
const entry = createThreadIndexEntry("0123456789ABC");
|
||||
const completed = markThreadCompleted(entry, "completed", 1234567890);
|
||||
expect(completed).toEqual({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "completed",
|
||||
completedAt: 1234567890,
|
||||
});
|
||||
});
|
||||
|
||||
test("markThreadCompleted with cancelled status", () => {
|
||||
const entry = createThreadIndexEntry("0123456789ABC");
|
||||
const cancelled = markThreadCompleted(entry, "cancelled", 9876543210);
|
||||
expect(cancelled).toEqual({
|
||||
head: "0123456789ABC",
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "cancelled",
|
||||
completedAt: 9876543210,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -160,7 +71,6 @@ describe("thread-index", () => {
|
||||
head: "HEAD00000000002",
|
||||
suspendedRole: "reviewer",
|
||||
suspendMessage: "Need input",
|
||||
status: "suspended",
|
||||
},
|
||||
};
|
||||
const parsed = parseThreadsIndex(raw);
|
||||
|
||||
@@ -5,7 +5,6 @@ export {
|
||||
} from "./schemas.js";
|
||||
export {
|
||||
createThreadIndexEntry,
|
||||
markThreadCompleted,
|
||||
markThreadSuspended,
|
||||
normalizeThreadIndexEntry,
|
||||
parseThreadsIndex,
|
||||
|
||||
@@ -15,17 +15,10 @@ export function normalizeThreadIndexEntry(raw: unknown): ThreadIndexEntry | null
|
||||
}
|
||||
const suspendedRole = rec.suspendedRole;
|
||||
const suspendMessage = rec.suspendMessage;
|
||||
const status = rec.status;
|
||||
const completedAt = rec.completedAt;
|
||||
return {
|
||||
head: head as CasRef,
|
||||
suspendedRole: typeof suspendedRole === "string" ? suspendedRole : null,
|
||||
suspendMessage: typeof suspendMessage === "string" ? suspendMessage : null,
|
||||
status:
|
||||
typeof status === "string"
|
||||
? (status as "idle" | "running" | "suspended" | "completed" | "cancelled")
|
||||
: "idle",
|
||||
completedAt: typeof completedAt === "number" ? completedAt : null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,8 +27,6 @@ export function createThreadIndexEntry(head: CasRef): ThreadIndexEntry {
|
||||
head,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -44,8 +35,6 @@ export function updateThreadHead(_entry: ThreadIndexEntry, head: CasRef): Thread
|
||||
head,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status: "idle",
|
||||
completedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -58,63 +47,21 @@ export function markThreadSuspended(
|
||||
head: entry.head,
|
||||
suspendedRole,
|
||||
suspendMessage,
|
||||
status: "suspended",
|
||||
completedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
export function markThreadCompleted(
|
||||
entry: ThreadIndexEntry,
|
||||
status: "completed" | "cancelled",
|
||||
now: number,
|
||||
): ThreadIndexEntry {
|
||||
return {
|
||||
head: entry.head,
|
||||
suspendedRole: null,
|
||||
suspendMessage: null,
|
||||
status,
|
||||
completedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
/** Serialize for variable store — compact string when not suspended. */
|
||||
export function serializeThreadIndexEntry(
|
||||
entry: ThreadIndexEntry,
|
||||
): string | Record<string, string | number> {
|
||||
// Compact string only for idle status with no suspend metadata
|
||||
if (
|
||||
entry.status === "idle" &&
|
||||
entry.suspendedRole === null &&
|
||||
entry.suspendMessage === null &&
|
||||
entry.completedAt === null
|
||||
) {
|
||||
): string | Record<string, string> {
|
||||
if (entry.suspendedRole === null || entry.suspendMessage === null) {
|
||||
return entry.head;
|
||||
}
|
||||
|
||||
// Build object representation
|
||||
const obj: Record<string, string | number> = {
|
||||
return {
|
||||
head: entry.head,
|
||||
suspendedRole: entry.suspendedRole,
|
||||
suspendMessage: entry.suspendMessage,
|
||||
};
|
||||
|
||||
// Include suspend metadata if present
|
||||
if (entry.suspendedRole !== null) {
|
||||
obj.suspendedRole = entry.suspendedRole;
|
||||
}
|
||||
if (entry.suspendMessage !== null) {
|
||||
obj.suspendMessage = entry.suspendMessage;
|
||||
}
|
||||
|
||||
// Always include status if not idle
|
||||
if (entry.status !== "idle") {
|
||||
obj.status = entry.status;
|
||||
}
|
||||
|
||||
// Include completedAt if present
|
||||
if (entry.completedAt !== null) {
|
||||
obj.completedAt = entry.completedAt;
|
||||
}
|
||||
|
||||
return obj;
|
||||
}
|
||||
|
||||
export function parseThreadsIndex(raw: unknown): ThreadsIndex {
|
||||
@@ -133,8 +80,8 @@ export function parseThreadsIndex(raw: unknown): ThreadsIndex {
|
||||
|
||||
export function serializeThreadsIndex(
|
||||
index: ThreadsIndex,
|
||||
): Record<string, string | Record<string, string | number>> {
|
||||
const out: Record<string, string | Record<string, string | number>> = {};
|
||||
): Record<string, string | Record<string, string>> {
|
||||
const out: Record<string, string | Record<string, string>> = {};
|
||||
for (const [threadId, entry] of Object.entries(index)) {
|
||||
out[threadId] = serializeThreadIndexEntry(entry);
|
||||
}
|
||||
|
||||
@@ -118,8 +118,6 @@ export type ThreadIndexEntry = {
|
||||
head: CasRef;
|
||||
suspendedRole: string | null;
|
||||
suspendMessage: string | null;
|
||||
status: ThreadStatus;
|
||||
completedAt: number | null;
|
||||
};
|
||||
|
||||
/** uwf thread steps — single step entry */
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
|
||||
import { parseArgv } from "../src/run.js";
|
||||
|
||||
describe("parseArgv", () => {
|
||||
let exitSpy: ReturnType<typeof vi.spyOn>;
|
||||
let _stderrSpy: ReturnType<typeof vi.spyOn>;
|
||||
let stderrSpy: ReturnType<typeof vi.spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
exitSpy = vi.spyOn(process, "exit").mockImplementation((() => {
|
||||
throw new Error("process.exit");
|
||||
}) as never);
|
||||
_stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation((() => true) as never);
|
||||
stderrSpy = vi.spyOn(process.stderr, "write").mockImplementation((() => true) as never);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -17,37 +17,22 @@ describe("parseArgv", () => {
|
||||
});
|
||||
|
||||
it("returns threadId, role, prompt for valid argv", () => {
|
||||
const result = parseArgv([
|
||||
"node",
|
||||
"script",
|
||||
"--thread",
|
||||
"abc123",
|
||||
"--role",
|
||||
"developer",
|
||||
"--prompt",
|
||||
"do stuff",
|
||||
]);
|
||||
const result = parseArgv(["node", "script", "--thread", "abc123", "--role", "developer", "--prompt", "do stuff"]);
|
||||
expect(result).toEqual({ threadId: "abc123", role: "developer", prompt: "do stuff" });
|
||||
});
|
||||
|
||||
it("exits when --thread is missing", () => {
|
||||
expect(() => parseArgv(["node", "script", "--role", "dev", "--prompt", "x"])).toThrow(
|
||||
"process.exit",
|
||||
);
|
||||
expect(() => parseArgv(["node", "script", "--role", "dev", "--prompt", "x"])).toThrow("process.exit");
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it("exits when --role is missing", () => {
|
||||
expect(() => parseArgv(["node", "script", "--thread", "t1", "--prompt", "x"])).toThrow(
|
||||
"process.exit",
|
||||
);
|
||||
expect(() => parseArgv(["node", "script", "--thread", "t1", "--prompt", "x"])).toThrow("process.exit");
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
|
||||
it("exits when --prompt is missing", () => {
|
||||
expect(() => parseArgv(["node", "script", "--thread", "t1", "--role", "dev"])).toThrow(
|
||||
"process.exit",
|
||||
);
|
||||
expect(() => parseArgv(["node", "script", "--thread", "t1", "--role", "dev"])).toThrow("process.exit");
|
||||
expect(exitSpy).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import { homedir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, it, expect } from "vitest";
|
||||
import {
|
||||
resolveStorageRoot,
|
||||
getDefaultStorageRoot,
|
||||
getCasDir,
|
||||
getConfigPath,
|
||||
getDefaultStorageRoot,
|
||||
getEnvPath,
|
||||
getGlobalCasDir,
|
||||
normalizeWorkflowConfig,
|
||||
resolveStorageRoot,
|
||||
} from "../src/storage.js";
|
||||
|
||||
const VALID_CONFIG = {
|
||||
@@ -79,33 +79,28 @@ describe("normalizeWorkflowConfig", () => {
|
||||
});
|
||||
|
||||
it("throws when defaultAgent missing", () => {
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, defaultAgent: undefined })).toThrow(
|
||||
"defaultAgent and defaultModel",
|
||||
);
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, defaultAgent: undefined }))
|
||||
.toThrow("defaultAgent and defaultModel");
|
||||
});
|
||||
|
||||
it("throws when defaultModel missing", () => {
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, defaultModel: 42 })).toThrow(
|
||||
"defaultAgent and defaultModel",
|
||||
);
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, defaultModel: 42 }))
|
||||
.toThrow("defaultAgent and defaultModel");
|
||||
});
|
||||
|
||||
it("throws on invalid providers entry", () => {
|
||||
expect(() =>
|
||||
normalizeWorkflowConfig({ ...VALID_CONFIG, providers: { bad: "string" } }),
|
||||
).toThrow("config.providers.bad must be a mapping");
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, providers: { bad: "string" } }))
|
||||
.toThrow("config.providers.bad must be a mapping");
|
||||
});
|
||||
|
||||
it("throws on invalid models entry", () => {
|
||||
expect(() =>
|
||||
normalizeWorkflowConfig({ ...VALID_CONFIG, models: { m: { provider: 123, name: "x" } } }),
|
||||
).toThrow("config.models.m requires provider and name");
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, models: { m: { provider: 123, name: "x" } } }))
|
||||
.toThrow("config.models.m requires provider and name");
|
||||
});
|
||||
|
||||
it("throws on invalid agents entry", () => {
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, agents: "bad" })).toThrow(
|
||||
"config.agents must be a mapping",
|
||||
);
|
||||
expect(() => normalizeWorkflowConfig({ ...VALID_CONFIG, agents: "bad" }))
|
||||
.toThrow("config.agents must be a mapping");
|
||||
});
|
||||
|
||||
it("returns null for undefined modelOverrides", () => {
|
||||
|
||||
@@ -82,10 +82,8 @@ export async function getActiveThreadEntry(
|
||||
}
|
||||
return {
|
||||
head: v.value as CasRef,
|
||||
status: (v.tags.status ?? "idle") as ThreadIndexEntry["status"],
|
||||
suspendedRole: v.tags.suspendedRole ?? null,
|
||||
suspendMessage: v.tags.suspendMessage ?? null,
|
||||
completedAt: v.tags.completedAt !== undefined ? Number(v.tags.completedAt) : null,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
CROCKFORD_BASE32_ALPHABET,
|
||||
decodeCrockfordBase32Bits,
|
||||
decodeCrockfordToUint64,
|
||||
encodeCrockfordBase32Bits,
|
||||
decodeCrockfordBase32Bits,
|
||||
encodeUint64AsCrockford,
|
||||
decodeCrockfordToUint64,
|
||||
} from "../src/base32.js";
|
||||
|
||||
describe("CROCKFORD_BASE32_ALPHABET", () => {
|
||||
@@ -105,7 +105,7 @@ describe("encodeUint64AsCrockford / decodeCrockfordToUint64", () => {
|
||||
});
|
||||
|
||||
it("roundtrips arbitrary value", () => {
|
||||
const value = 0xdead_beef_cafe_baben;
|
||||
const value = 0xDEAD_BEEF_CAFE_BABEn;
|
||||
const encoded = encodeUint64AsCrockford(value);
|
||||
const decoded = decodeCrockfordToUint64(encoded);
|
||||
expect(decoded).toEqual({ ok: true, value });
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { assertValidLogTag } from "../src/process-logger/log-tag.js";
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { assertValidLogTag } from '../src/process-logger/log-tag.js';
|
||||
|
||||
describe("assertValidLogTag", () => {
|
||||
it("accepts valid 8-char Crockford Base32 tags", () => {
|
||||
expect(() => assertValidLogTag("0123ABCD")).not.toThrow();
|
||||
expect(() => assertValidLogTag("VWXYZ789")).not.toThrow();
|
||||
expect(() => assertValidLogTag("00000000")).not.toThrow();
|
||||
expect(() => assertValidLogTag("ZZZZZZZZ")).not.toThrow();
|
||||
describe('assertValidLogTag', () => {
|
||||
it('accepts valid 8-char Crockford Base32 tags', () => {
|
||||
expect(() => assertValidLogTag('0123ABCD')).not.toThrow();
|
||||
expect(() => assertValidLogTag('VWXYZ789')).not.toThrow();
|
||||
expect(() => assertValidLogTag('00000000')).not.toThrow();
|
||||
expect(() => assertValidLogTag('ZZZZZZZZ')).not.toThrow();
|
||||
});
|
||||
|
||||
it("accepts lowercase (converted via toUpperCase)", () => {
|
||||
expect(() => assertValidLogTag("abcdefgh")).not.toThrow();
|
||||
expect(() => assertValidLogTag("0a1b2c3d")).not.toThrow();
|
||||
it('accepts lowercase (converted via toUpperCase)', () => {
|
||||
expect(() => assertValidLogTag('abcdefgh')).not.toThrow();
|
||||
expect(() => assertValidLogTag('0a1b2c3d')).not.toThrow();
|
||||
});
|
||||
|
||||
it("throws on too short", () => {
|
||||
expect(() => assertValidLogTag("1234567")).toThrow();
|
||||
expect(() => assertValidLogTag("")).toThrow();
|
||||
it('throws on too short', () => {
|
||||
expect(() => assertValidLogTag('1234567')).toThrow();
|
||||
expect(() => assertValidLogTag('')).toThrow();
|
||||
});
|
||||
|
||||
it("throws on too long", () => {
|
||||
expect(() => assertValidLogTag("123456789")).toThrow();
|
||||
it('throws on too long', () => {
|
||||
expect(() => assertValidLogTag('123456789')).toThrow();
|
||||
});
|
||||
|
||||
it("throws on invalid chars I, L, O, U", () => {
|
||||
expect(() => assertValidLogTag("IIIIIIII")).toThrow();
|
||||
expect(() => assertValidLogTag("LLLLLLLL")).toThrow();
|
||||
expect(() => assertValidLogTag("OOOOOOOO")).toThrow();
|
||||
expect(() => assertValidLogTag("UUUUUUUU")).toThrow();
|
||||
it('throws on invalid chars I, L, O, U', () => {
|
||||
expect(() => assertValidLogTag('IIIIIIII')).toThrow();
|
||||
expect(() => assertValidLogTag('LLLLLLLL')).toThrow();
|
||||
expect(() => assertValidLogTag('OOOOOOOO')).toThrow();
|
||||
expect(() => assertValidLogTag('UUUUUUUU')).toThrow();
|
||||
});
|
||||
|
||||
it("throws on special characters", () => {
|
||||
expect(() => assertValidLogTag("1234567!")).toThrow();
|
||||
expect(() => assertValidLogTag("ABCD-EFG")).toThrow();
|
||||
expect(() => assertValidLogTag("ABCD EFG")).toThrow();
|
||||
it('throws on special characters', () => {
|
||||
expect(() => assertValidLogTag('1234567!')).toThrow();
|
||||
expect(() => assertValidLogTag('ABCD-EFG')).toThrow();
|
||||
expect(() => assertValidLogTag('ABCD EFG')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,40 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { mergeRefsWithContentHash, normalizeRefsField } from "../src/refs-field.js";
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { mergeRefsWithContentHash, normalizeRefsField } from '../src/refs-field.js';
|
||||
|
||||
describe("mergeRefsWithContentHash", () => {
|
||||
it("appends a new content hash", () => {
|
||||
expect(mergeRefsWithContentHash(["a", "b"], "c")).toEqual(["a", "b", "c"]);
|
||||
describe('mergeRefsWithContentHash', () => {
|
||||
it('appends a new content hash', () => {
|
||||
expect(mergeRefsWithContentHash(['a', 'b'], 'c')).toEqual(['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
it("skips duplicate content hash", () => {
|
||||
expect(mergeRefsWithContentHash(["a", "b"], "b")).toEqual(["a", "b"]);
|
||||
it('skips duplicate content hash', () => {
|
||||
expect(mergeRefsWithContentHash(['a', 'b'], 'b')).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it("preserves order", () => {
|
||||
expect(mergeRefsWithContentHash(["x", "y"], "z")).toEqual(["x", "y", "z"]);
|
||||
it('preserves order', () => {
|
||||
expect(mergeRefsWithContentHash(['x', 'y'], 'z')).toEqual(['x', 'y', 'z']);
|
||||
});
|
||||
|
||||
it("handles empty refs", () => {
|
||||
expect(mergeRefsWithContentHash([], "a")).toEqual(["a"]);
|
||||
it('handles empty refs', () => {
|
||||
expect(mergeRefsWithContentHash([], 'a')).toEqual(['a']);
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeRefsField", () => {
|
||||
it("returns empty array for non-array", () => {
|
||||
describe('normalizeRefsField', () => {
|
||||
it('returns empty array for non-array', () => {
|
||||
expect(normalizeRefsField(null)).toEqual([]);
|
||||
expect(normalizeRefsField(undefined)).toEqual([]);
|
||||
expect(normalizeRefsField(42)).toEqual([]);
|
||||
});
|
||||
|
||||
it("passes through string array", () => {
|
||||
expect(normalizeRefsField(["a", "b"])).toEqual(["a", "b"]);
|
||||
it('passes through string array', () => {
|
||||
expect(normalizeRefsField(['a', 'b'])).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it("filters non-strings from mixed array", () => {
|
||||
expect(normalizeRefsField(["a", 1, "b", null])).toEqual(["a", "b"]);
|
||||
it('filters non-strings from mixed array', () => {
|
||||
expect(normalizeRefsField(['a', 1, 'b', null])).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it("handles empty array", () => {
|
||||
it('handles empty array', () => {
|
||||
expect(normalizeRefsField([])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,36 +1,36 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { err, ok } from "../src/result.js";
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ok, err } from '../src/result.js';
|
||||
|
||||
describe("result", () => {
|
||||
describe("ok", () => {
|
||||
it("wraps a value", () => {
|
||||
describe('result', () => {
|
||||
describe('ok', () => {
|
||||
it('wraps a value', () => {
|
||||
const r = ok(42);
|
||||
expect(r).toEqual({ ok: true, value: 42 });
|
||||
});
|
||||
|
||||
it("wraps a string value", () => {
|
||||
const r = ok("hello");
|
||||
it('wraps a string value', () => {
|
||||
const r = ok('hello');
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value).toBe("hello");
|
||||
if (r.ok) expect(r.value).toBe('hello');
|
||||
});
|
||||
});
|
||||
|
||||
describe("err", () => {
|
||||
it("wraps an error", () => {
|
||||
const r = err("fail");
|
||||
expect(r).toEqual({ ok: false, error: "fail" });
|
||||
describe('err', () => {
|
||||
it('wraps an error', () => {
|
||||
const r = err('fail');
|
||||
expect(r).toEqual({ ok: false, error: 'fail' });
|
||||
});
|
||||
|
||||
it("wraps an Error object", () => {
|
||||
const e = new Error("boom");
|
||||
it('wraps an Error object', () => {
|
||||
const e = new Error('boom');
|
||||
const r = err(e);
|
||||
expect(r.ok).toBe(false);
|
||||
if (!r.ok) expect(r.error).toBe(e);
|
||||
});
|
||||
});
|
||||
|
||||
describe("type narrowing", () => {
|
||||
it("narrows ok result", () => {
|
||||
describe('type narrowing', () => {
|
||||
it('narrows ok result', () => {
|
||||
const r = ok(10) as ReturnType<typeof ok<number>> | ReturnType<typeof err<string>>;
|
||||
if (r.ok) {
|
||||
expect(r.value).toBe(10);
|
||||
@@ -39,10 +39,10 @@ describe("result", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("narrows err result", () => {
|
||||
const r = err("bad") as ReturnType<typeof ok<number>> | ReturnType<typeof err<string>>;
|
||||
it('narrows err result', () => {
|
||||
const r = err('bad') as ReturnType<typeof ok<number>> | ReturnType<typeof err<string>>;
|
||||
if (!r.ok) {
|
||||
expect(r.error).toBe("bad");
|
||||
expect(r.error).toBe('bad');
|
||||
} else {
|
||||
expect.unreachable();
|
||||
}
|
||||
|
||||
@@ -1,29 +1,25 @@
|
||||
import { homedir } from "node:os";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
getDefaultStorageRoot,
|
||||
getDefaultWorkflowStorageRoot,
|
||||
getGlobalCasDir,
|
||||
} from "../src/storage-root.js";
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { homedir } from 'node:os';
|
||||
import { getDefaultStorageRoot, getDefaultWorkflowStorageRoot, getGlobalCasDir } from '../src/storage-root.js';
|
||||
|
||||
describe("getDefaultStorageRoot", () => {
|
||||
it("returns homedir + /.uwf", () => {
|
||||
expect(getDefaultStorageRoot()).toBe(`${homedir()}/.uwf`);
|
||||
describe('getDefaultStorageRoot', () => {
|
||||
it('returns homedir + /.uwf', () => {
|
||||
expect(getDefaultStorageRoot()).toBe(homedir() + '/.uwf');
|
||||
});
|
||||
});
|
||||
|
||||
describe("getDefaultWorkflowStorageRoot", () => {
|
||||
it("returns same as getDefaultStorageRoot (deprecated alias)", () => {
|
||||
describe('getDefaultWorkflowStorageRoot', () => {
|
||||
it('returns same as getDefaultStorageRoot (deprecated alias)', () => {
|
||||
expect(getDefaultWorkflowStorageRoot()).toBe(getDefaultStorageRoot());
|
||||
});
|
||||
});
|
||||
|
||||
describe("getGlobalCasDir", () => {
|
||||
it("appends /cas to given storage root", () => {
|
||||
expect(getGlobalCasDir("/tmp/test")).toBe("/tmp/test/cas");
|
||||
describe('getGlobalCasDir', () => {
|
||||
it('appends /cas to given storage root', () => {
|
||||
expect(getGlobalCasDir('/tmp/test')).toBe('/tmp/test/cas');
|
||||
});
|
||||
|
||||
it("falls back to default when undefined", () => {
|
||||
expect(getGlobalCasDir(undefined)).toBe(`${homedir()}/.uwf/cas`);
|
||||
it('falls back to default when undefined', () => {
|
||||
expect(getGlobalCasDir(undefined)).toBe(homedir() + '/.uwf/cas');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user