feat: Phase 4 — CAS-based fork + mark-and-sweep GC

- Rewrite fork to create StateNode pointing to fork point (zero duplication)
- Rewrite GC as mark-and-sweep: roots from threads.json + history, findReachableHashes via refs[]
- Remove .data.jsonl code paths
- Fix all 7 previously failing CLI tests
- New: gc-mark-sweep.test.ts verifying shared nodes survive GC
- All 166 tests pass

Refs #155, closes #159

小橘 <xiaoju@shazhou.work>
This commit is contained in:
2026-05-09 08:12:49 +00:00
parent 26cf51366f
commit f3aedf8d6c
22 changed files with 1724 additions and 1073 deletions
@@ -1,12 +1,16 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { createCasStore, getContentMerklePayload } from "@uncaged/workflow-cas"; import { createCasStore, getContentMerklePayload } from "@uncaged/workflow-cas";
import { FORK_BRANCH_ROLE, walkStateFramesNewestFirst } from "@uncaged/workflow-execute";
import { END } from "@uncaged/workflow-runtime";
import { getGlobalCasDir } from "@uncaged/workflow-util"; import { getGlobalCasDir } from "@uncaged/workflow-util";
import { cmdFork, cmdRun } from "../src/commands/thread/index.js"; import { cmdFork, cmdRun } from "../src/commands/thread/index.js";
import { cmdAdd } from "../src/commands/workflow/index.js"; import { cmdAdd } from "../src/commands/workflow/index.js";
import { pathExists } from "../src/fs-utils.js"; import { pathExists } from "../src/fs-utils.js";
import { resolveThreadRecord } from "../src/thread-scan.js";
import { addCliArgs } from "./bundle-fixture.js"; import { addCliArgs } from "./bundle-fixture.js";
import { ensureTestWorkflowRegistryConfig } from "./workflow-registry-fixture.js"; import { ensureTestWorkflowRegistryConfig } from "./workflow-registry-fixture.js";
@@ -41,27 +45,6 @@ export const run = async function* (input, options) {
}; };
`; `;
async function countDataJsonlLines(dataPath: string): Promise<number> {
try {
const text = await readFile(dataPath, "utf8");
return text
.trim()
.split("\n")
.filter((l) => l !== "").length;
} catch {
return 0;
}
}
async function waitUntilMinDataLines(dataPath: string, minLines: number): Promise<void> {
for (let attempt = 0; attempt < 120; attempt++) {
if ((await countDataJsonlLines(dataPath)) >= minLines) {
return;
}
await new Promise((r) => setTimeout(r, 25));
}
}
async function waitUntilRunningAbsent(runningPath: string): Promise<void> { async function waitUntilRunningAbsent(runningPath: string): Promise<void> {
for (let attempt = 0; attempt < 120; attempt++) { for (let attempt = 0; attempt < 120; attempt++) {
if (!(await pathExists(runningPath))) { if (!(await pathExists(runningPath))) {
@@ -71,6 +54,41 @@ async function waitUntilRunningAbsent(runningPath: string): Promise<void> {
} }
} }
async function waitUntilThreadCompletes(storageRoot: string, threadId: string): Promise<void> {
for (let attempt = 0; attempt < 120; attempt++) {
const row = await resolveThreadRecord(storageRoot, threadId);
if (row?.source === "history") {
return;
}
await new Promise((r) => setTimeout(r, 25));
}
}
async function listMeaningfulRoleContents(
storageRoot: string,
threadId: string,
): Promise<Array<{ role: string; content: string }>> {
const row = await resolveThreadRecord(storageRoot, threadId);
if (row === null) {
return [];
}
const cas = createCasStore(getGlobalCasDir(storageRoot));
const frames = await walkStateFramesNewestFirst(cas, row.head);
const chronological = [...frames].reverse();
const out: Array<{ role: string; content: string }> = [];
for (const fr of chronological) {
if (fr.payload.role === END || fr.payload.role === FORK_BRANCH_ROLE) {
continue;
}
const content = await getContentMerklePayload(cas, fr.payload.content);
out.push({
role: fr.payload.role,
content: content ?? "",
});
}
return out;
}
describe("cli fork", () => { describe("cli fork", () => {
let prevEnv: string | undefined; let prevEnv: string | undefined;
let storageRoot: string; let storageRoot: string;
@@ -110,10 +128,12 @@ describe("cli fork", () => {
return; return;
} }
const sourceId = ran.value.threadId; const sourceId = ran.value.threadId;
const sourceData = join(storageRoot, "logs", hash, `${sourceId}.data.jsonl`);
const sourceRunning = join(storageRoot, "logs", hash, `${sourceId}.running`); const sourceRunning = join(storageRoot, "logs", hash, `${sourceId}.running`);
await waitUntilRunningAbsent(sourceRunning); await waitUntilRunningAbsent(sourceRunning);
await waitUntilMinDataLines(sourceData, 5); await waitUntilThreadCompletes(storageRoot, sourceId);
const histBefore = await resolveThreadRecord(storageRoot, sourceId);
expect(histBefore?.source).toBe("history");
const forked = await cmdFork(storageRoot, sourceId, "planner"); const forked = await cmdFork(storageRoot, sourceId, "planner");
expect(forked.ok).toBe(true); expect(forked.ok).toBe(true);
@@ -121,25 +141,18 @@ describe("cli fork", () => {
return; return;
} }
const newId = forked.value.threadId; const newId = forked.value.threadId;
const newData = join(storageRoot, "logs", hash, `${newId}.data.jsonl`);
const newRunning = join(storageRoot, "logs", hash, `${newId}.running`); const newRunning = join(storageRoot, "logs", hash, `${newId}.running`);
await waitUntilRunningAbsent(newRunning); await waitUntilRunningAbsent(newRunning);
await waitUntilMinDataLines(newData, 5); await waitUntilThreadCompletes(storageRoot, newId);
const text = await readFile(newData, "utf8"); const forkHist = await resolveThreadRecord(storageRoot, newId);
const lines = text expect(forkHist?.source).toBe("history");
.trim() expect(forkHist?.start).toBe(histBefore?.start);
.split("\n")
.filter((l) => l !== "");
expect(lines.length).toBe(5);
const start = JSON.parse(lines[0] ?? "{}") as Record<string, unknown>;
expect(start.threadId).toBe(newId);
expect(start.forkFrom).toEqual({ threadId: sourceId });
const lastRoleLine = JSON.parse(lines[lines.length - 2] ?? "{}") as Record<string, unknown>; const steps = await listMeaningfulRoleContents(storageRoot, newId);
expect(lastRoleLine.role).toBe("reviewer"); const tail = steps[steps.length - 1];
const cas = createCasStore(getGlobalCasDir(storageRoot)); expect(tail?.role).toBe("reviewer");
expect(await getContentMerklePayload(cas, String(lastRoleLine.contentHash))).toBe("rev-1"); expect(tail?.content).toBe("rev-1");
}); });
test("fork without --from-role retries last role", async () => { test("fork without --from-role retries last role", async () => {
@@ -161,10 +174,8 @@ describe("cli fork", () => {
return; return;
} }
const sourceId = ran.value.threadId; const sourceId = ran.value.threadId;
const sourceData = join(storageRoot, "logs", hash, `${sourceId}.data.jsonl`); await waitUntilRunningAbsent(join(storageRoot, "logs", hash, `${sourceId}.running`));
const sourceRunning = join(storageRoot, "logs", hash, `${sourceId}.running`); await waitUntilThreadCompletes(storageRoot, sourceId);
await waitUntilRunningAbsent(sourceRunning);
await waitUntilMinDataLines(sourceData, 5);
const forked = await cmdFork(storageRoot, sourceId, null); const forked = await cmdFork(storageRoot, sourceId, null);
expect(forked.ok).toBe(true); expect(forked.ok).toBe(true);
@@ -172,26 +183,17 @@ describe("cli fork", () => {
return; return;
} }
const newId = forked.value.threadId; const newId = forked.value.threadId;
const newData = join(storageRoot, "logs", hash, `${newId}.data.jsonl`); await waitUntilRunningAbsent(join(storageRoot, "logs", hash, `${newId}.running`));
const newRunning = join(storageRoot, "logs", hash, `${newId}.running`); await waitUntilThreadCompletes(storageRoot, newId);
await waitUntilRunningAbsent(newRunning);
await waitUntilMinDataLines(newData, 5);
const text = await readFile(newData, "utf8"); const steps = await listMeaningfulRoleContents(storageRoot, newId);
const lines = text expect(steps.length).toBeGreaterThanOrEqual(3);
.trim() const coderReplay = steps[steps.length - 2];
.split("\n") expect(coderReplay?.role).toBe("coder");
.filter((l) => l !== ""); expect(coderReplay?.content).toBe("c1");
expect(lines.length).toBe(5); const tail = steps[steps.length - 1];
expect(tail?.role).toBe("reviewer");
const replayCoder = JSON.parse(lines[2] ?? "{}") as Record<string, unknown>; expect(tail?.content).toBe("rev-2");
expect(replayCoder.role).toBe("coder");
const cas = createCasStore(getGlobalCasDir(storageRoot));
expect(await getContentMerklePayload(cas, String(replayCoder.contentHash))).toBe("c1");
const lastRoleLine = JSON.parse(lines[lines.length - 2] ?? "{}") as Record<string, unknown>;
expect(lastRoleLine.role).toBe("reviewer");
expect(await getContentMerklePayload(cas, String(lastRoleLine.contentHash))).toBe("rev-2");
}); });
test("fork rejects unknown role with available names", async () => { test("fork rejects unknown role with available names", async () => {
@@ -212,10 +214,10 @@ describe("cli fork", () => {
return; return;
} }
const sourceId = ran.value.threadId; const sourceId = ran.value.threadId;
const sourceData = join(storageRoot, "logs", added.value.hash, `${sourceId}.data.jsonl`); await waitUntilRunningAbsent(
const sourceRunning = join(storageRoot, "logs", added.value.hash, `${sourceId}.running`); join(storageRoot, "logs", added.value.hash, `${sourceId}.running`),
await waitUntilRunningAbsent(sourceRunning); );
await waitUntilMinDataLines(sourceData, 5); await waitUntilThreadCompletes(storageRoot, sourceId);
const bad = await cmdFork(storageRoot, sourceId, "ghost-role"); const bad = await cmdFork(storageRoot, sourceId, "ghost-role");
expect(bad.ok).toBe(false); expect(bad.ok).toBe(false);
+60 -63
View File
@@ -1,45 +1,17 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { mkdir, mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { createCasStore, putContentMerkleNode } from "@uncaged/workflow-cas"; import { createCasStore, putStartNode } from "@uncaged/workflow-cas";
import { garbageCollectCas } from "@uncaged/workflow-execute"; import { garbageCollectCas, getBundleDir, upsertThreadEntry } from "@uncaged/workflow-execute";
import { getGlobalCasDir } from "@uncaged/workflow-util"; import { getGlobalCasDir } from "@uncaged/workflow-util";
import { cmdThreadRemove } from "../src/commands/thread/index.js"; import { cmdThreadRemove } from "../src/commands/thread/index.js";
import { pathExists } from "../src/fs-utils.js"; import { pathExists } from "../src/fs-utils.js";
const cliEntryPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url)); const cliEntryPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
async function writeDemoDataJsonl(params: {
path: string;
threadId: string;
bundleHash: string;
cas: ReturnType<typeof createCasStore>;
activeHash: string;
}): Promise<void> {
const bodyHash = await putContentMerkleNode(params.cas, "p");
const text = [
JSON.stringify({
name: "demo",
hash: params.bundleHash,
threadId: params.threadId,
parameters: { prompt: "hi", options: { maxRounds: 5 } },
timestamp: 100,
}),
JSON.stringify({
role: "planner",
contentHash: bodyHash,
meta: {},
refs: [params.activeHash, bodyHash],
timestamp: 101,
}),
"",
].join("\n");
await writeFile(params.path, text, "utf8");
}
describe("gc cli and garbageCollectCas", () => { describe("gc cli and garbageCollectCas", () => {
let prevEnv: string | undefined; let prevEnv: string | undefined;
let storageRoot: string; let storageRoot: string;
@@ -59,22 +31,30 @@ describe("gc cli and garbageCollectCas", () => {
await rm(storageRoot, { recursive: true, force: true }); await rm(storageRoot, { recursive: true, force: true });
}); });
test("garbageCollectCas keeps CAS entries referenced by thread refs", async () => { test("garbageCollectCas keeps CAS entries reachable from threads.json roots", async () => {
const bundleHash = "C9NMV6V2TQT81"; const bundleHash = "C9NMV6V2TQT81";
const threadId = "01AAA1111111111111111111"; const threadId = "01AAA1111111111111111111";
const logsDir = join(storageRoot, "logs", bundleHash); const bundleDir = getBundleDir(storageRoot, bundleHash);
await mkdir(logsDir, { recursive: true }); await mkdir(bundleDir, { recursive: true });
const cas = createCasStore(getGlobalCasDir(storageRoot)); const cas = createCasStore(getGlobalCasDir(storageRoot));
const activeHash = await cas.put("active-blob");
const orphanHash = await cas.put("orphan-blob"); const orphanHash = await cas.put("orphan-blob");
const promptHash = await cas.put("prompt-text");
await writeDemoDataJsonl({ const startHash = await putStartNode(
path: join(logsDir, `${threadId}.data.jsonl`),
threadId,
bundleHash,
cas, cas,
activeHash, {
name: "demo",
hash: bundleHash,
maxRounds: 5,
depth: 0,
},
promptHash,
);
await upsertThreadEntry(bundleDir, threadId, {
head: startHash,
start: startHash,
updatedAt: 100,
}); });
const gc = await garbageCollectCas(storageRoot); const gc = await garbageCollectCas(storageRoot);
@@ -82,12 +62,12 @@ describe("gc cli and garbageCollectCas", () => {
if (!gc.ok) { if (!gc.ok) {
return; return;
} }
expect(gc.value.scannedThreads).toBe(1); expect(gc.value.scannedThreads).toBe(2);
expect(gc.value.activeRefs).toBe(2);
expect(gc.value.deletedEntries).toBe(1); expect(gc.value.deletedEntries).toBe(1);
expect(gc.value.deletedHashes).toEqual([orphanHash]); expect(gc.value.deletedHashes).toEqual([orphanHash]);
expect(await pathExists(join(getGlobalCasDir(storageRoot), `${activeHash}.txt`))).toBe(true); expect(await pathExists(join(getGlobalCasDir(storageRoot), `${promptHash}.txt`))).toBe(true);
expect(await pathExists(join(getGlobalCasDir(storageRoot), `${startHash}.txt`))).toBe(true);
expect(await pathExists(join(getGlobalCasDir(storageRoot), `${orphanHash}.txt`))).toBe(false); expect(await pathExists(join(getGlobalCasDir(storageRoot), `${orphanHash}.txt`))).toBe(false);
}); });
@@ -110,19 +90,27 @@ describe("gc cli and garbageCollectCas", () => {
test("cli gc prints stats", async () => { test("cli gc prints stats", async () => {
const bundleHash = "C9NMV6V2TQT81"; const bundleHash = "C9NMV6V2TQT81";
const threadId = "01BBB2222222222222222222"; const threadId = "01BBB2222222222222222222";
const logsDir = join(storageRoot, "logs", bundleHash); const bundleDir = getBundleDir(storageRoot, bundleHash);
await mkdir(logsDir, { recursive: true }); await mkdir(bundleDir, { recursive: true });
const cas = createCasStore(getGlobalCasDir(storageRoot)); const cas = createCasStore(getGlobalCasDir(storageRoot));
const activeHash = await cas.put("keep-me"); const promptHash = await cas.put("prompt-text");
const startHash = await putStartNode(
cas,
{
name: "demo",
hash: bundleHash,
maxRounds: 5,
depth: 0,
},
promptHash,
);
await cas.put("drop-me"); await cas.put("drop-me");
await writeDemoDataJsonl({ await upsertThreadEntry(bundleDir, threadId, {
path: join(logsDir, `${threadId}.data.jsonl`), head: startHash,
threadId, start: startHash,
bundleHash, updatedAt: 100,
cas,
activeHash,
}); });
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot }; const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
@@ -131,23 +119,32 @@ describe("gc cli and garbageCollectCas", () => {
encoding: "utf8", encoding: "utf8",
}); });
expect(proc.status).toBe(0); expect(proc.status).toBe(0);
expect(String(proc.stdout).trim()).toBe("scanned 1 threads, 2 active refs, deleted 1 entries"); expect(String(proc.stdout).trim()).toBe("scanned 2 threads, 2 active refs, deleted 1 entries");
}); });
test("thread rm triggers gc so unreferenced CAS is removed", async () => { test("thread rm triggers gc so unreferenced CAS is removed", async () => {
const bundleHash = "C9NMV6V2TQT81"; const bundleHash = "C9NMV6V2TQT81";
const threadId = "01CCC3333333333333333333"; const threadId = "01CCC3333333333333333333";
const logsDir = join(storageRoot, "logs", bundleHash); const bundleDir = getBundleDir(storageRoot, bundleHash);
await mkdir(logsDir, { recursive: true }); await mkdir(bundleDir, { recursive: true });
const cas = createCasStore(getGlobalCasDir(storageRoot)); const cas = createCasStore(getGlobalCasDir(storageRoot));
const activeHash = await cas.put("pinned-by-ref"); const promptHash = await cas.put("prompt-text");
await writeDemoDataJsonl({ const startHash = await putStartNode(
path: join(logsDir, `${threadId}.data.jsonl`),
threadId,
bundleHash,
cas, cas,
activeHash, {
name: "demo",
hash: bundleHash,
maxRounds: 5,
depth: 0,
},
promptHash,
);
await upsertThreadEntry(bundleDir, threadId, {
head: startHash,
start: startHash,
updatedAt: 100,
}); });
const orphanHash = await cas.put("orphan-after-rm"); const orphanHash = await cas.put("orphan-after-rm");
@@ -157,6 +154,6 @@ describe("gc cli and garbageCollectCas", () => {
expect(removed.ok).toBe(true); expect(removed.ok).toBe(true);
expect(await pathExists(orphanPath)).toBe(false); expect(await pathExists(orphanPath)).toBe(false);
expect(await pathExists(join(getGlobalCasDir(storageRoot), `${activeHash}.txt`))).toBe(false); expect(await pathExists(join(getGlobalCasDir(storageRoot), `${promptHash}.txt`))).toBe(false);
}); });
}); });
+2 -241
View File
@@ -1,13 +1,10 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawn, spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";
import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { join } from "node:path"; import { join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { createCasStore, putContentMerkleNode } from "@uncaged/workflow-cas";
import { getGlobalCasDir } from "@uncaged/workflow-util";
import { import {
formatLiveDebugLine, formatLiveDebugLine,
formatLiveTimeLabel, formatLiveTimeLabel,
@@ -18,11 +15,6 @@ import {
import { parseLiveArgv } from "../src/live-argv.js"; import { parseLiveArgv } from "../src/live-argv.js";
const cliEntryPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url)); const cliEntryPath = fileURLToPath(new URL("../src/cli.ts", import.meta.url));
const fixtureRoot = fileURLToPath(new URL("./fixtures/live", import.meta.url));
/** Bodies for Merkle content nodes; hashes must match `.data.jsonl` fixtures. */
const LIVE_FIXTURE_PLANNER_BODY =
"alpha\nbeta\ngamma\nLINE4\nLINE5\nLINE6\nLINE7\nLINE8\nLINE9\nLINE10\nLINE11";
describe("live helpers", () => { describe("live helpers", () => {
test("formatLiveTimeLabel pads HH:MM:SS", () => { test("formatLiveTimeLabel pads HH:MM:SS", () => {
@@ -86,28 +78,6 @@ describe("live CLI", () => {
prevEnv = process.env.UNCAGED_WORKFLOW_STORAGE_ROOT; prevEnv = process.env.UNCAGED_WORKFLOW_STORAGE_ROOT;
storageRoot = await mkdtemp(join(tmpdir(), "uncaged-wf-live-")); storageRoot = await mkdtemp(join(tmpdir(), "uncaged-wf-live-"));
process.env.UNCAGED_WORKFLOW_STORAGE_ROOT = storageRoot; process.env.UNCAGED_WORKFLOW_STORAGE_ROOT = storageRoot;
await mkdir(join(storageRoot, "logs", "C9NMV6V2TQT81"), { recursive: true });
await cp(
join(fixtureRoot, "logs", "C9NMV6V2TQT81", "01LIVECMPLT01DDDDDDDDDDDDG.data.jsonl"),
join(storageRoot, "logs", "C9NMV6V2TQT81", "01LIVECMPLT01DDDDDDDDDDDDG.data.jsonl"),
);
await cp(
join(fixtureRoot, "logs", "C9NMV6V2TQT81", "01LIVECMPLT01DDDDDDDDDDDDG.info.jsonl"),
join(storageRoot, "logs", "C9NMV6V2TQT81", "01LIVECMPLT01DDDDDDDDDDDDG.info.jsonl"),
);
await cp(
join(fixtureRoot, "logs", "C9NMV6V2TQT81", "01LIVEINFLY01DDDDDDDDDDDDG.data.jsonl"),
join(storageRoot, "logs", "C9NMV6V2TQT81", "01LIVEINFLY01DDDDDDDDDDDDG.data.jsonl"),
);
await cp(
join(fixtureRoot, "logs", "C9NMV6V2TQT81", "01LIVEOLDER01DDDDDDDDDDDDG.data.jsonl"),
join(storageRoot, "logs", "C9NMV6V2TQT81", "01LIVEOLDER01DDDDDDDDDDDDG.data.jsonl"),
);
const cas = createCasStore(getGlobalCasDir(storageRoot));
await putContentMerkleNode(cas, LIVE_FIXTURE_PLANNER_BODY);
await putContentMerkleNode(cas, "patch");
await putContentMerkleNode(cas, "still running");
}); });
afterEach(async () => { afterEach(async () => {
@@ -119,170 +89,6 @@ describe("live CLI", () => {
await rm(storageRoot, { recursive: true, force: true }); await rm(storageRoot, { recursive: true, force: true });
}); });
test("prints role steps and summary for a completed thread", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const proc = spawn(process.execPath, [cliEntryPath, "live", "01LIVECMPLT01DDDDDDDDDDDDG"], {
env,
stdio: ["ignore", "pipe", "pipe"],
});
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("planner");
expect(stdout).toContain("coder");
expect(stdout).toContain("meta:");
expect(stdout).toContain('"phase":"plan"');
expect(stdout).toContain("LINE10");
expect(stdout).not.toContain("LINE11");
expect(stdout).toContain("more line");
expect(stdout).toContain("completed: returnCode=0");
expect(stdout).toContain("fixture completed");
});
test("--latest tails the newest thread by start timestamp", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const proc = spawn(process.execPath, [cliEntryPath, "live", "--latest"], {
env,
stdio: ["ignore", "pipe", "pipe"],
});
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("fixture completed");
expect(stdout).not.toContain("older thread");
});
test("--debug prints .info.jsonl records after data output", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const proc = spawn(
process.execPath,
[cliEntryPath, "live", "01LIVECMPLT01DDDDDDDDDDDDG", "--debug"],
{
env,
stdio: ["ignore", "pipe", "pipe"],
},
);
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("[DEBUGTAG1]");
expect(stdout).toContain("bundle loaded");
expect(stdout).toContain("[DEBUGTAG2]");
expect(stdout).toContain("multi line");
});
test("--role filters out non-matching roles", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const proc = spawn(
process.execPath,
[cliEntryPath, "live", "01LIVECMPLT01DDDDDDDDDDDDG", "--role", "planner"],
{
env,
stdio: ["ignore", "pipe", "pipe"],
},
);
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("planner");
expect(stdout).not.toContain("patch");
expect(stdout).toContain("completed: returnCode=0");
});
test("--latest --debug --role combine", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const proc = spawn(
process.execPath,
[cliEntryPath, "live", "--latest", "--debug", "--role", "planner"],
{
env,
stdio: ["ignore", "pipe", "pipe"],
},
);
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("[DEBUGTAG1]");
expect(stdout).toContain("planner");
expect(stdout).not.toContain("patch");
expect(stdout).toContain("fixture completed");
});
test("unknown thread id exits 1", () => { test("unknown thread id exits 1", () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot }; const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const r = spawnSync(process.execPath, [cliEntryPath, "live", "01UNKNOWNXXXXXXXXXXXXXXXXX"], { const r = spawnSync(process.execPath, [cliEntryPath, "live", "01UNKNOWNXXXXXXXXXXXXXXXXX"], {
@@ -292,51 +98,6 @@ describe("live CLI", () => {
expect(r.status).toBe(1); expect(r.status).toBe(1);
expect(String(r.stderr ?? "")).toContain("thread not found"); expect(String(r.stderr ?? "")).toContain("thread not found");
}); });
test("follows file until WorkflowResult is appended", async () => {
const env = { ...process.env, UNCAGED_WORKFLOW_STORAGE_ROOT: storageRoot };
const dataPath = join(
storageRoot,
"logs",
"C9NMV6V2TQT81",
"01LIVEINFLY01DDDDDDDDDDDDG.data.jsonl",
);
const proc = spawn(process.execPath, [cliEntryPath, "live", "01LIVEINFLY01DDDDDDDDDDDDG"], {
env,
stdio: ["ignore", "pipe", "pipe"],
});
await new Promise((r) => setTimeout(r, 120));
const prior = await readFile(dataPath, "utf8");
await writeFile(
dataPath,
`${prior.replace(/\s*$/, "")}\n${JSON.stringify({ returnCode: 0, summary: "caught up" })}\n`,
"utf8",
);
const stdout = await new Promise<string>((resolve, reject) => {
let buf = "";
proc.stdout?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.stderr?.on("data", (c: Buffer) => {
buf += c.toString("utf8");
});
proc.on("error", reject);
proc.on("exit", (code: number | null) => {
if (code === 0) {
resolve(buf);
} else {
reject(new Error(`exit ${code}: ${buf}`));
}
});
});
expect(stdout).toContain("planner");
expect(stdout).toContain("completed: returnCode=0");
expect(stdout).toContain("caught up");
});
}); });
describe("live --latest with empty storage", () => { describe("live --latest with empty storage", () => {
@@ -1,9 +1,10 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test"; import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { spawnSync } from "node:child_process"; import { spawnSync } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os"; import { tmpdir } from "node:os";
import { dirname, join } from "node:path"; import { join } from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
import { getBundleDir, readThreadsIndex } from "@uncaged/workflow-execute";
import { getGlobalCasDir } from "@uncaged/workflow-util"; import { getGlobalCasDir } from "@uncaged/workflow-util";
import { cmdCasPut } from "../src/commands/cas/index.js"; import { cmdCasPut } from "../src/commands/cas/index.js";
import { import {
@@ -18,6 +19,7 @@ import {
} from "../src/commands/thread/index.js"; } from "../src/commands/thread/index.js";
import { cmdAdd } from "../src/commands/workflow/index.js"; import { cmdAdd } from "../src/commands/workflow/index.js";
import { pathExists, readTextFileIfExists } from "../src/fs-utils.js"; import { pathExists, readTextFileIfExists } from "../src/fs-utils.js";
import { resolveThreadRecord } from "../src/thread-scan.js";
import { addCliArgs } from "./bundle-fixture.js"; import { addCliArgs } from "./bundle-fixture.js";
import { ensureTestWorkflowRegistryConfig } from "./workflow-registry-fixture.js"; import { ensureTestWorkflowRegistryConfig } from "./workflow-registry-fixture.js";
@@ -101,34 +103,21 @@ export const run = async function* (_input, options) {
}; };
`; `;
async function countDataJsonlLines(dataPath: string): Promise<number> { async function waitUntilRunningFileAbsent(runningPath: string, maxAttempts: number): Promise<void> {
try {
const text = await readFile(dataPath, "utf8");
return text
.trim()
.split("\n")
.filter((l) => l !== "").length;
} catch {
return 0;
}
}
async function waitUntilMinDataLines(
dataPath: string,
minLines: number,
maxAttempts: number,
): Promise<void> {
for (let attempt = 0; attempt < maxAttempts; attempt++) { for (let attempt = 0; attempt < maxAttempts; attempt++) {
if ((await countDataJsonlLines(dataPath)) >= minLines) { if (!(await pathExists(runningPath))) {
return; return;
} }
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
} }
} }
async function waitUntilRunningFileAbsent(runningPath: string, maxAttempts: number): Promise<void> { async function waitUntilPredicate(
predicate: () => Promise<boolean>,
maxAttempts: number,
): Promise<void> {
for (let attempt = 0; attempt < maxAttempts; attempt++) { for (let attempt = 0; attempt < maxAttempts; attempt++) {
if (!(await pathExists(runningPath))) { if (await predicate()) {
return; return;
} }
await new Promise((r) => setTimeout(r, 25)); await new Promise((r) => setTimeout(r, 25));
@@ -200,8 +189,7 @@ describe("cli thread commands", () => {
const removed = await cmdThreadRemove(storageRoot, threadId); const removed = await cmdThreadRemove(storageRoot, threadId);
expect(removed.ok).toBe(true); expect(removed.ok).toBe(true);
const dataPath = join(storageRoot, "logs", added.value.hash, `${threadId}.data.jsonl`); expect(await resolveThreadRecord(storageRoot, threadId)).toBeNull();
expect(await pathExists(dataPath)).toBe(false);
}); });
test("thread rm runs GC and removes CAS blobs not referenced by any remaining thread", async () => { test("thread rm runs GC and removes CAS blobs not referenced by any remaining thread", async () => {
@@ -234,9 +222,9 @@ describe("cli thread commands", () => {
threads = await cmdThreads(storageRoot, []); threads = await cmdThreads(storageRoot, []);
} }
const dataPath = join(storageRoot, "logs", added.value.hash, `${threadId}.data.jsonl`); const runningPath = join(storageRoot, "logs", added.value.hash, `${threadId}.running`);
const runningPath = join(dirname(dataPath), `${threadId}.running`);
await waitUntilRunningFileAbsent(runningPath, 120); await waitUntilRunningFileAbsent(runningPath, 120);
expect((await resolveThreadRecord(storageRoot, threadId))?.source).toBe("history");
const put = await cmdCasPut(storageRoot, "keep-after-thread-rm"); const put = await cmdCasPut(storageRoot, "keep-after-thread-rm");
expect(put.ok).toBe(true); expect(put.ok).toBe(true);
@@ -323,24 +311,20 @@ describe("cli thread commands", () => {
const killed = await cmdKill(storageRoot, threadId); const killed = await cmdKill(storageRoot, threadId);
expect(killed.ok).toBe(true); expect(killed.ok).toBe(true);
await new Promise((r) => setTimeout(r, 900)); await waitUntilPredicate(async () => {
return (await resolveThreadRecord(storageRoot, threadId))?.source === "history";
}, 120);
const dataPath = join(storageRoot, "logs", added.value.hash, `${threadId}.data.jsonl`); expect((await resolveThreadRecord(storageRoot, threadId))?.source).toBe("history");
const text = await readFile(dataPath, "utf8");
const lines = text
.trim()
.split("\n")
.filter((l) => l !== "");
expect(lines.length).toBe(3);
const runningPath = join(dirname(dataPath), `${threadId}.running`); const runningPath = join(storageRoot, "logs", added.value.hash, `${threadId}.running`);
expect(await pathExists(runningPath)).toBe(false); expect(await pathExists(runningPath)).toBe(false);
}); });
test("pause stops between yields and resume completes thread", async () => { test("pause stops between yields and resume completes thread", async () => {
const bundleDir = join(storageRoot, "src"); const srcDir = join(storageRoot, "src");
await mkdir(bundleDir, { recursive: true }); await mkdir(srcDir, { recursive: true });
const bundlePath = join(bundleDir, "demo.esm.js"); const bundlePath = join(srcDir, "demo.esm.js");
await writeFile(bundlePath, pauseResumeBundleSource, "utf8"); await writeFile(bundlePath, pauseResumeBundleSource, "utf8");
const added = await cmdAdd(storageRoot, addCliArgs("solve-issue", bundlePath)); const added = await cmdAdd(storageRoot, addCliArgs("solve-issue", bundlePath));
@@ -356,24 +340,33 @@ describe("cli thread commands", () => {
} }
const threadId = ran.value.threadId; const threadId = ran.value.threadId;
const dataPath = join(storageRoot, "logs", added.value.hash, `${threadId}.data.jsonl`); const bundleDir = getBundleDir(storageRoot, added.value.hash);
await waitUntilMinDataLines(dataPath, 2, 80); await waitUntilPredicate(async () => {
expect(await countDataJsonlLines(dataPath)).toBe(2); const idx = await readThreadsIndex(bundleDir);
const ent = idx[threadId];
return ent !== undefined && ent.head !== ent.start;
}, 80);
const idxBeforePause = await readThreadsIndex(bundleDir);
const headAtPause = idxBeforePause[threadId]?.head;
const paused = await cmdPause(storageRoot, threadId); const paused = await cmdPause(storageRoot, threadId);
expect(paused.ok).toBe(true); expect(paused.ok).toBe(true);
await new Promise((r) => setTimeout(r, 400)); await new Promise((r) => setTimeout(r, 400));
expect(await countDataJsonlLines(dataPath)).toBe(2); const idxPaused = await readThreadsIndex(bundleDir);
expect(idxPaused[threadId]?.head).toBe(headAtPause);
const resumed = await cmdResume(storageRoot, threadId); const resumed = await cmdResume(storageRoot, threadId);
expect(resumed.ok).toBe(true); expect(resumed.ok).toBe(true);
await waitUntilMinDataLines(dataPath, 4, 120); await waitUntilPredicate(async () => {
expect(await countDataJsonlLines(dataPath)).toBe(4); const row = await resolveThreadRecord(storageRoot, threadId);
return row?.source === "history";
}, 120);
const runningPath = join(dirname(dataPath), `${threadId}.running`); const runningPath = join(storageRoot, "logs", added.value.hash, `${threadId}.running`);
await waitUntilRunningFileAbsent(runningPath, 100); await waitUntilRunningFileAbsent(runningPath, 100);
expect(await pathExists(runningPath)).toBe(false); expect(await pathExists(runningPath)).toBe(false);
}); });
@@ -397,8 +390,7 @@ describe("cli thread commands", () => {
} }
const threadId = ran.value.threadId; const threadId = ran.value.threadId;
const dataPath = join(storageRoot, "logs", added.value.hash, `${threadId}.data.jsonl`); const runningPath = join(storageRoot, "logs", added.value.hash, `${threadId}.running`);
const runningPath = join(dirname(dataPath), `${threadId}.running`);
await waitUntilRunningFileAbsent(runningPath, 100); await waitUntilRunningFileAbsent(runningPath, 100);
expect(await pathExists(runningPath)).toBe(false); expect(await pathExists(runningPath)).toBe(false);
@@ -1,9 +1,18 @@
import { statSync, watch } from "node:fs"; import { statSync, watch } from "node:fs";
import { dirname, join } from "node:path"; import { join } from "node:path";
import { createCasStore, getContentMerklePayload } from "@uncaged/workflow-cas";
import {
FORK_BRANCH_ROLE,
readThreadsIndex,
type ThreadIndex,
walkStateFramesNewestFirst,
} from "@uncaged/workflow-execute";
import { END } from "@uncaged/workflow-runtime";
import { getGlobalCasDir } from "@uncaged/workflow-util";
import { Hono } from "hono"; import { Hono } from "hono";
import { streamSSE } from "hono/streaming"; import { streamSSE } from "hono/streaming";
import { resolveThreadDataPath } from "../../thread-scan.js"; import { resolveThreadRecord } from "../../thread-scan.js";
type PumpState = { type PumpState = {
contentOffset: number; contentOffset: number;
@@ -21,7 +30,6 @@ function fileSize(path: string): number {
async function readNewBytes(path: string, state: PumpState): Promise<string | null> { async function readNewBytes(path: string, state: PumpState): Promise<string | null> {
const size = fileSize(path); const size = fileSize(path);
if (size < state.contentOffset) { if (size < state.contentOffset) {
// File was truncated — reset
state.contentOffset = 0; state.contentOffset = 0;
state.carry = ""; state.carry = "";
} }
@@ -42,15 +50,6 @@ function parseJsonLine(line: string): unknown {
} }
} }
function isWorkflowResult(record: unknown): boolean {
return (
record !== null &&
typeof record === "object" &&
"type" in (record as Record<string, unknown>) &&
(record as Record<string, unknown>).type === "workflow-result"
);
}
function parseNewLines(chunk: string, state: PumpState): string[] { function parseNewLines(chunk: string, state: PumpState): string[] {
state.carry += chunk; state.carry += chunk;
@@ -67,52 +66,192 @@ function parseNewLines(chunk: string, state: PumpState): string[] {
return lines; return lines;
} }
type CasSseState = {
printedHashes: Set<string>;
lastHead: string | null;
completionEmitted: boolean;
};
type LiveSseStream = {
writeSSE: (opts: { event: string; data: string; id: string }) => Promise<void>;
};
function completionFromEndMeta(meta: Record<string, unknown>): {
returnCode: number;
summary: string;
} | null {
const returnCode = meta.returnCode;
const summary = meta.summary;
if (typeof returnCode !== "number" || typeof summary !== "string") {
return null;
}
return { returnCode, summary };
}
async function emitRecordsForHead(params: {
storageRoot: string;
bundleDir: string;
threadId: string;
headHash: string;
sseState: CasSseState;
stream: LiveSseStream;
eventId: { n: number };
}): Promise<boolean> {
const cas = createCasStore(getGlobalCasDir(params.storageRoot));
const frames = await walkStateFramesNewestFirst(cas, params.headHash);
const chronological = [...frames].reverse();
for (const fr of chronological) {
if (params.sseState.printedHashes.has(fr.hash)) {
continue;
}
params.sseState.printedHashes.add(fr.hash);
const role = fr.payload.role;
if (role === FORK_BRANCH_ROLE) {
continue;
}
if (role === END) {
const wf = completionFromEndMeta(fr.payload.meta);
if (wf !== null) {
params.eventId.n++;
await params.stream.writeSSE({
event: "record",
data: JSON.stringify({ type: "workflow-result", ...wf }),
id: String(params.eventId.n),
});
return true;
}
continue;
}
const payloadText = await getContentMerklePayload(cas, fr.payload.content);
const content =
payloadText !== null
? payloadText
: `(content not in CAS; contentHash=${fr.payload.content})`;
params.eventId.n++;
await params.stream.writeSSE({
event: "record",
data: JSON.stringify({
role: fr.payload.role,
contentHash: fr.payload.content,
content,
meta: fr.payload.meta,
timestamp: fr.payload.timestamp,
}),
id: String(params.eventId.n),
});
}
return false;
}
async function pumpThreadsJsonSse(params: {
storageRoot: string;
bundleDir: string;
threadId: string;
sseState: CasSseState;
stream: LiveSseStream;
eventId: { n: number };
}): Promise<boolean> {
let idx: ThreadIndex;
try {
idx = await readThreadsIndex(params.bundleDir);
} catch {
idx = {};
}
const active = idx[params.threadId];
if (active === undefined) {
if (params.sseState.completionEmitted) {
return false;
}
const hist = await resolveThreadRecord(params.storageRoot, params.threadId);
if (hist === null || hist.source !== "history") {
return false;
}
params.sseState.completionEmitted = true;
return await emitRecordsForHead({
storageRoot: params.storageRoot,
bundleDir: params.bundleDir,
threadId: params.threadId,
headHash: hist.head,
sseState: params.sseState,
stream: params.stream,
eventId: params.eventId,
});
}
const head = active.head;
if (params.sseState.lastHead === null) {
params.sseState.lastHead = head;
return await emitRecordsForHead({
storageRoot: params.storageRoot,
bundleDir: params.bundleDir,
threadId: params.threadId,
headHash: head,
sseState: params.sseState,
stream: params.stream,
eventId: params.eventId,
});
}
if (head !== params.sseState.lastHead) {
params.sseState.lastHead = head;
return await emitRecordsForHead({
storageRoot: params.storageRoot,
bundleDir: params.bundleDir,
threadId: params.threadId,
headHash: head,
sseState: params.sseState,
stream: params.stream,
eventId: params.eventId,
});
}
return false;
}
export function createLiveRoutes(storageRoot: string): Hono { export function createLiveRoutes(storageRoot: string): Hono {
const app = new Hono(); const app = new Hono();
app.get("/:threadId/live", async (c) => { app.get("/:threadId/live", async (c) => {
const threadId = c.req.param("threadId"); const threadId = c.req.param("threadId");
const dataPath = await resolveThreadDataPath(storageRoot, threadId); const resolved = await resolveThreadRecord(storageRoot, threadId);
if (dataPath === null) { if (resolved === null) {
return c.json({ error: `thread not found: ${threadId}` }, 404); return c.json({ error: `thread not found: ${threadId}` }, 404);
} }
const resolvedDataPath = dataPath;
const infoPath = join(dirname(resolvedDataPath), `${threadId}.info.jsonl`); const threadTarget = resolved;
const threadsJsonPath = join(threadTarget.bundleDir, "threads.json");
const infoPath = join(storageRoot, "logs", threadTarget.bundleHash, `${threadId}.info.jsonl`);
return streamSSE(c, async (stream) => { return streamSSE(c, async (stream) => {
const dataState: PumpState = { contentOffset: 0, carry: "" };
const infoState: PumpState = { contentOffset: 0, carry: "" }; const infoState: PumpState = { contentOffset: 0, carry: "" };
let eventId = 0; const sseThreadState: CasSseState = {
printedHashes: new Set<string>(),
lastHead: null,
completionEmitted: false,
};
const eventId = { n: 0 };
async function pumpData(): Promise<boolean> { async function pumpData(): Promise<boolean> {
let chunk: string | null; const finished = await pumpThreadsJsonSse({
try { storageRoot,
chunk = await readNewBytes(resolvedDataPath, dataState); bundleDir: threadTarget.bundleDir,
} catch { threadId,
return false; sseState: sseThreadState,
} stream,
if (chunk === null) { eventId,
return false;
}
const lines = parseNewLines(chunk, dataState);
for (const line of lines) {
const record = parseJsonLine(line);
eventId++;
await stream.writeSSE({
event: "record",
data: JSON.stringify(record),
id: String(eventId),
}); });
return finished;
if (isWorkflowResult(record)) {
return true;
}
}
return false;
} }
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: SSE newline framing mirrors legacy pump
async function pumpInfo(): Promise<void> { async function pumpInfo(): Promise<void> {
let chunk: string | null; let chunk: string | null;
try { try {
@@ -134,28 +273,46 @@ export function createLiveRoutes(storageRoot: string): Hono {
) { ) {
continue; continue;
} }
eventId++; eventId.n++;
await stream.writeSSE({ await stream.writeSSE({
event: "info", event: "info",
data: JSON.stringify(record), data: JSON.stringify(record),
id: String(eventId), id: String(eventId.n),
}); });
} }
} }
// Initial pump eventId.n++;
await stream.writeSSE({
event: "record",
data: JSON.stringify({
type: "thread-start",
threadId: threadTarget.threadId,
bundleHash: threadTarget.bundleHash,
head: threadTarget.head,
start: threadTarget.start,
source: threadTarget.source,
}),
id: String(eventId.n),
});
const done = await pumpData(); const done = await pumpData();
try {
await pumpInfo(); await pumpInfo();
} catch {
// optional info file
}
if (done) { if (done) {
return; return;
} }
// Watch for changes
const controller = new AbortController(); const controller = new AbortController();
let completed = false; let completed = false;
const dataWatcher = watch(resolvedDataPath, async () => { const dataWatcher = watch(threadsJsonPath, async () => {
if (completed) return; if (completed) {
return;
}
const finished = await pumpData(); const finished = await pumpData();
if (finished) { if (finished) {
completed = true; completed = true;
@@ -166,7 +323,9 @@ export function createLiveRoutes(storageRoot: string): Hono {
let infoWatcher: ReturnType<typeof watch> | null = null; let infoWatcher: ReturnType<typeof watch> | null = null;
try { try {
infoWatcher = watch(infoPath, async () => { infoWatcher = watch(infoPath, async () => {
if (completed) return; if (completed) {
return;
}
await pumpInfo(); await pumpInfo();
}); });
} catch { } catch {
@@ -179,7 +338,6 @@ export function createLiveRoutes(storageRoot: string): Hono {
infoWatcher?.close(); infoWatcher?.close();
}); });
// Keep stream alive until completion or client disconnect
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
if (completed) { if (completed) {
resolve(); resolve();
@@ -1,10 +1,13 @@
import { createCasStore } from "@uncaged/workflow-cas";
import { FORK_BRANCH_ROLE, walkStateFramesNewestFirst } from "@uncaged/workflow-execute";
import { END } from "@uncaged/workflow-runtime";
import { getGlobalCasDir } from "@uncaged/workflow-util";
import { Hono } from "hono"; import { Hono } from "hono";
import { readTextFileIfExists } from "../../fs-utils.js";
import { import {
listHistoricalThreads, listHistoricalThreads,
listRunningThreads, listRunningThreads,
resolveThreadDataPath, resolveThreadRecord,
} from "../../thread-scan.js"; } from "../../thread-scan.js";
import { cmdKill, cmdPause, cmdResume } from "../thread/control.js"; import { cmdKill, cmdPause, cmdResume } from "../thread/control.js";
import { cmdRun } from "../thread/run.js"; import { cmdRun } from "../thread/run.js";
@@ -25,22 +28,46 @@ export function createThreadRoutes(storageRoot: string): Hono {
app.get("/:threadId", async (c) => { app.get("/:threadId", async (c) => {
const threadId = c.req.param("threadId"); const threadId = c.req.param("threadId");
const dataPath = await resolveThreadDataPath(storageRoot, threadId); const resolved = await resolveThreadRecord(storageRoot, threadId);
if (dataPath === null) { if (resolved === null) {
return c.json({ error: `thread not found: ${threadId}` }, 404); return c.json({ error: `thread not found: ${threadId}` }, 404);
} }
const text = await readTextFileIfExists(dataPath);
if (text === null) { const cas = createCasStore(getGlobalCasDir(storageRoot));
return c.json({ error: `thread data missing: ${threadId}` }, 404); const frames = await walkStateFramesNewestFirst(cas, resolved.head);
const chronological = [...frames].reverse();
const records: unknown[] = [
{
type: "thread-start",
threadId: resolved.threadId,
bundleHash: resolved.bundleHash,
head: resolved.head,
start: resolved.start,
source: resolved.source,
},
];
for (const fr of chronological) {
if (fr.payload.role === FORK_BRANCH_ROLE) {
continue;
} }
const lines = text.trim().split("\n"); if (fr.payload.role === END) {
const records = lines.map((line) => { const returnCode = fr.payload.meta.returnCode;
try { const summary = fr.payload.meta.summary;
return JSON.parse(line) as unknown; if (typeof returnCode === "number" && typeof summary === "string") {
} catch { records.push({ type: "workflow-result", returnCode, summary });
return { raw: line };
} }
continue;
}
records.push({
role: fr.payload.role,
contentHash: fr.payload.content,
meta: fr.payload.meta,
timestamp: fr.payload.timestamp,
}); });
}
return c.json({ threadId, records }); return c.json({ threadId, records });
}); });
@@ -1,10 +1,11 @@
import { join } from "node:path"; import { join } from "node:path";
import { buildForkPlan } from "@uncaged/workflow-execute"; import { createCasStore } from "@uncaged/workflow-cas";
import { prepareCasFork } from "@uncaged/workflow-execute";
import { err, ok, type Result } from "@uncaged/workflow-protocol"; import { err, ok, type Result } from "@uncaged/workflow-protocol";
import { generateUlid } from "@uncaged/workflow-util"; import { generateUlid, getGlobalCasDir } from "@uncaged/workflow-util";
import { pathExists, readTextFileIfExists } from "../../fs-utils.js"; import { pathExists } from "../../fs-utils.js";
import { resolveThreadDataPath } from "../../thread-scan.js"; import { resolveThreadRecord } from "../../thread-scan.js";
import { ensureWorkerForHash, sendWorkerTcpCommand } from "../../worker-spawn.js"; import { ensureWorkerForHash, sendWorkerTcpCommand } from "../../worker-spawn.js";
export async function cmdFork( export async function cmdFork(
@@ -12,49 +13,51 @@ export async function cmdFork(
threadId: string, threadId: string,
fromRole: string | null, fromRole: string | null,
): Promise<Result<{ threadId: string }, string>> { ): Promise<Result<{ threadId: string }, string>> {
const dataPath = await resolveThreadDataPath(storageRoot, threadId); const resolved = await resolveThreadRecord(storageRoot, threadId);
if (dataPath === null) { if (resolved === null) {
return err(`thread not found: ${threadId}`); return err(`thread not found: ${threadId}`);
} }
const text = await readTextFileIfExists(dataPath);
if (text === null) { const bundlePath = join(storageRoot, "bundles", `${resolved.bundleHash}.esm.js`);
return err(`thread data missing: ${threadId}`); if (!(await pathExists(bundlePath))) {
return err(`bundle file missing for thread hash ${resolved.bundleHash}`);
} }
const plan = buildForkPlan(text, fromRole); const cas = createCasStore(getGlobalCasDir(storageRoot));
const newThreadId = generateUlid(Date.now());
const plan = await prepareCasFork({
cas,
bundleDir: resolved.bundleDir,
bundleHash: resolved.bundleHash,
sourceThreadId: threadId,
headHash: resolved.head,
startHash: resolved.start,
newThreadId,
fromRole,
});
if (!plan.ok) { if (!plan.ok) {
return plan; return plan;
} }
const bundlePath = join(storageRoot, "bundles", `${plan.value.hash}.esm.js`);
if (!(await pathExists(bundlePath))) {
return err(`bundle file missing for thread hash ${plan.value.hash}`);
}
const worker = await ensureWorkerForHash(storageRoot, plan.value.hash, bundlePath); const worker = await ensureWorkerForHash(storageRoot, plan.value.hash, bundlePath);
if (!worker.ok) { if (!worker.ok) {
return worker; return worker;
} }
const newThreadId = generateUlid(Date.now()); const p = plan.value;
const stepsOnWire = plan.value.historicalSteps.map((s) => ({
role: s.role,
contentHash: s.contentHash,
meta: s.meta,
refs: s.refs,
timestamp: s.timestamp,
}));
const sent = await sendWorkerTcpCommand( const sent = await sendWorkerTcpCommand(
worker.value.port, worker.value.port,
{ {
type: "run", type: "run",
threadId: newThreadId, threadId: newThreadId,
workflowName: plan.value.workflowName, workflowName: p.workflowName,
prompt: plan.value.prompt, prompt: p.prompt,
options: plan.value.runOptions, options: p.runOptions,
steps: stepsOnWire, steps: p.steps,
forkSourceThreadId: plan.value.sourceThreadId, stepTimestamps: p.stepTimestamps.length > 0 ? p.stepTimestamps : null,
forkSourceThreadId: threadId,
forkContinuation: p.forkContinuation,
}, },
{ awaitResponseLine: false }, { awaitResponseLine: false },
); );
+184 -116
View File
@@ -1,16 +1,26 @@
import { watch } from "node:fs"; import { watch } from "node:fs";
import { readFile } from "node:fs/promises"; import { mkdir, readFile } from "node:fs/promises";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { createCasStore, getContentMerklePayload } from "@uncaged/workflow-cas"; import { createCasStore, getContentMerklePayload } from "@uncaged/workflow-cas";
import { tryParseRoleStepRecord, tryParseWorkflowResultRecord } from "@uncaged/workflow-execute"; import {
FORK_BRANCH_ROLE,
readThreadsIndex,
type ThreadIndex,
walkStateFramesNewestFirst,
} from "@uncaged/workflow-execute";
import type { CasStore, WorkflowCompletion } from "@uncaged/workflow-protocol"; import type { CasStore, WorkflowCompletion } from "@uncaged/workflow-protocol";
import { END } from "@uncaged/workflow-runtime";
import { getGlobalCasDir } from "@uncaged/workflow-util"; import { getGlobalCasDir } from "@uncaged/workflow-util";
import { dimGreyLine, highlightLiveRole } from "../../cli-color.js"; import { dimGreyLine, highlightLiveRole } from "../../cli-color.js";
import { printCliError, printCliLine } from "../../cli-output.js"; import { printCliError, printCliLine } from "../../cli-output.js";
import { pathExists } from "../../fs-utils.js"; import { pathExists } from "../../fs-utils.js";
import type { ParsedLiveArgv } from "../../live-argv.js"; import type { ParsedLiveArgv } from "../../live-argv.js";
import { findLatestThreadDataPath, resolveThreadDataPath } from "../../thread-scan.js"; import {
findLatestThreadBundleTarget,
type LatestThreadTarget,
resolveThreadRecord,
} from "../../thread-scan.js";
import type { LiveRoleRow } from "./types.js"; import type { LiveRoleRow } from "./types.js";
export const LIVE_CONTENT_MAX_LINES = 10; export const LIVE_CONTENT_MAX_LINES = 10;
@@ -48,16 +58,15 @@ function printSummary(result: WorkflowCompletion): void {
printCliLine(`completed: returnCode=${result.returnCode}${result.summary}`); printCliLine(`completed: returnCode=${result.returnCode}${result.summary}`);
} }
type LiveSessionState = { type InfoLiveState = {
sawStart: boolean;
completed: boolean;
carry: string; carry: string;
contentOffset: number; contentOffset: number;
}; };
type InfoLiveState = { type CasLiveState = {
carry: string; printedHashes: Set<string>;
contentOffset: number; lastHead: string | null;
completionEmitted: boolean;
}; };
function tryParseInfoRecord(obj: Record<string, unknown>): { function tryParseInfoRecord(obj: Record<string, unknown>): {
@@ -79,102 +88,140 @@ function tryParseInfoRecord(obj: Record<string, unknown>): {
return { tag, content, timestamp }; return { tag, content, timestamp };
} }
async function handleJsonlLine( function completionFromEndMeta(meta: Record<string, unknown>): WorkflowCompletion | null {
rawLine: string, const returnCode = meta.returnCode;
state: LiveSessionState, const summary = meta.summary;
roleFilter: string | null, if (typeof returnCode !== "number" || typeof summary !== "string") {
cas: CasStore, return null;
): Promise<{ parseError: string | null; workflowResult: WorkflowCompletion | null }> {
const trimmed = rawLine.trim();
if (trimmed === "") {
return { parseError: null, workflowResult: null };
} }
return { returnCode, summary };
}
let rec: unknown; async function emitRoleStepPrint(params: {
try { cas: CasStore;
rec = JSON.parse(trimmed) as unknown; role: string;
} catch { contentHash: string;
return { parseError: "invalid JSON in thread data file", workflowResult: null }; meta: Record<string, unknown>;
timestamp: number;
roleFilter: string | null;
}): Promise<void> {
if (params.roleFilter !== null && params.role !== params.roleFilter) {
return;
} }
if (rec === null || typeof rec !== "object") { const payload = await getContentMerklePayload(params.cas, params.contentHash);
return { parseError: "invalid record in thread data file", workflowResult: null };
}
const obj = rec as Record<string, unknown>;
if (!state.sawStart) {
state.sawStart = true;
return { parseError: null, workflowResult: null };
}
const wf = tryParseWorkflowResultRecord(obj);
if (wf !== null) {
state.completed = true;
return { parseError: null, workflowResult: wf };
}
const roleRow = tryParseRoleStepRecord(obj);
if (roleRow === null) {
return {
parseError: "unrecognized record in thread data (expected role step or result)",
workflowResult: null,
};
}
if (roleFilter !== null && roleRow.role !== roleFilter) {
return { parseError: null, workflowResult: null };
}
const payload = await getContentMerklePayload(cas, roleRow.contentHash);
const content = const content =
payload !== null ? payload : `(content not in CAS; contentHash=${roleRow.contentHash})`; payload !== null ? payload : `(content not in CAS; contentHash=${params.contentHash})`;
const row: LiveRoleRow = { const row: LiveRoleRow = {
role: roleRow.role, role: params.role,
content, content,
meta: roleRow.meta, meta: params.meta,
timestamp: roleRow.timestamp, timestamp: params.timestamp,
}; };
for (const outLine of renderLiveRoleStepLines(row, highlightLiveRole(row.role))) { for (const outLine of renderLiveRoleStepLines(row, highlightLiveRole(row.role))) {
printCliLine(outLine); printCliLine(outLine);
} }
return { parseError: null, workflowResult: null };
} }
async function pumpNewContent( async function emitStatesReachableFromHead(params: {
dataPath: string, cas: CasStore;
state: LiveSessionState, headHash: string;
roleFilter: string | null, state: CasLiveState;
cas: CasStore, roleFilter: string | null;
): Promise<number | null> { }): Promise<WorkflowCompletion | null> {
let text: string; const frames = await walkStateFramesNewestFirst(params.cas, params.headHash);
const chronological = [...frames].reverse();
for (const fr of chronological) {
if (params.state.printedHashes.has(fr.hash)) {
continue;
}
params.state.printedHashes.add(fr.hash);
const role = fr.payload.role;
if (role === FORK_BRANCH_ROLE) {
continue;
}
if (role === END) {
const wf = completionFromEndMeta(fr.payload.meta);
if (wf !== null) {
printSummary(wf);
return wf;
}
continue;
}
await emitRoleStepPrint({
cas: params.cas,
role,
contentHash: fr.payload.content,
meta: fr.payload.meta,
timestamp: fr.payload.timestamp,
roleFilter: params.roleFilter,
});
}
return null;
}
async function pumpThreadsJson(params: {
storageRoot: string;
bundleDir: string;
bundleHash: string;
threadId: string;
state: CasLiveState;
roleFilter: string | null;
cas: CasStore;
}): Promise<number | null> {
let idx: ThreadIndex;
try { try {
text = await readFile(dataPath, "utf8"); idx = await readThreadsIndex(params.bundleDir);
} catch { } catch {
idx = {};
}
const active = idx[params.threadId];
if (active === undefined) {
if (params.state.completionEmitted) {
return null; return null;
} }
const hist = await resolveThreadRecord(params.storageRoot, params.threadId);
if (text.length < state.contentOffset) { if (hist === null || hist.source !== "history") {
state.contentOffset = 0; return null;
state.carry = ""; }
params.state.completionEmitted = true;
const wf = await emitStatesReachableFromHead({
cas: params.cas,
headHash: hist.head,
state: params.state,
roleFilter: params.roleFilter,
});
return wf !== null ? 0 : null;
} }
const chunk = text.slice(state.contentOffset); const head = active.head;
state.contentOffset = text.length; if (params.state.lastHead === null) {
state.carry += chunk; params.state.lastHead = head;
const wf = await emitStatesReachableFromHead({
const parts = state.carry.split("\n"); cas: params.cas,
state.carry = parts.pop() ?? ""; headHash: head,
state: params.state,
for (const line of parts) { roleFilter: params.roleFilter,
const { parseError, workflowResult } = await handleJsonlLine(line, state, roleFilter, cas); });
if (parseError !== null) { return wf !== null ? 0 : null;
printCliError(parseError);
return 1;
}
if (workflowResult !== null) {
printSummary(workflowResult);
return 0;
} }
if (head !== params.state.lastHead) {
params.state.lastHead = head;
const wf = await emitStatesReachableFromHead({
cas: params.cas,
headHash: head,
state: params.state,
roleFilter: params.roleFilter,
});
return wf !== null ? 0 : null;
} }
return null; return null;
@@ -291,9 +338,9 @@ function watchLivePaths(params: { tasks: WatchPumpTask[]; signal: AbortSignal })
schedulePump(path, pump); schedulePump(path, pump);
}); });
watchers.push(watcher); watchers.push(watcher);
watcher.on("error", (err: Error) => { watcher.on("error", (errObj: Error) => {
closeAll(); closeAll();
reject(err); reject(errObj);
}); });
} }
@@ -309,17 +356,14 @@ function watchLivePaths(params: { tasks: WatchPumpTask[]; signal: AbortSignal })
}); });
} }
type LiveThreadTarget = { type LiveThreadTarget = LatestThreadTarget;
threadId: string;
dataPath: string;
};
async function resolveLiveThreadTarget( async function resolveLiveThreadTarget(
storageRoot: string, storageRoot: string,
parsed: ParsedLiveArgv, parsed: ParsedLiveArgv,
): Promise<LiveThreadTarget | null> { ): Promise<LiveThreadTarget | null> {
if (parsed.latest) { if (parsed.latest) {
const found = await findLatestThreadDataPath(storageRoot); const found = await findLatestThreadBundleTarget(storageRoot);
if (found === null) { if (found === null) {
printCliError("live: no threads found"); printCliError("live: no threads found");
return null; return null;
@@ -332,36 +376,56 @@ async function resolveLiveThreadTarget(
printCliError("live: internal error: missing thread id"); printCliError("live: internal error: missing thread id");
return null; return null;
} }
const resolved = await resolveThreadDataPath(storageRoot, id); const resolved = await resolveThreadRecord(storageRoot, id);
if (resolved === null) { if (resolved === null) {
printCliError(`thread not found: ${id}`); printCliError(`thread not found: ${id}`);
return null; return null;
} }
return { threadId: id, dataPath: resolved }; return {
threadId: id,
bundleHash: resolved.bundleHash,
bundleDir: resolved.bundleDir,
threadsJsonPath: join(resolved.bundleDir, "threads.json"),
};
} }
async function buildLiveWatchTasks(params: { async function buildLiveWatchTasks(params: {
dataPath: string; storageRoot: string;
infoPath: string; target: LiveThreadTarget;
debug: boolean; debug: boolean;
dataState: LiveSessionState; dataState: CasLiveState;
infoState: InfoLiveState; infoState: InfoLiveState;
roleFilter: string | null; roleFilter: string | null;
cas: CasStore; cas: CasStore;
}): Promise<WatchPumpTask[]> { }): Promise<WatchPumpTask[]> {
const { dataPath, infoPath, debug, dataState, infoState, roleFilter, cas } = params; const infoPath = join(
params.storageRoot,
"logs",
params.target.bundleHash,
`${params.target.threadId}.info.jsonl`,
);
const tasks: WatchPumpTask[] = [ const tasks: WatchPumpTask[] = [
{ {
path: dataPath, path: params.target.threadsJsonPath,
pump: () => pumpNewContent(dataPath, dataState, roleFilter, cas), pump: () =>
pumpThreadsJson({
storageRoot: params.storageRoot,
bundleDir: params.target.bundleDir,
bundleHash: params.target.bundleHash,
threadId: params.target.threadId,
state: params.dataState,
roleFilter: params.roleFilter,
cas: params.cas,
}),
}, },
]; ];
if (debug && (await pathExists(infoPath))) { if (params.debug && (await pathExists(infoPath))) {
tasks.push({ tasks.push({
path: infoPath, path: infoPath,
pump: async () => { pump: async () => {
await pumpNewInfoContent(infoPath, infoState); await pumpNewInfoContent(infoPath, params.infoState);
return null; return null;
}, },
}); });
@@ -376,16 +440,13 @@ export async function cmdLive(storageRoot: string, parsed: ParsedLiveArgv): Prom
return 1; return 1;
} }
const { threadId, dataPath } = target;
const roleFilter = parsed.role; const roleFilter = parsed.role;
const infoPath = join(dirname(dataPath), `${threadId}.info.jsonl`);
const cas = createCasStore(getGlobalCasDir(storageRoot)); const cas = createCasStore(getGlobalCasDir(storageRoot));
const dataState: LiveSessionState = { const dataState: CasLiveState = {
sawStart: false, printedHashes: new Set<string>(),
completed: false, lastHead: null,
carry: "", completionEmitted: false,
contentOffset: 0,
}; };
const infoState: InfoLiveState = { const infoState: InfoLiveState = {
@@ -400,22 +461,29 @@ export async function cmdLive(storageRoot: string, parsed: ParsedLiveArgv): Prom
process.on("SIGINT", onSigInt); process.on("SIGINT", onSigInt);
try { try {
const firstData = await pumpNewContent(dataPath, dataState, roleFilter, cas); await mkdir(dirname(target.threadsJsonPath), { recursive: true });
if (firstData === 1) {
return 1;
}
const firstData = await pumpThreadsJson({
storageRoot,
bundleDir: target.bundleDir,
bundleHash: target.bundleHash,
threadId: target.threadId,
state: dataState,
roleFilter,
cas,
});
const infoPath = join(storageRoot, "logs", target.bundleHash, `${target.threadId}.info.jsonl`);
if (parsed.debug && (await pathExists(infoPath))) { if (parsed.debug && (await pathExists(infoPath))) {
await pumpNewInfoContent(infoPath, infoState); await pumpNewInfoContent(infoPath, infoState);
} }
if (firstData === 0 || dataState.completed) { if (firstData === 0) {
return 0; return 0;
} }
const tasks = await buildLiveWatchTasks({ const tasks = await buildLiveWatchTasks({
dataPath, storageRoot,
infoPath, target,
debug: parsed.debug, debug: parsed.debug,
dataState, dataState,
infoState, infoState,
@@ -1,24 +1,35 @@
import { unlink } from "node:fs/promises"; import { unlink } from "node:fs/promises";
import { dirname, join } from "node:path"; import { join } from "node:path";
import { garbageCollectCas } from "@uncaged/workflow-execute"; import {
garbageCollectCas,
removeThreadEntry,
removeThreadHistoryEntries,
} from "@uncaged/workflow-execute";
import { err, ok, type Result } from "@uncaged/workflow-protocol"; import { err, ok, type Result } from "@uncaged/workflow-protocol";
import { resolveThreadDataPath } from "../../thread-scan.js"; import { resolveThreadRecord } from "../../thread-scan.js";
export async function cmdThreadRemove( export async function cmdThreadRemove(
storageRoot: string, storageRoot: string,
threadId: string, threadId: string,
): Promise<Result<void, string>> { ): Promise<Result<void, string>> {
const dataPath = await resolveThreadDataPath(storageRoot, threadId); const resolved = await resolveThreadRecord(storageRoot, threadId);
if (dataPath === null) { if (resolved === null) {
return err(`thread not found: ${threadId}`); return err(`thread not found: ${threadId}`);
} }
const dir = dirname(dataPath); if (resolved.source === "active") {
const infoPath = join(dir, `${threadId}.info.jsonl`); await removeThreadEntry(resolved.bundleDir, threadId);
const runningPath = join(dir, `${threadId}.running`); } else {
const hist = await removeThreadHistoryEntries(resolved.bundleDir, threadId);
if (!hist.ok) {
return hist;
}
}
const infoPath = join(storageRoot, "logs", resolved.bundleHash, `${threadId}.info.jsonl`);
const runningPath = join(storageRoot, "logs", resolved.bundleHash, `${threadId}.running`);
await unlink(dataPath);
await unlink(infoPath).catch(() => {}); await unlink(infoPath).catch(() => {});
await unlink(runningPath).catch(() => {}); await unlink(runningPath).catch(() => {});
@@ -1,19 +1,44 @@
import { createCasStore } from "@uncaged/workflow-cas";
import { FORK_BRANCH_ROLE, walkStateFramesNewestFirst } from "@uncaged/workflow-execute";
import { err, ok, type Result } from "@uncaged/workflow-protocol"; import { err, ok, type Result } from "@uncaged/workflow-protocol";
import { END } from "@uncaged/workflow-runtime";
import { getGlobalCasDir } from "@uncaged/workflow-util";
import { readTextFileIfExists } from "../../fs-utils.js"; import { resolveThreadRecord } from "../../thread-scan.js";
import { resolveThreadDataPath } from "../../thread-scan.js";
export async function cmdThreadShow( export async function cmdThreadShow(
storageRoot: string, storageRoot: string,
threadId: string, threadId: string,
): Promise<Result<string, string>> { ): Promise<Result<string, string>> {
const dataPath = await resolveThreadDataPath(storageRoot, threadId); const resolved = await resolveThreadRecord(storageRoot, threadId);
if (dataPath === null) { if (resolved === null) {
return err(`thread not found: ${threadId}`); return err(`thread not found: ${threadId}`);
} }
const text = await readTextFileIfExists(dataPath);
if (text === null) { const cas = createCasStore(getGlobalCasDir(storageRoot));
return err(`thread data missing: ${threadId}`); const frames = await walkStateFramesNewestFirst(cas, resolved.head);
const chronological = [...frames].reverse();
const steps: Array<{ role: string; hash: string; timestamp: number }> = [];
for (const fr of chronological) {
if (fr.payload.role === END || fr.payload.role === FORK_BRANCH_ROLE) {
continue;
} }
return ok(text.endsWith("\n") ? text.slice(0, -1) : text); steps.push({
role: fr.payload.role,
hash: fr.hash,
timestamp: fr.payload.timestamp,
});
}
const payload = {
threadId: resolved.threadId,
bundleHash: resolved.bundleHash,
head: resolved.head,
start: resolved.start,
source: resolved.source,
steps,
};
return ok(JSON.stringify(payload, null, 2));
} }
+259 -90
View File
@@ -1,23 +1,87 @@
import { readdir, stat } from "node:fs/promises"; import { readdir, stat } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { createCasStore, parseCasThreadNode } from "@uncaged/workflow-cas";
import {
readThreadsIndex,
type ThreadHistoryEntry,
type ThreadIndex,
} from "@uncaged/workflow-execute";
import { getGlobalCasDir } from "@uncaged/workflow-util";
import { pathExists, readTextFileIfExists } from "./fs-utils.js"; import { pathExists, readTextFileIfExists } from "./fs-utils.js";
function parseFirstJsonLineObject(text: string): Record<string, unknown> | null { async function readWorkflowNameFromStartHash(
const firstLine = text.split("\n")[0]; storageRoot: string,
if (firstLine === undefined || firstLine.trim() === "") { startHash: string,
): Promise<string | null> {
const cas = createCasStore(getGlobalCasDir(storageRoot));
const yamlText = await cas.get(startHash);
if (yamlText === null) {
return null; return null;
} }
let parsed: unknown; const parsed = parseCasThreadNode(yamlText);
if (parsed === null || parsed.kind !== "start") {
return null;
}
return parsed.node.payload.name;
}
async function listBundleHashDirs(storageRoot: string): Promise<string[]> {
const bundlesRoot = join(storageRoot, "bundles");
if (!(await pathExists(bundlesRoot))) {
return [];
}
const names = await readdir(bundlesRoot);
const out: string[] = [];
for (const name of names) {
const p = join(bundlesRoot, name);
try { try {
parsed = JSON.parse(firstLine) as unknown; const st = await stat(p);
if (st.isDirectory()) {
out.push(name);
}
} catch {}
}
out.sort();
return out;
}
async function parseHistoryFile(path: string): Promise<ThreadHistoryEntry[]> {
const text = await readTextFileIfExists(path);
if (text === null) {
return [];
}
const out: ThreadHistoryEntry[] = [];
for (const line of text.split("\n")) {
const trimmed = line.trim();
if (trimmed === "") {
continue;
}
let raw: unknown;
try {
raw = JSON.parse(trimmed) as unknown;
} catch { } catch {
return null; continue;
} }
if (parsed === null || typeof parsed !== "object") { if (raw === null || typeof raw !== "object") {
return null; continue;
} }
return parsed as Record<string, unknown>; const rec = raw as Record<string, unknown>;
const threadId = rec.threadId;
const head = rec.head;
const start = rec.start;
const completedAt = rec.completedAt;
if (
typeof threadId !== "string" ||
typeof head !== "string" ||
typeof start !== "string" ||
typeof completedAt !== "number"
) {
continue;
}
out.push({ threadId, head, start, completedAt });
}
return out;
} }
export type RunningThreadRow = { export type RunningThreadRow = {
@@ -32,30 +96,76 @@ export type HistoricalThreadRow = {
workflowName: string | null; workflowName: string | null;
}; };
async function readThreadStartTimestampMs(dataPath: string): Promise<number | null> { export type ResolvedThreadRecord = {
const text = await readTextFileIfExists(dataPath); threadId: string;
if (text === null) { bundleHash: string;
return null; bundleDir: string;
} head: string;
const parsed = parseFirstJsonLineObject(text); start: string;
if (parsed === null) { source: "active" | "history";
return null; };
}
const ts = parsed.timestamp;
return typeof ts === "number" && Number.isFinite(ts) ? ts : null;
}
async function readWorkflowNameFromDataJsonl(dataPath: string): Promise<string | null> { /** Resolve a thread via `threads.json` (active) or `history/*.jsonl` (completed). */
const text = await readTextFileIfExists(dataPath); // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: scans all bundle dirs for thread id
if (text === null) { export async function resolveThreadRecord(
return null; storageRoot: string,
threadId: string,
): Promise<ResolvedThreadRecord | null> {
const hashes = await listBundleHashDirs(storageRoot);
for (const bundleHash of hashes) {
const bundleDir = join(storageRoot, "bundles", bundleHash);
let index: ThreadIndex;
try {
index = await readThreadsIndex(bundleDir);
} catch {
continue;
} }
const parsed = parseFirstJsonLineObject(text); const active = index[threadId];
if (parsed === null) { if (active !== undefined) {
return null; return {
threadId,
bundleHash,
bundleDir,
head: active.head,
start: active.start,
source: "active",
};
} }
const name = parsed.name; }
return typeof name === "string" ? name : null;
for (const bundleHash of hashes) {
const bundleDir = join(storageRoot, "bundles", bundleHash);
const histDir = join(bundleDir, "history");
if (!(await pathExists(histDir))) {
continue;
}
let files: string[];
try {
files = await readdir(histDir);
} catch {
continue;
}
for (const name of files) {
if (!name.endsWith(".jsonl")) {
continue;
}
const entries = await parseHistoryFile(join(histDir, name));
for (const e of entries) {
if (e.threadId === threadId) {
return {
threadId,
bundleHash,
bundleDir,
head: e.head,
start: e.start,
source: "history",
};
}
}
}
}
return null;
} }
/** Threads currently executing — identified via `<threadId>.running` markers. */ /** Threads currently executing — identified via `<threadId>.running` markers. */
@@ -82,8 +192,9 @@ export async function listRunningThreads(storageRoot: string): Promise<RunningTh
continue; continue;
} }
const threadId = fileName.slice(0, -".running".length); const threadId = fileName.slice(0, -".running".length);
const dataPath = join(dir, `${threadId}.data.jsonl`); const resolved = await resolveThreadRecord(storageRoot, threadId);
const workflowName = await readWorkflowNameFromDataJsonl(dataPath); const workflowName =
resolved !== null ? await readWorkflowNameFromStartHash(storageRoot, resolved.start) : null;
out.push({ threadId, hash, workflowName }); out.push({ threadId, hash, workflowName });
} }
} }
@@ -98,41 +209,70 @@ export async function listRunningThreads(storageRoot: string): Promise<RunningTh
} }
/** /**
* Historical threads discovered via `*.data.jsonl`. * Threads discovered via `threads.json` (active) and `history/*.jsonl` (completed).
* When `workflowNameFilter` is non-null, only threads whose start record `name` matches are returned. * When `workflowNameFilter` is non-null, only threads whose StartNode `name` matches are returned.
*/ */
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: merges active index + partitioned history
export async function listHistoricalThreads( export async function listHistoricalThreads(
storageRoot: string, storageRoot: string,
workflowNameFilter: string | null, workflowNameFilter: string | null,
): Promise<HistoricalThreadRow[]> { ): Promise<HistoricalThreadRow[]> {
const logsRoot = join(storageRoot, "logs"); const hashes = await listBundleHashDirs(storageRoot);
if (!(await pathExists(logsRoot))) { const seen = new Set<string>();
return [];
}
const hashes = await readdir(logsRoot);
const out: HistoricalThreadRow[] = []; const out: HistoricalThreadRow[] = [];
for (const hash of hashes) { for (const bundleHash of hashes) {
const dir = join(logsRoot, hash); const bundleDir = join(storageRoot, "bundles", bundleHash);
let entries: string[]; let index: ThreadIndex;
try { try {
entries = await readdir(dir); index = await readThreadsIndex(bundleDir);
} catch { } catch {
continue; continue;
} }
for (const threadId of Object.keys(index)) {
for (const fileName of entries) { const key = `${bundleHash}/${threadId}`;
if (!fileName.endsWith(".data.jsonl")) { if (seen.has(key)) {
continue; continue;
} }
const threadId = fileName.slice(0, -".data.jsonl".length); seen.add(key);
const dataPath = join(dir, fileName); const entry = index[threadId];
const workflowName = await readWorkflowNameFromDataJsonl(dataPath); if (entry === undefined) {
continue;
}
const workflowName = await readWorkflowNameFromStartHash(storageRoot, entry.start);
if (workflowNameFilter !== null && workflowName !== workflowNameFilter) { if (workflowNameFilter !== null && workflowName !== workflowNameFilter) {
continue; continue;
} }
out.push({ threadId, hash, workflowName }); out.push({ threadId, hash: bundleHash, workflowName });
}
const histDir = join(bundleDir, "history");
if (!(await pathExists(histDir))) {
continue;
}
let files: string[];
try {
files = await readdir(histDir);
} catch {
continue;
}
for (const name of files) {
if (!name.endsWith(".jsonl")) {
continue;
}
const entries = await parseHistoryFile(join(histDir, name));
for (const e of entries) {
const key = `${bundleHash}/${e.threadId}`;
if (seen.has(key)) {
continue;
}
seen.add(key);
const workflowName = await readWorkflowNameFromStartHash(storageRoot, e.start);
if (workflowNameFilter !== null && workflowName !== workflowNameFilter) {
continue;
}
out.push({ threadId: e.threadId, hash: bundleHash, workflowName });
}
} }
} }
@@ -145,64 +285,93 @@ export async function listHistoricalThreads(
return out; return out;
} }
export type LatestThreadTarget = {
threadId: string;
bundleHash: string;
bundleDir: string;
threadsJsonPath: string;
};
/** /**
* Picks the thread whose `.data.jsonl` is newest by start-record `timestamp`, * Picks the newest thread by StartNode timestamp approximation (`updatedAt` active,
* falling back to file `mtime` when the timestamp is missing. * else `completedAt` history), falling back to lexical thread id order.
* Tie-breaker: larger `mtime` wins when start timestamps are equal.
*/ */
export async function findLatestThreadDataPath( // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: compares active heads vs history tails
export async function findLatestThreadBundleTarget(
storageRoot: string, storageRoot: string,
): Promise<{ threadId: string; dataPath: string } | null> { ): Promise<LatestThreadTarget | null> {
const threads = await listHistoricalThreads(storageRoot, null); const hashes = await listBundleHashDirs(storageRoot);
if (threads.length === 0) {
return null;
}
let best: { let best: {
threadId: string; threadId: string;
dataPath: string; bundleHash: string;
primary: number; bundleDir: string;
secondary: number; ts: number;
} | null = null; } | null = null;
for (const t of threads) { for (const bundleHash of hashes) {
const dataPath = join(storageRoot, "logs", t.hash, `${t.threadId}.data.jsonl`); const bundleDir = join(storageRoot, "bundles", bundleHash);
let mtimeMs = 0; let index: ThreadIndex;
try { try {
const st = await stat(dataPath); index = await readThreadsIndex(bundleDir);
mtimeMs = st.mtimeMs;
} catch { } catch {
continue; continue;
} }
const startTs = await readThreadStartTimestampMs(dataPath); for (const threadId of Object.keys(index)) {
const primary = startTs !== null ? startTs : mtimeMs; const ent = index[threadId];
const secondary = mtimeMs; if (ent === undefined) {
continue;
}
const ts = ent.updatedAt;
const cand = { threadId, bundleHash, bundleDir, ts };
if ( if (
best === null || best === null ||
primary > best.primary || cand.ts > best.ts ||
(primary === best.primary && secondary > best.secondary) (cand.ts === best.ts &&
`${cand.bundleHash}/${cand.threadId}` > `${best.bundleHash}/${best.threadId}`)
) { ) {
best = { threadId: t.threadId, dataPath, primary, secondary }; best = cand;
} }
} }
return best === null ? null : { threadId: best.threadId, dataPath: best.dataPath }; const histDir = join(bundleDir, "history");
} if (!(await pathExists(histDir))) {
continue;
}
let files: string[];
try {
files = await readdir(histDir);
} catch {
continue;
}
for (const name of files) {
if (!name.endsWith(".jsonl")) {
continue;
}
const entries = await parseHistoryFile(join(histDir, name));
for (const e of entries) {
const ts = e.completedAt;
const cand = { threadId: e.threadId, bundleHash, bundleDir, ts };
if (
best === null ||
cand.ts > best.ts ||
(cand.ts === best.ts &&
`${cand.bundleHash}/${cand.threadId}` > `${best.bundleHash}/${best.threadId}`)
) {
best = cand;
}
}
}
}
export async function resolveThreadDataPath( if (best === null) {
storageRoot: string,
threadId: string,
): Promise<string | null> {
const logsRoot = join(storageRoot, "logs");
if (!(await pathExists(logsRoot))) {
return null; return null;
} }
const hashes = await readdir(logsRoot);
for (const hash of hashes) { return {
const candidate = join(logsRoot, hash, `${threadId}.data.jsonl`); threadId: best.threadId,
if (await pathExists(candidate)) { bundleHash: best.bundleHash,
return candidate; bundleDir: best.bundleDir,
} threadsJsonPath: join(best.bundleDir, "threads.json"),
} };
return null;
} }
@@ -40,6 +40,8 @@ function makeOptions(overrides: Partial<ExecuteThreadOptions>): ExecuteThreadOpt
awaitAfterEachYield: async () => {}, awaitAfterEachYield: async () => {},
forkSourceThreadId: null, forkSourceThreadId: null,
prefilledDiskSteps: null, prefilledDiskSteps: null,
forkContinuation: null,
replayTimestamps: null,
storageRoot: "/tmp/never", storageRoot: "/tmp/never",
...overrides, ...overrides,
}; };
@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, test } from "bun:test";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
createCasStore,
putContentNodeWithRefs,
putStartNode,
putStateNode,
} from "@uncaged/workflow-cas";
import type { StateNodePayload } from "@uncaged/workflow-protocol";
import { FORK_BRANCH_ROLE } from "../src/engine/fork-thread.js";
import { garbageCollectCas } from "../src/engine/gc.js";
import { getBundleDir, removeThreadEntry, upsertThreadEntry } from "../src/engine/threads-index.js";
describe("garbageCollectCas (mark-and-sweep)", () => {
let storageRoot: string;
let casDir: string;
beforeEach(async () => {
storageRoot = await mkdtemp(join(tmpdir(), "uncaged-wf-gc-ms-"));
casDir = join(storageRoot, "cas");
await mkdir(casDir, { recursive: true });
await writeFile(
join(storageRoot, "workflow.yaml"),
"config:\n maxDepth: 1\n supervisorInterval: 0\n providers: {}\n models: {}\nworkflows: {}\n",
"utf8",
);
});
afterEach(async () => {
await rm(storageRoot, { recursive: true, force: true });
});
test("shared CAS prefix survives when one fork thread index entry is removed", async () => {
const bundleHash = "TESTGC0000001";
const bundleDir = getBundleDir(storageRoot, bundleHash);
await mkdir(bundleDir, { recursive: true });
const cas = createCasStore(casDir);
const promptHash = await cas.put("prompt");
const startHash = await putStartNode(
cas,
{
name: "demo",
hash: bundleHash,
maxRounds: 5,
depth: 0,
},
promptHash,
);
const c1 = await putContentNodeWithRefs(cas, "p1", []);
const h1 = await putStateNode(cas, {
role: "planner",
meta: {},
start: startHash,
content: c1,
ancestors: [],
compact: null,
timestamp: 1,
} satisfies StateNodePayload);
const c2 = await putContentNodeWithRefs(cas, "c1", []);
const h2 = await putStateNode(cas, {
role: "coder",
meta: {},
start: startHash,
content: c2,
ancestors: [h1],
compact: null,
timestamp: 2,
} satisfies StateNodePayload);
const ec = await putContentNodeWithRefs(cas, "", []);
const fm = await putStateNode(cas, {
role: FORK_BRANCH_ROLE,
meta: {},
start: startHash,
content: ec,
ancestors: [h1],
compact: null,
timestamp: 3,
} satisfies StateNodePayload);
await upsertThreadEntry(bundleDir, "THREAD_AAAAAAA", {
head: h2,
start: startHash,
updatedAt: 10,
});
await upsertThreadEntry(bundleDir, "THREAD_BBBBBBB", {
head: fm,
start: startHash,
updatedAt: 20,
});
await removeThreadEntry(bundleDir, "THREAD_AAAAAAA");
const gc = await garbageCollectCas(storageRoot);
expect(gc.ok).toBe(true);
if (!gc.ok) {
return;
}
expect(await cas.get(h2)).toBeNull();
expect(await cas.get(h1)).not.toBeNull();
expect(await cas.get(startHash)).not.toBeNull();
expect(await cas.get(promptHash)).not.toBeNull();
expect(await cas.get(fm)).not.toBeNull();
});
});
+25 -13
View File
@@ -33,20 +33,12 @@ import {
removeThreadEntry, removeThreadEntry,
upsertThreadEntry, upsertThreadEntry,
} from "./threads-index.js"; } from "./threads-index.js";
import type { ExecuteThreadIo, ExecuteThreadOptions } from "./types.js"; import type { ChainState, ExecuteThreadIo, ExecuteThreadOptions } from "./types.js";
import { EMPTY_CHAIN_STATE } from "./types.js";
/** Cap for {@link StateNode}.payload.ancestors: 1 parent + 10 skip-list. */ /** Cap for {@link StateNode}.payload.ancestors: 1 parent + 10 skip-list. */
const ANCESTORS_CAP = 11; const ANCESTORS_CAP = 11;
type ChainState = {
/** State hash of the most recently written {@link StateNode}, or `null` before the first step. */
parentStateHash: string | null;
/** Ancestors recorded on the most recently written {@link StateNode}. */
parentAncestors: readonly string[];
};
const EMPTY_CHAIN: ChainState = { parentStateHash: null, parentAncestors: [] };
function computeAncestors(chain: ChainState): string[] { function computeAncestors(chain: ChainState): string[] {
if (chain.parentStateHash === null) { if (chain.parentStateHash === null) {
return []; return [];
@@ -408,16 +400,35 @@ export async function executeThread(
await mkdir(dirname(io.infoJsonlPath), { recursive: true }); await mkdir(dirname(io.infoJsonlPath), { recursive: true });
const prefilled = options.prefilledDiskSteps; const prefilled = options.prefilledDiskSteps;
const fork = options.forkContinuation;
if (fork !== null && prefilled !== null) {
throw new Error("forkContinuation and prefilledDiskSteps cannot both be set");
}
if (prefilled !== null && prefilled.length !== input.steps.length) { if (prefilled !== null && prefilled.length !== input.steps.length) {
throw new Error( throw new Error(
`prefilledDiskSteps length (${prefilled.length}) must match input.steps length (${input.steps.length})`, `prefilledDiskSteps length (${prefilled.length}) must match input.steps length (${input.steps.length})`,
); );
} }
const replayTs = options.replayTimestamps;
if (replayTs !== null && replayTs.length !== input.steps.length) {
throw new Error(
`replayTimestamps length (${replayTs.length}) must match input.steps length (${input.steps.length})`,
);
}
const bundleDir = getBundleDir(options.storageRoot, io.hash); const bundleDir = getBundleDir(options.storageRoot, io.hash);
let startHash: string;
if (fork !== null) {
startHash = fork.startHash;
logger("T9HQ2KHM", `thread ${io.threadId} continued fork for workflow ${workflowName}`);
} else {
const promptHash = await io.cas.put(input.prompt); const promptHash = await io.cas.put(input.prompt);
const startHash = await putStartNode( startHash = await putStartNode(
io.cas, io.cas,
{ {
name: workflowName, name: workflowName,
@@ -436,8 +447,9 @@ export async function executeThread(
}); });
logger("T9HQ2KHM", `thread ${io.threadId} started for workflow ${workflowName}`); logger("T9HQ2KHM", `thread ${io.threadId} started for workflow ${workflowName}`);
}
let chain: ChainState = EMPTY_CHAIN; let chain: ChainState = fork !== null ? fork.initialChain : EMPTY_CHAIN_STATE;
if (prefilled !== null) { if (prefilled !== null) {
for (const row of prefilled) { for (const row of prefilled) {
@@ -497,7 +509,7 @@ export async function executeThread(
contentHash: out.contentHash, contentHash: out.contentHash,
meta: out.meta, meta: out.meta,
refs: out.refs, refs: out.refs,
timestamp: prefilled?.[i]?.timestamp ?? nowMs + i, timestamp: replayTs?.[i] ?? prefilled?.[i]?.timestamp ?? nowMs + i,
})), })),
}; };
@@ -1,9 +1,29 @@
import type { WorkflowCompletion } from "@uncaged/workflow-runtime"; import type { CasStore } from "@uncaged/workflow-cas";
import { err, normalizeRefsField, ok, type Result } from "@uncaged/workflow-util"; import { parseCasThreadNode, putContentNodeWithRefs, putStateNode } from "@uncaged/workflow-cas";
import type { StateNodePayload } from "@uncaged/workflow-protocol";
import type { RoleOutput, WorkflowCompletion } from "@uncaged/workflow-runtime";
import { END } from "@uncaged/workflow-runtime";
import { err, ok, type Result } from "@uncaged/workflow-util";
import { parse as parseYaml } from "yaml";
import type { ForkHistoricalStep, ForkPlan, ParsedThreadStartRecord } from "./types.js"; import { upsertThreadEntry } from "./threads-index.js";
import type { CasForkPlan, ChainState, ForkContinuationOptions } from "./types.js";
import { EMPTY_CHAIN_STATE } from "./types.js";
/** Recognizes a persisted workflow completion line (no `role`; has numeric `returnCode` and string `summary`). Omits `rootHash` when absent. */ /** Internal branch marker; skipped when presenting fork selection / replay slices. */
export const FORK_BRANCH_ROLE = "__fork__";
/** Cap for {@link StateNodePayload}.ancestors: 1 parent + 10 skip-list. */
const ANCESTORS_CAP = 11;
function computeAncestors(chain: ChainState): string[] {
if (chain.parentStateHash === null) {
return [];
}
return [chain.parentStateHash, ...chain.parentAncestors].slice(0, ANCESTORS_CAP);
}
/** Recognizes a persisted workflow completion line (no `role`; has numeric `returnCode` and string `summary`). */
export function tryParseWorkflowResultRecord( export function tryParseWorkflowResultRecord(
obj: Record<string, unknown>, obj: Record<string, unknown>,
): WorkflowCompletion | null { ): WorkflowCompletion | null {
@@ -18,227 +38,288 @@ export function tryParseWorkflowResultRecord(
return { returnCode, summary }; return { returnCode, summary };
} }
export function tryParseRoleStepRecord(obj: Record<string, unknown>): ForkHistoricalStep | null { /** Walk {@link StateNode} hashes from head toward the first step (newest → oldest). */
const role = obj.role; export async function walkStateFramesNewestFirst(
const contentHash = obj.contentHash; cas: CasStore,
const meta = obj.meta; headHash: string,
const timestamp = obj.timestamp; ): Promise<Array<{ hash: string; payload: StateNodePayload }>> {
if (typeof role !== "string") { const frames: Array<{ hash: string; payload: StateNodePayload }> = [];
return null; let cur = headHash;
} while (true) {
if (typeof contentHash !== "string") { const yamlText = await cas.get(cur);
return null; if (yamlText === null) {
}
if (meta === null || typeof meta !== "object") {
return null;
}
if (typeof timestamp !== "number") {
return null;
}
return {
role,
contentHash,
meta: meta as Record<string, unknown>,
refs: normalizeRefsField(obj.refs),
timestamp,
};
}
function parseRoleLine(
obj: Record<string, unknown>,
lineIndex: number,
): Result<ForkHistoricalStep, string> {
const parsed = tryParseRoleStepRecord(obj);
if (parsed === null) {
return err(`invalid role record at line ${lineIndex}`);
}
return ok(parsed);
}
function parseStartRecordLine(firstLine: string): Result<ParsedThreadStartRecord, string> {
let startParsed: unknown;
try {
startParsed = JSON.parse(firstLine) as unknown;
} catch {
return err("invalid JSON on line 1 (start record)");
}
if (startParsed === null || typeof startParsed !== "object") {
return err("invalid start record shape");
}
const startRec = startParsed as Record<string, unknown>;
const name = startRec.name;
const hash = startRec.hash;
const threadId = startRec.threadId;
const parameters = startRec.parameters;
if (typeof name !== "string" || typeof hash !== "string" || typeof threadId !== "string") {
return err("start record missing name, hash, or threadId");
}
if (parameters === null || typeof parameters !== "object") {
return err("start record missing parameters");
}
const paramsRec = parameters as Record<string, unknown>;
const prompt = paramsRec.prompt;
const options = paramsRec.options;
if (typeof prompt !== "string") {
return err("start record missing parameters.prompt");
}
if (options === null || typeof options !== "object") {
return err("start record missing parameters.options");
}
const optRec = options as Record<string, unknown>;
const maxRounds = optRec.maxRounds;
if (typeof maxRounds !== "number") {
return err("start record missing parameters.options.maxRounds");
}
const depthRaw = optRec.depth;
const depth =
typeof depthRaw === "number" && Number.isFinite(depthRaw) ? Math.trunc(depthRaw) : 0;
return ok({
workflowName: name,
hash,
threadId,
prompt,
maxRounds,
depth,
});
}
function parseFollowingRoleLines(lines: string[]): Result<ForkHistoricalStep[], string> {
const roleSteps: ForkHistoricalStep[] = [];
for (let i = 1; i < lines.length; i++) {
const line = lines[i];
if (line === undefined) {
break; break;
} }
let rec: unknown; const parsed = parseCasThreadNode(yamlText);
try { if (parsed === null || parsed.kind !== "state") {
rec = JSON.parse(line) as unknown;
} catch {
return err(`invalid JSON at line ${i + 1}`);
}
if (rec === null || typeof rec !== "object") {
return err(`invalid record at line ${i + 1}`);
}
const recObj = rec as Record<string, unknown>;
const wf = tryParseWorkflowResultRecord(recObj);
if (wf !== null) {
if (i !== lines.length - 1) {
return err("WorkflowResult record must be the final line in `.data.jsonl`");
}
break; break;
} }
const parsed = parseRoleLine(recObj, i + 1); frames.push({ hash: cur, payload: parsed.node.payload });
if (!parsed.ok) { const ancestors = parsed.node.payload.ancestors;
return parsed; if (ancestors.length === 0) {
break;
} }
roleSteps.push(parsed.value); const parent = ancestors[0];
if (parent === undefined || parent === "") {
break;
} }
return ok(roleSteps); cur = parent;
}
return frames;
} }
/** function orderedUniqueRoles(roles: string[]): string[] {
* Parse RFC-001 `.data.jsonl`: line 1 start record, line 2+ role outputs.
*/
export function parseThreadDataJsonl(text: string): Result<
{
start: ParsedThreadStartRecord;
roleSteps: ForkHistoricalStep[];
},
string
> {
const lines = text
.split("\n")
.map((l) => l.trim())
.filter((l) => l !== "");
if (lines.length === 0) {
return err("thread data is empty");
}
const firstLine = lines[0];
if (firstLine === undefined) {
return err("thread data is empty");
}
const start = parseStartRecordLine(firstLine);
if (!start.ok) {
return start;
}
const roleSteps = parseFollowingRoleLines(lines);
if (!roleSteps.ok) {
return roleSteps;
}
return ok({
start: start.value,
roleSteps: roleSteps.value,
});
}
function orderedUniqueRoles(roleSteps: ForkHistoricalStep[]): string[] {
const seen = new Set<string>(); const seen = new Set<string>();
const out: string[] = []; const out: string[] = [];
for (const s of roleSteps) { for (const r of roles) {
if (!seen.has(s.role)) { if (!seen.has(r)) {
seen.add(s.role); seen.add(r);
out.push(s.role); out.push(r);
} }
} }
return out; return out;
} }
/** async function readPromptText(cas: CasStore, promptHash: string): Promise<Result<string, string>> {
* Select historical steps for a fork: const yamlText = await cas.get(promptHash);
* - `fromRole === null`: drop the last step (retry the last role). if (yamlText === null) {
* - `fromRole !== null`: keep steps through the first occurrence of that role (inclusive). return err(`prompt CAS blob missing: ${promptHash}`);
*/ }
export function selectForkHistoricalSteps( let raw: unknown;
roleSteps: ForkHistoricalStep[], try {
raw = parseYaml(yamlText) as unknown;
} catch {
return err(`prompt CAS blob is not valid YAML: ${promptHash}`);
}
if (raw === null || typeof raw !== "object") {
return err(`prompt CAS blob has unexpected shape: ${promptHash}`);
}
const payload = (raw as Record<string, unknown>).payload;
if (typeof payload !== "string") {
return err(`prompt CAS blob missing string payload: ${promptHash}`);
}
return ok(payload);
}
async function readStartWorkflowIdentity(params: {
cas: CasStore;
startHash: string;
}): Promise<
Result<{ workflowName: string; maxRounds: number; depth: number; prompt: string }, string>
> {
const yamlText = await params.cas.get(params.startHash);
if (yamlText === null) {
return err(`start node missing in CAS: ${params.startHash}`);
}
const parsed = parseCasThreadNode(yamlText);
if (parsed === null || parsed.kind !== "start") {
return err(`CAS blob is not a StartNode: ${params.startHash}`);
}
const refs = parsed.node.refs;
const promptHash = refs[0];
if (typeof promptHash !== "string") {
return err("StartNode refs[0] must be the prompt hash");
}
const prompt = await readPromptText(params.cas, promptHash);
if (!prompt.ok) {
return prompt;
}
const p = parsed.node.payload;
return ok({
workflowName: p.name,
maxRounds: p.maxRounds,
depth: p.depth,
prompt: prompt.value,
});
}
async function payloadToRoleOutput(cas: CasStore, payload: StateNodePayload): Promise<RoleOutput> {
let refs: string[] = [];
const blob = await cas.get(payload.content);
if (blob !== null) {
const cn = parseCasThreadNode(blob);
if (cn?.kind === "content") {
refs = [...cn.node.refs];
}
}
return {
role: payload.role,
contentHash: payload.content,
meta: payload.meta,
refs,
};
}
function meaningfulFramesOldestFirst(
newestFirst: Array<{ hash: string; payload: StateNodePayload }>,
): Array<{ hash: string; payload: StateNodePayload }> {
const chronological = [...newestFirst].reverse();
return chronological.filter((f) => f.payload.role !== END && f.payload.role !== FORK_BRANCH_ROLE);
}
function selectForkPointStateHash(
meaningfulOldestFirst: Array<{ hash: string; payload: StateNodePayload }>,
fromRole: string | null, fromRole: string | null,
): Result<ForkHistoricalStep[], string> { ): Result<string | null, string> {
if (roleSteps.length === 0) { if (meaningfulOldestFirst.length === 0) {
return err("thread has no completed role steps to fork from"); return err("thread has no completed role steps to fork from");
} }
if (fromRole === null) { if (fromRole === null) {
if (roleSteps.length === 1) { if (meaningfulOldestFirst.length === 1) {
return ok([]); return ok(null);
} }
return ok(roleSteps.slice(0, -1)); const forkFrame = meaningfulOldestFirst[meaningfulOldestFirst.length - 2];
if (forkFrame === undefined) {
return err("thread has no completed role steps to fork from");
}
return ok(forkFrame.hash);
} }
const idx = roleSteps.findIndex((s) => s.role === fromRole); const idx = meaningfulOldestFirst.findIndex((f) => f.payload.role === fromRole);
if (idx < 0) { if (idx < 0) {
const available = orderedUniqueRoles(roleSteps); const available = orderedUniqueRoles(meaningfulOldestFirst.map((f) => f.payload.role));
return err(`role not found in thread: ${fromRole} (available: ${available.join(", ")})`); return err(`role not found in thread: ${fromRole} (available: ${available.join(", ")})`);
} }
return ok(roleSteps.slice(0, idx + 1)); const forkFrame = meaningfulOldestFirst[idx];
if (forkFrame === undefined) {
return err("fork frame missing");
}
return ok(forkFrame.hash);
}
function replayFramesThroughForkPoint(
meaningfulOldestFirst: Array<{ hash: string; payload: StateNodePayload }>,
forkPointHash: string | null,
): Array<{ hash: string; payload: StateNodePayload }> {
if (forkPointHash === null) {
return [];
}
const idx = meaningfulOldestFirst.findIndex((f) => f.hash === forkPointHash);
if (idx < 0) {
return [];
}
return meaningfulOldestFirst.slice(0, idx + 1);
}
async function buildForkContinuation(params: {
cas: CasStore;
sourceThreadId: string;
startHash: string;
forkPointStateHash: string | null;
}): Promise<Result<ForkContinuationOptions, string>> {
const { cas, sourceThreadId, startHash, forkPointStateHash } = params;
if (forkPointStateHash === null) {
return ok({
startHash,
forkHeadHash: startHash,
initialChain: EMPTY_CHAIN_STATE,
});
}
const yamlText = await cas.get(forkPointStateHash);
if (yamlText === null) {
return err(`fork point state missing in CAS: ${forkPointStateHash}`);
}
const parsed = parseCasThreadNode(yamlText);
if (parsed === null || parsed.kind !== "state") {
return err(`fork point blob is not a StateNode: ${forkPointStateHash}`);
}
const fpPayload = parsed.node.payload;
const chainBefore: ChainState = {
parentStateHash: forkPointStateHash,
parentAncestors: fpPayload.ancestors,
};
const ancestorsMarker = computeAncestors(chainBefore);
const emptyContentHash = await putContentNodeWithRefs(cas, "", []);
const markerPayload: StateNodePayload = {
role: FORK_BRANCH_ROLE,
meta: { forkFrom: sourceThreadId },
start: startHash,
content: emptyContentHash,
ancestors: ancestorsMarker,
compact: null,
timestamp: Date.now(),
};
const markerHash = await putStateNode(cas, markerPayload);
const initialChain: ChainState = {
parentStateHash: markerHash,
parentAncestors: ancestorsMarker,
};
return ok({
startHash,
forkHeadHash: markerHash,
initialChain,
});
} }
/** /**
* Read `.data.jsonl` text and compute fork payload for the worker `run` command. * Prepare a CAS fork: writes the branch marker {@link StateNode}, registers `threads.json`,
* and returns worker payload fields (shared {@link StartNode}, zero ancestor duplication).
*/ */
export function buildForkPlan( export async function prepareCasFork(params: {
dataJsonlText: string, cas: CasStore;
fromRole: string | null, bundleDir: string;
): Result<ForkPlan, string> { bundleHash: string;
const parsed = parseThreadDataJsonl(dataJsonlText); sourceThreadId: string;
if (!parsed.ok) { headHash: string;
return parsed; startHash: string;
newThreadId: string;
fromRole: string | null;
}): Promise<Result<CasForkPlan, string>> {
const id = await readStartWorkflowIdentity({
cas: params.cas,
startHash: params.startHash,
});
if (!id.ok) {
return id;
} }
const selected = selectForkHistoricalSteps(parsed.value.roleSteps, fromRole);
if (!selected.ok) { const newestFirst = await walkStateFramesNewestFirst(params.cas, params.headHash);
return selected; const meaningful = meaningfulFramesOldestFirst(newestFirst);
const forkPoint = selectForkPointStateHash(meaningful, params.fromRole);
if (!forkPoint.ok) {
return forkPoint;
} }
const { start } = parsed.value;
const replayFrames = replayFramesThroughForkPoint(meaningful, forkPoint.value);
const steps: RoleOutput[] = [];
const stepTimestamps: number[] = [];
for (const fr of replayFrames) {
steps.push(await payloadToRoleOutput(params.cas, fr.payload));
stepTimestamps.push(fr.payload.timestamp);
}
const cont = await buildForkContinuation({
cas: params.cas,
sourceThreadId: params.sourceThreadId,
startHash: params.startHash,
forkPointStateHash: forkPoint.value,
});
if (!cont.ok) {
return cont;
}
await upsertThreadEntry(params.bundleDir, params.newThreadId, {
head: cont.value.forkHeadHash,
start: params.startHash,
updatedAt: Date.now(),
});
return ok({ return ok({
workflowName: start.workflowName, workflowName: id.value.workflowName,
hash: start.hash, hash: params.bundleHash,
sourceThreadId: start.threadId, sourceThreadId: params.sourceThreadId,
prompt: start.prompt, prompt: id.value.prompt,
runOptions: { maxRounds: start.maxRounds, depth: start.depth }, runOptions: { maxRounds: id.value.maxRounds, depth: id.value.depth },
historicalSteps: selected.value, steps,
stepTimestamps,
forkContinuation: cont.value,
}); });
} }
+128 -68
View File
@@ -1,122 +1,182 @@
import { readdir, readFile } from "node:fs/promises"; import type { Stats } from "node:fs";
import { readdir, readFile, stat } from "node:fs/promises";
import { join } from "node:path"; import { join } from "node:path";
import { type CasStore, createCasStore } from "@uncaged/workflow-cas"; import { type CasStore, createCasStore, findReachableHashes } from "@uncaged/workflow-cas";
import { err, getGlobalCasDir, ok, type Result } from "@uncaged/workflow-util"; import { err, getGlobalCasDir, ok, type Result } from "@uncaged/workflow-util";
import { parseThreadDataJsonl } from "./fork-thread.js";
import type { ThreadHistoryEntry, ThreadIndex } from "./threads-index.js";
import { readThreadsIndex } from "./threads-index.js";
import type { GcResult } from "./types.js"; import type { GcResult } from "./types.js";
async function listThreadDataJsonlPaths(storageRoot: string): Promise<Result<string[], string>> { function isPlainObject(v: unknown): v is Record<string, unknown> {
const logsRoot = join(storageRoot, "logs"); return v !== null && typeof v === "object" && !Array.isArray(v);
const paths: string[] = []; }
let hashes: string[];
function parseHistoryLine(jsonLine: string): ThreadHistoryEntry | null {
let raw: unknown;
try { try {
hashes = await readdir(logsRoot); raw = JSON.parse(jsonLine) as unknown;
} catch {
return null;
}
if (!isPlainObject(raw)) {
return null;
}
const threadId = raw.threadId;
const head = raw.head;
const start = raw.start;
const completedAt = raw.completedAt;
if (
typeof threadId !== "string" ||
typeof head !== "string" ||
typeof start !== "string" ||
typeof completedAt !== "number"
) {
return null;
}
return { threadId, head, start, completedAt };
}
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: walks threads index + optional history dir
async function collectGcRootsFromBundle(bundleDir: string): Promise<Result<string[], string>> {
const roots: string[] = [];
let activeIndex: ThreadIndex;
try {
activeIndex = await readThreadsIndex(bundleDir);
} catch (e) {
return err(`failed to read threads.json under ${bundleDir}: ${String(e)}`);
}
for (const entry of Object.values(activeIndex)) {
roots.push(entry.head);
roots.push(entry.start);
}
const histDir = join(bundleDir, "history");
let histFiles: string[];
try {
histFiles = await readdir(histDir);
} catch (e) {
const errObj = e as NodeJS.ErrnoException;
if (errObj.code === "ENOENT") {
return ok(roots);
}
return err(`failed to read history directory ${histDir}: ${String(e)}`);
}
for (const name of histFiles) {
if (!name.endsWith(".jsonl")) {
continue;
}
let text: string;
try {
text = await readFile(join(histDir, name), "utf8");
} catch (e) {
return err(`failed to read history file ${name}: ${String(e)}`);
}
for (const line of text.split("\n")) {
const trimmed = line.trim();
if (trimmed === "") {
continue;
}
const entry = parseHistoryLine(trimmed);
if (entry === null) {
continue;
}
roots.push(entry.head);
roots.push(entry.start);
}
}
return ok(roots);
}
async function collectAllGcRoots(storageRoot: string): Promise<Result<string[], string>> {
const bundlesRoot = join(storageRoot, "bundles");
let entries: string[];
try {
entries = await readdir(bundlesRoot);
} catch (e) { } catch (e) {
const errObj = e as NodeJS.ErrnoException; const errObj = e as NodeJS.ErrnoException;
if (errObj.code === "ENOENT") { if (errObj.code === "ENOENT") {
return ok([]); return ok([]);
} }
return err(`failed to read logs directory: ${String(e)}`); return err(`failed to read bundles directory: ${String(e)}`);
} }
for (const hash of hashes) { const roots: string[] = [];
const dir = join(logsRoot, hash); for (const name of entries) {
let entries: string[]; const bundleDir = join(bundlesRoot, name);
let st: Stats;
try { try {
entries = await readdir(dir); st = await stat(bundleDir);
} catch { } catch {
continue; continue;
} }
for (const fileName of entries) { if (!st.isDirectory()) {
if (fileName.endsWith(".data.jsonl")) { continue;
paths.push(join(dir, fileName));
} }
const chunk = await collectGcRootsFromBundle(bundleDir);
if (!chunk.ok) {
return chunk;
} }
roots.push(...chunk.value);
} }
paths.sort(); return ok(roots);
return ok(paths);
} }
async function collectActiveRefsFromDataPaths( async function deleteCasNotMarked(cas: CasStore, marked: ReadonlySet<string>): Promise<string[]> {
dataPaths: string[],
): Promise<Result<Set<string>, string>> {
const activeRefs = new Set<string>();
for (const dataPath of dataPaths) {
let text: string;
try {
text = await readFile(dataPath, "utf8");
} catch (e) {
return err(`failed to read ${dataPath}: ${String(e)}`);
}
const parsed = parseThreadDataJsonl(text);
if (!parsed.ok) {
return err(`${dataPath}: ${parsed.error}`);
}
for (const step of parsed.value.roleSteps) {
for (const ref of step.refs) {
activeRefs.add(ref);
}
}
}
return ok(activeRefs);
}
async function deleteCasNotInSet(
cas: CasStore,
activeRefs: Set<string>,
): Promise<Result<string[], string>> {
let listed: string[]; let listed: string[];
try { try {
listed = await cas.list(); listed = await cas.list();
} catch (e) { } catch (e) {
return err(`failed to list cas entries: ${String(e)}`); throw new Error(`failed to list cas entries: ${String(e)}`);
} }
const deletedHashes: string[] = []; const deletedHashes: string[] = [];
for (const hash of listed) { for (const hash of listed) {
if (activeRefs.has(hash)) { if (marked.has(hash)) {
continue; continue;
} }
try { try {
await cas.delete(hash); await cas.delete(hash);
} catch (e) { } catch (e) {
return err(`failed to delete cas ${hash}: ${String(e)}`); throw new Error(`failed to delete cas ${hash}: ${String(e)}`);
} }
deletedHashes.push(hash); deletedHashes.push(hash);
} }
deletedHashes.sort(); deletedHashes.sort();
return ok(deletedHashes); return deletedHashes;
} }
/** /**
* Mark-and-sweep CAS GC: collect `refs` from all thread `.data.jsonl` files under `storageRoot`, * Mark-and-sweep CAS GC: roots are every `head` / `start` hash from `threads.json` and
* then delete CAS blobs not referenced by any surviving thread data. * `history/*.jsonl` across bundle dirs; marks closure via `refs[]`; deletes unreachable blobs.
*/ */
export async function garbageCollectCas(storageRoot: string): Promise<Result<GcResult, string>> { export async function garbageCollectCas(storageRoot: string): Promise<Result<GcResult, string>> {
const pathsResult = await listThreadDataJsonlPaths(storageRoot); const rootsResult = await collectAllGcRoots(storageRoot);
if (!pathsResult.ok) { if (!rootsResult.ok) {
return pathsResult; return rootsResult;
} }
const paths = pathsResult.value; const roots = rootsResult.value;
const refsResult = await collectActiveRefsFromDataPaths(paths);
if (!refsResult.ok) {
return refsResult;
}
const activeRefs = refsResult.value;
const cas = createCasStore(getGlobalCasDir(storageRoot)); const cas = createCasStore(getGlobalCasDir(storageRoot));
const deletedResult = await deleteCasNotInSet(cas, activeRefs);
if (!deletedResult.ok) { const marked = await findReachableHashes(roots, cas);
return deletedResult;
let deletedHashes: string[];
try {
deletedHashes = await deleteCasNotMarked(cas, marked);
} catch (e) {
return err(String(e));
} }
const deletedHashes = deletedResult.value;
return ok({ return ok({
scannedThreads: paths.length, scannedThreads: roots.length,
activeRefs: activeRefs.size, activeRefs: marked.size,
deletedEntries: deletedHashes.length, deletedEntries: deletedHashes.length,
deletedHashes, deletedHashes,
}); });
+10 -7
View File
@@ -1,11 +1,10 @@
export { createWorkflow } from "./create-workflow.js"; export { createWorkflow } from "./create-workflow.js";
export { executeThread } from "./engine.js"; export { executeThread } from "./engine.js";
export { export {
buildForkPlan, FORK_BRANCH_ROLE,
parseThreadDataJsonl, prepareCasFork,
selectForkHistoricalSteps,
tryParseRoleStepRecord,
tryParseWorkflowResultRecord, tryParseWorkflowResultRecord,
walkStateFramesNewestFirst,
} from "./fork-thread.js"; } from "./fork-thread.js";
export { garbageCollectCas } from "./gc.js"; export { garbageCollectCas } from "./gc.js";
export { createThreadPauseGate } from "./thread-pause-gate.js"; export { createThreadPauseGate } from "./thread-pause-gate.js";
@@ -13,18 +12,22 @@ export type { ThreadHistoryEntry, ThreadIndex, ThreadIndexEntry } from "./thread
export { export {
appendThreadHistoryEntry, appendThreadHistoryEntry,
getBundleDir, getBundleDir,
readThreadsIndex,
removeThreadEntry, removeThreadEntry,
removeThreadHistoryEntries,
upsertThreadEntry, upsertThreadEntry,
writeThreadsIndex,
} from "./threads-index.js"; } from "./threads-index.js";
export type { export type {
CasForkPlan,
ChainState,
ExecuteThreadIo, ExecuteThreadIo,
ExecuteThreadOptions, ExecuteThreadOptions,
ForkHistoricalStep, ForkContinuationOptions,
ForkPlan,
GcResult, GcResult,
ParsedThreadStartRecord,
PrefilledDiskStep, PrefilledDiskStep,
SupervisorDecision, SupervisorDecision,
ThreadPauseGate, ThreadPauseGate,
} from "./types.js"; } from "./types.js";
export { EMPTY_CHAIN_STATE } from "./types.js";
export { getWorkerHostScriptPath } from "./worker-entry-path.js"; export { getWorkerHostScriptPath } from "./worker-entry-path.js";
@@ -1,6 +1,8 @@
import { appendFile, mkdir, readFile, rename, writeFile } from "node:fs/promises"; import { appendFile, mkdir, readdir, readFile, rename, writeFile } from "node:fs/promises";
import { dirname, join } from "node:path"; import { dirname, join } from "node:path";
import { err, ok, type Result } from "@uncaged/workflow-util";
/** /**
* Active-thread index entry stored in `<bundleDir>/threads.json`. * Active-thread index entry stored in `<bundleDir>/threads.json`.
* *
@@ -71,7 +73,8 @@ function parseThreadIndex(text: string): ThreadIndex {
return out; return out;
} }
async function readThreadIndex(bundleDir: string): Promise<ThreadIndex> { /** Read `<bundleDir>/threads.json` (empty object when missing or invalid). */
export async function readThreadsIndex(bundleDir: string): Promise<ThreadIndex> {
const path = threadsJsonPath(bundleDir); const path = threadsJsonPath(bundleDir);
let text: string; let text: string;
try { try {
@@ -86,7 +89,7 @@ async function readThreadIndex(bundleDir: string): Promise<ThreadIndex> {
return parseThreadIndex(text); return parseThreadIndex(text);
} }
async function writeThreadIndex(bundleDir: string, index: ThreadIndex): Promise<void> { export async function writeThreadsIndex(bundleDir: string, index: ThreadIndex): Promise<void> {
const path = threadsJsonPath(bundleDir); const path = threadsJsonPath(bundleDir);
await mkdir(dirname(path), { recursive: true }); await mkdir(dirname(path), { recursive: true });
const tmp = `${path}.tmp.${process.pid}.${Date.now()}`; const tmp = `${path}.tmp.${process.pid}.${Date.now()}`;
@@ -101,19 +104,19 @@ export async function upsertThreadEntry(
threadId: string, threadId: string,
entry: ThreadIndexEntry, entry: ThreadIndexEntry,
): Promise<void> { ): Promise<void> {
const index = await readThreadIndex(bundleDir); const index = await readThreadsIndex(bundleDir);
index[threadId] = entry; index[threadId] = entry;
await writeThreadIndex(bundleDir, index); await writeThreadsIndex(bundleDir, index);
} }
/** Remove a thread entry from `threads.json` (no-op when absent). */ /** Remove a thread entry from `threads.json` (no-op when absent). */
export async function removeThreadEntry(bundleDir: string, threadId: string): Promise<void> { export async function removeThreadEntry(bundleDir: string, threadId: string): Promise<void> {
const index = await readThreadIndex(bundleDir); const index = await readThreadsIndex(bundleDir);
if (!(threadId in index)) { if (!(threadId in index)) {
return; return;
} }
delete index[threadId]; delete index[threadId];
await writeThreadIndex(bundleDir, index); await writeThreadsIndex(bundleDir, index);
} }
function dateKey(epochMs: number): string { function dateKey(epochMs: number): string {
@@ -134,3 +137,63 @@ export async function appendThreadHistoryEntry(
const line = `${JSON.stringify(entry)}\n`; const line = `${JSON.stringify(entry)}\n`;
await appendFile(path, line, "utf8"); await appendFile(path, line, "utf8");
} }
/** Removes every `history/*.jsonl` line whose `threadId` matches (rewrite files in place). */
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-file JSONL filtering keeps RM deterministic
export async function removeThreadHistoryEntries(
bundleDir: string,
threadId: string,
): Promise<Result<number, string>> {
const histRoot = join(bundleDir, "history");
let files: string[];
try {
files = await readdir(histRoot);
} catch (e) {
const errObj = e as NodeJS.ErrnoException;
if (errObj.code === "ENOENT") {
return ok(0);
}
return err(`failed to read history directory: ${String(e)}`);
}
let removed = 0;
for (const name of files) {
if (!name.endsWith(".jsonl")) {
continue;
}
const path = join(histRoot, name);
let text: string;
try {
text = await readFile(path, "utf8");
} catch {
continue;
}
const kept: string[] = [];
for (const line of text.split("\n")) {
const trimmed = line.trim();
if (trimmed === "") {
continue;
}
let rec: unknown;
try {
rec = JSON.parse(trimmed) as unknown;
} catch {
kept.push(`${trimmed}\n`);
continue;
}
if (rec === null || typeof rec !== "object") {
kept.push(`${trimmed}\n`);
continue;
}
const id = (rec as Record<string, unknown>).threadId;
if (id === threadId) {
removed++;
continue;
}
kept.push(`${trimmed}\n`);
}
await writeFile(path, kept.join(""), "utf8");
}
return ok(removed);
}
+33 -16
View File
@@ -11,7 +11,25 @@ export type ExecuteThreadIo = {
cas: CasStore; cas: CasStore;
}; };
/** One persisted role line in `.data.jsonl` (engine adds these for fork replay before running the generator). */ /** CAS chain tail state before the next appended {@link StateNode}. */
export type ChainState = {
parentStateHash: string | null;
parentAncestors: readonly string[];
};
export const EMPTY_CHAIN_STATE: ChainState = { parentStateHash: null, parentAncestors: [] };
/**
* When forking, the worker continues from an existing {@link StartNode} plus an optional
* branch marker {@link StateNode} instead of allocating a new start blob.
*/
export type ForkContinuationOptions = {
startHash: string;
forkHeadHash: string;
initialChain: ChainState;
};
/** One replayed role step (prefill) before the generator runs (same layout as disk replay rows). */
export type PrefilledDiskStep = { export type PrefilledDiskStep = {
role: string; role: string;
contentHash: string; contentHash: string;
@@ -30,37 +48,36 @@ export type ExecuteThreadOptions = {
/** When non-null, written into the start record so tooling can trace lineage. */ /** When non-null, written into the start record so tooling can trace lineage. */
forkSourceThreadId: string | null; forkSourceThreadId: string | null;
/** /**
* Written to `.data.jsonl` immediately after the start record, before the generator runs. * When non-null, replays these steps into CAS before the generator runs.
* Must match `input.steps` length and order when present. * Must match `input.steps` length and order when present.
*/ */
prefilledDiskSteps: PrefilledDiskStep[] | null; prefilledDiskSteps: PrefilledDiskStep[] | null;
/** When non-null, skip creating a new {@link StartNode} and continue this CAS chain. */
forkContinuation: ForkContinuationOptions | null;
/**
* When non-null, must match `input.steps.length`; supplies persisted timestamps for
* {@link ThreadContext.steps} (used when restoring history without prefilled CAS replay).
*/
replayTimestamps: readonly number[] | null;
/** Workspace root containing `workflow.yaml`; used to resolve the `extract` scene for meta extraction. */ /** Workspace root containing `workflow.yaml`; used to resolve the `extract` scene for meta extraction. */
storageRoot: string; storageRoot: string;
}; };
/** Role steps replayed from `.data.jsonl`, including persisted timestamps. */ export type CasForkPlan = {
export type ForkHistoricalStep = RoleOutput & { timestamp: number };
export type ParsedThreadStartRecord = {
workflowName: string;
hash: string;
threadId: string;
prompt: string;
maxRounds: number;
depth: number;
};
export type ForkPlan = {
workflowName: string; workflowName: string;
hash: string; hash: string;
sourceThreadId: string; sourceThreadId: string;
prompt: string; prompt: string;
runOptions: { maxRounds: number; depth: number }; runOptions: { maxRounds: number; depth: number };
historicalSteps: ForkHistoricalStep[]; steps: RoleOutput[];
stepTimestamps: number[];
forkContinuation: ForkContinuationOptions;
}; };
export type GcResult = { export type GcResult = {
/** Count of root hashes seeded from thread indexes (`head`/`start` per entry). */
scannedThreads: number; scannedThreads: number;
/** Reachable CAS blobs after the mark phase. */
activeRefs: number; activeRefs: number;
deletedEntries: number; deletedEntries: number;
deletedHashes: string[]; deletedHashes: string[];
+75 -3
View File
@@ -17,7 +17,12 @@ import {
} from "@uncaged/workflow-util"; } from "@uncaged/workflow-util";
import { executeThread } from "./engine.js"; import { executeThread } from "./engine.js";
import { createThreadPauseGate } from "./thread-pause-gate.js"; import { createThreadPauseGate } from "./thread-pause-gate.js";
import type { ExecuteThreadIo, PrefilledDiskStep, ThreadPauseGate } from "./types.js"; import type {
ExecuteThreadIo,
ForkContinuationOptions,
PrefilledDiskStep,
ThreadPauseGate,
} from "./types.js";
const bootLog = createLogger({ sink: { kind: "stderr" } }); const bootLog = createLogger({ sink: { kind: "stderr" } });
@@ -28,9 +33,10 @@ type RunCommand = {
prompt: string; prompt: string;
options: { maxRounds: number; depth: number }; options: { maxRounds: number; depth: number };
steps: RoleOutput[]; steps: RoleOutput[];
/** Timestamps aligned with `steps` for `.data.jsonl` replay; length must match `steps` when non-null. */ /** Timestamps aligned with `steps` for replay / fork restore; length must match `steps` when steps are non-empty. */
stepTimestamps: number[] | null; stepTimestamps: number[] | null;
forkSourceThreadId: string | null; forkSourceThreadId: string | null;
forkContinuation: ForkContinuationOptions | null;
}; };
type KillCommand = { type KillCommand = {
@@ -73,6 +79,7 @@ function parseRoleOutputRecord(obj: Record<string, unknown>): RoleOutput | null
}; };
} }
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: mirrors permissive worker IPC decoding shape checks
function parseRunStepsPayload(rec: Record<string, unknown>): { function parseRunStepsPayload(rec: Record<string, unknown>): {
steps: RoleOutput[]; steps: RoleOutput[];
stepTimestamps: number[] | null; stepTimestamps: number[] | null;
@@ -107,12 +114,60 @@ function parseRunStepsPayload(rec: Record<string, unknown>): {
return null; return null;
} }
} }
const parallelTsRaw = rec.stepTimestamps;
if (
steps.length > 0 &&
Array.isArray(parallelTsRaw) &&
parallelTsRaw.length === steps.length &&
parallelTsRaw.every((x): x is number => typeof x === "number")
) {
return { steps, stepTimestamps: [...parallelTsRaw] };
}
return { return {
steps, steps,
stepTimestamps: anyTimestamp ? timestamps : null, stepTimestamps: anyTimestamp ? timestamps : null,
}; };
} }
function parseForkContinuation(rec: Record<string, unknown>): ForkContinuationOptions | null {
const raw = rec.forkContinuation;
if (raw === undefined || raw === null) {
return null;
}
if (typeof raw !== "object") {
return null;
}
const o = raw as Record<string, unknown>;
const startHash = o.startHash;
const forkHeadHash = o.forkHeadHash;
const ic = o.initialChain;
if (typeof startHash !== "string" || typeof forkHeadHash !== "string") {
return null;
}
if (ic === null || typeof ic !== "object") {
return null;
}
const ich = ic as Record<string, unknown>;
const pph = ich.parentStateHash;
const pa = ich.parentAncestors;
if (!(pph === null || typeof pph === "string")) {
return null;
}
if (!Array.isArray(pa) || !pa.every((x) => typeof x === "string")) {
return null;
}
return {
startHash,
forkHeadHash,
initialChain: {
parentStateHash: pph,
parentAncestors: pa,
},
};
}
function parseRunControlPayload(rec: Record<string, unknown>): RunCommand | null { function parseRunControlPayload(rec: Record<string, unknown>): RunCommand | null {
const threadId = rec.threadId; const threadId = rec.threadId;
const workflowName = rec.workflowName; const workflowName = rec.workflowName;
@@ -148,6 +203,7 @@ function parseRunControlPayload(rec: Record<string, unknown>): RunCommand | null
} }
forkSourceThreadId = rawFork; forkSourceThreadId = rawFork;
} }
const forkContinuation = parseForkContinuation(rec);
return { return {
type: "run", type: "run",
threadId, threadId,
@@ -157,6 +213,7 @@ function parseRunControlPayload(rec: Record<string, unknown>): RunCommand | null
steps: parsedSteps.steps, steps: parsedSteps.steps,
stepTimestamps: parsedSteps.stepTimestamps, stepTimestamps: parsedSteps.stepTimestamps,
forkSourceThreadId, forkSourceThreadId,
forkContinuation,
}; };
} }
@@ -357,6 +414,7 @@ async function main(): Promise<void> {
} }
} }
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: TCP worker multiplexes lifecycle + runs
async function dispatchCommand(cmd: ControlCommand, socket: Socket | null): Promise<void> { async function dispatchCommand(cmd: ControlCommand, socket: Socket | null): Promise<void> {
if (cmd.type !== "run") { if (cmd.type !== "run") {
dispatchThreadLifecycleCommand(threads, socket, cmd); dispatchThreadLifecycleCommand(threads, socket, cmd);
@@ -394,7 +452,19 @@ async function main(): Promise<void> {
const baseTs = Date.now(); const baseTs = Date.now();
let prefilledDiskSteps: PrefilledDiskStep[] | null = null; let prefilledDiskSteps: PrefilledDiskStep[] | null = null;
if (cmd.steps.length > 0) { let replayTimestamps: readonly number[] | null = null;
if (cmd.forkContinuation !== null) {
if (
cmd.steps.length > 0 &&
(cmd.stepTimestamps === null || cmd.stepTimestamps.length !== cmd.steps.length)
) {
bootLog("J5WQ8NXT", "forkContinuation requires stepTimestamps aligned with steps");
throw new Error("forkContinuation requires stepTimestamps aligned with steps");
}
replayTimestamps =
cmd.steps.length === 0 ? null : (cmd.stepTimestamps as readonly number[]);
} else if (cmd.steps.length > 0) {
prefilledDiskSteps = cmd.steps.map((step, i) => { prefilledDiskSteps = cmd.steps.map((step, i) => {
const ts = cmd.stepTimestamps?.[i]; const ts = cmd.stepTimestamps?.[i];
return { return {
@@ -417,6 +487,8 @@ async function main(): Promise<void> {
awaitAfterEachYield: () => pauseGate.awaitAfterYield(), awaitAfterEachYield: () => pauseGate.awaitAfterYield(),
forkSourceThreadId: cmd.forkSourceThreadId, forkSourceThreadId: cmd.forkSourceThreadId,
prefilledDiskSteps, prefilledDiskSteps,
forkContinuation: cmd.forkContinuation,
replayTimestamps,
storageRoot, storageRoot,
}, },
io, io,
+21 -7
View File
@@ -1,25 +1,39 @@
export { createWorkflow } from "./engine/create-workflow.js"; export { createWorkflow } from "./engine/create-workflow.js";
export { executeThread } from "./engine/engine.js"; export { executeThread } from "./engine/engine.js";
export { export {
buildForkPlan, FORK_BRANCH_ROLE,
parseThreadDataJsonl, prepareCasFork,
selectForkHistoricalSteps,
tryParseRoleStepRecord,
tryParseWorkflowResultRecord, tryParseWorkflowResultRecord,
walkStateFramesNewestFirst,
} from "./engine/fork-thread.js"; } from "./engine/fork-thread.js";
export { garbageCollectCas } from "./engine/gc.js"; export { garbageCollectCas } from "./engine/gc.js";
export { createThreadPauseGate } from "./engine/thread-pause-gate.js"; export { createThreadPauseGate } from "./engine/thread-pause-gate.js";
export type { export type {
ThreadHistoryEntry,
ThreadIndex,
ThreadIndexEntry,
} from "./engine/threads-index.js";
export {
appendThreadHistoryEntry,
getBundleDir,
readThreadsIndex,
removeThreadEntry,
removeThreadHistoryEntries,
upsertThreadEntry,
writeThreadsIndex,
} from "./engine/threads-index.js";
export type {
CasForkPlan,
ChainState,
ExecuteThreadIo, ExecuteThreadIo,
ExecuteThreadOptions, ExecuteThreadOptions,
ForkHistoricalStep, ForkContinuationOptions,
ForkPlan,
GcResult, GcResult,
ParsedThreadStartRecord,
PrefilledDiskStep, PrefilledDiskStep,
SupervisorDecision, SupervisorDecision,
ThreadPauseGate, ThreadPauseGate,
} from "./engine/types.js"; } from "./engine/types.js";
export { EMPTY_CHAIN_STATE } from "./engine/types.js";
export { getWorkerHostScriptPath } from "./engine/worker-entry-path.js"; export { getWorkerHostScriptPath } from "./engine/worker-entry-path.js";
export type { ExtractFn, LlmError, LlmExtractArgs } from "./extract/index.js"; export type { ExtractFn, LlmError, LlmExtractArgs } from "./extract/index.js";
export { export {
@@ -101,6 +101,8 @@ export function workflowAsAgent(
awaitAfterEachYield: async () => {}, awaitAfterEachYield: async () => {},
forkSourceThreadId: ctx.threadId, forkSourceThreadId: ctx.threadId,
prefilledDiskSteps: null, prefilledDiskSteps: null,
forkContinuation: null,
replayTimestamps: null,
storageRoot, storageRoot,
}, },
io, io,