Merge ticket/t4-step-mirrors: step schemas, whole-plan hash v2, record schemas (#24)
# Conflicts: # test/workflow-journal.test.ts
This commit is contained in:
commit
e15c86f007
8 files changed
+578
-369
No files matched your search
+17
-20
@@ -19,7 +19,7 @@ import type {
|
|||||||
WorkflowJournalItem,
|
WorkflowJournalItem,
|
||||||
WorkflowJournalStep,
|
WorkflowJournalStep,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
import type { WorkflowPlan, WorkflowStep } from "./workflow-plan.ts";
|
import type { WorkflowPlan } from "./workflow-plan.ts";
|
||||||
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
import type { WorkflowRunSpec } from "./workflow-run.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -39,23 +39,20 @@ function canonical(value: unknown): string {
|
|||||||
return JSON.stringify(value);
|
return JSON.stringify(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
function planInputs(plan: WorkflowPlan): unknown {
|
/**
|
||||||
// Provenance (source, filePath) is where the plan came from, not what it asks
|
* Bumped when the hash payload changes shape, so a future replay layer can tell
|
||||||
// for; the same plan copied elsewhere keeps its step hashes.
|
* which era a persisted hash came from. Version 2 hashed whole plan steps.
|
||||||
return {
|
*/
|
||||||
name: plan.name,
|
export const WORKFLOW_HASH_PAYLOAD_VERSION = 2;
|
||||||
description: plan.description,
|
|
||||||
args: plan.args,
|
/**
|
||||||
steps: plan.steps.map((step: WorkflowStep) => ({
|
* The plan as the replay contract sees it: steps whole, so a new step field is
|
||||||
id: step.id,
|
* hashed by default. Provenance (source, filePath) is where the plan came from,
|
||||||
agent: step.agent,
|
* not what it asks for; the same plan copied elsewhere keeps its step hashes.
|
||||||
task: step.task,
|
*/
|
||||||
needs: step.needs,
|
function planHashInput(plan: WorkflowPlan): Omit<WorkflowPlan, "source" | "filePath"> {
|
||||||
each: step.each,
|
const { source: _source, filePath: _filePath, ...inputs } = plan;
|
||||||
model: step.model,
|
return inputs;
|
||||||
cwd: step.cwd,
|
|
||||||
})),
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -65,7 +62,7 @@ function planInputs(plan: WorkflowPlan): unknown {
|
|||||||
* identical hashes across runs.
|
* identical hashes across runs.
|
||||||
*/
|
*/
|
||||||
export function workflowStepInputHash(plan: WorkflowPlan, stepId: string, args: Readonly<Record<string, string>>): string {
|
export function workflowStepInputHash(plan: WorkflowPlan, stepId: string, args: Readonly<Record<string, string>>): string {
|
||||||
const payload = canonical({ version: 1, plan: planInputs(plan), step: stepId, args });
|
const payload = canonical({ version: WORKFLOW_HASH_PAYLOAD_VERSION, plan: planHashInput(plan), step: stepId, args });
|
||||||
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -81,7 +78,7 @@ export function workflowItemInputHash(
|
|||||||
args: Readonly<Record<string, string>>,
|
args: Readonly<Record<string, string>>,
|
||||||
item: string,
|
item: string,
|
||||||
): string {
|
): string {
|
||||||
const payload = canonical({ version: 1, plan: planInputs(plan), step: stepId, item, args });
|
const payload = canonical({ version: WORKFLOW_HASH_PAYLOAD_VERSION, plan: planHashInput(plan), step: stepId, item, args });
|
||||||
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
return `sha256:${createHash("sha256").update(payload, "utf8").digest("hex")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+23
-137
@@ -1,20 +1,26 @@
|
|||||||
import type { JobSnapshot, WorkflowJournal, WorkflowJournalItem, WorkflowJournalStep } from "./types.ts";
|
/**
|
||||||
|
* Session-entry persistence for jobs and workflow journals.
|
||||||
|
*
|
||||||
|
* The record shapes and their validators are the TypeBox schemas in
|
||||||
|
* `schemas.ts`: this module only wraps a record in its entry envelope and, on
|
||||||
|
* restore, accepts an entry exactly when `Value.Check` says the envelope and
|
||||||
|
* the record inside it match. There is no second hand-written validator to
|
||||||
|
* drift from the type.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { Value } from "typebox/value";
|
||||||
|
import {
|
||||||
|
PersistedJobSchema,
|
||||||
|
PersistedWorkflowJournalSchema,
|
||||||
|
type JobSnapshot,
|
||||||
|
type PersistedJob,
|
||||||
|
type PersistedWorkflowJournal,
|
||||||
|
type WorkflowJournal,
|
||||||
|
} from "./schemas.ts";
|
||||||
|
|
||||||
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
|
export const SUBAGENT_JOB_ENTRY = "subagent-job-v1";
|
||||||
export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1";
|
export const WORKFLOW_RUN_ENTRY = "pi-workflow-run-v1";
|
||||||
|
|
||||||
interface PersistedJob {
|
|
||||||
version: 1;
|
|
||||||
sessionId: string;
|
|
||||||
job: JobSnapshot;
|
|
||||||
}
|
|
||||||
|
|
||||||
interface PersistedWorkflowJournal {
|
|
||||||
version: 1;
|
|
||||||
sessionId: string;
|
|
||||||
journal: WorkflowJournal;
|
|
||||||
}
|
|
||||||
|
|
||||||
export function persistedJob(sessionId: string, job: JobSnapshot): PersistedJob {
|
export function persistedJob(sessionId: string, job: JobSnapshot): PersistedJob {
|
||||||
return { version: 1, sessionId, job: structuredClone(job) };
|
return { version: 1, sessionId, job: structuredClone(job) };
|
||||||
}
|
}
|
||||||
@@ -27,136 +33,16 @@ function record(value: unknown): value is Record<string, unknown> {
|
|||||||
return value !== null && typeof value === "object";
|
return value !== null && typeof value === "object";
|
||||||
}
|
}
|
||||||
|
|
||||||
const modes = new Set(["single", "parallel", "chain", "workflow"]);
|
|
||||||
const jobStatuses = new Set(["queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"]);
|
|
||||||
const taskStatuses = new Set(["queued", "running", "succeeded", "failed", "skipped", "cancelled", "interrupted"]);
|
|
||||||
const usageKeys = ["input", "output", "cacheRead", "cacheWrite", "cost", "contextTokens", "turns"] as const;
|
|
||||||
|
|
||||||
function validUsage(value: unknown): boolean {
|
|
||||||
return record(value) && usageKeys.every((key) => typeof value[key] === "number" && Number.isFinite(value[key]));
|
|
||||||
}
|
|
||||||
|
|
||||||
function validActivity(value: unknown): boolean {
|
|
||||||
return Array.isArray(value) && value.every((item) =>
|
|
||||||
record(item)
|
|
||||||
&& (item.kind === "text" || item.kind === "toolCall" || item.kind === "toolResult")
|
|
||||||
&& typeof item.summary === "string"
|
|
||||||
&& typeof item.timestamp === "number" && Number.isFinite(item.timestamp)
|
|
||||||
&& (item.isError === undefined || typeof item.isError === "boolean")
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validTask(value: unknown): boolean {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.agent === "string"
|
|
||||||
&& (value.agentSource === "user" || value.agentSource === "project" || value.agentSource === "unknown")
|
|
||||||
&& typeof value.task === "string"
|
|
||||||
&& typeof value.cwd === "string"
|
|
||||||
&& (value.stepId === undefined || typeof value.stepId === "string")
|
|
||||||
&& (value.item === undefined || (typeof value.item === "number" && Number.isInteger(value.item)))
|
|
||||||
&& (value.itemValue === undefined || typeof value.itemValue === "string")
|
|
||||||
&& typeof value.status === "string" && taskStatuses.has(value.status)
|
|
||||||
&& (typeof value.exitCode === "number" || value.exitCode === null)
|
|
||||||
&& typeof value.output === "string"
|
|
||||||
&& typeof value.outputTruncated === "boolean"
|
|
||||||
&& typeof value.outputBytesOmitted === "number"
|
|
||||||
&& typeof value.stderr === "string"
|
|
||||||
&& typeof value.stderrTruncated === "boolean"
|
|
||||||
&& (value.activity === undefined || validActivity(value.activity))
|
|
||||||
&& validUsage(value.usage);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validJob(value: unknown): value is JobSnapshot {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.id === "string"
|
|
||||||
&& typeof value.mode === "string" && modes.has(value.mode)
|
|
||||||
&& (value.agentScope === "user" || value.agentScope === "project" || value.agentScope === "both")
|
|
||||||
&& (typeof value.projectAgentsDir === "string" || value.projectAgentsDir === null)
|
|
||||||
&& Array.isArray(value.projectAgentsDirs) && value.projectAgentsDirs.every((dir) => typeof dir === "string")
|
|
||||||
&& typeof value.status === "string" && jobStatuses.has(value.status)
|
|
||||||
&& typeof value.plannedTaskCount === "number" && Number.isInteger(value.plannedTaskCount)
|
|
||||||
&& typeof value.createdAt === "number" && Number.isFinite(value.createdAt)
|
|
||||||
&& Array.isArray(value.results) && value.results.every(validTask)
|
|
||||||
&& validUsage(value.usage);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function extractJobSnapshots(entries: unknown[]): JobSnapshot[] {
|
export function extractJobSnapshots(entries: unknown[]): JobSnapshot[] {
|
||||||
const snapshots: JobSnapshot[] = [];
|
const snapshots: JobSnapshot[] = [];
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
if (!record(entry) || entry.type !== "custom" || entry.customType !== SUBAGENT_JOB_ENTRY || !record(entry.data)) continue;
|
if (!record(entry) || entry.type !== "custom" || entry.customType !== SUBAGENT_JOB_ENTRY) continue;
|
||||||
if (entry.data.version !== 1 || !validJob(entry.data.job)) continue;
|
if (!Value.Check(PersistedJobSchema, entry.data)) continue;
|
||||||
snapshots.push(structuredClone(entry.data.job));
|
snapshots.push(structuredClone(entry.data.job));
|
||||||
}
|
}
|
||||||
return snapshots;
|
return snapshots;
|
||||||
}
|
}
|
||||||
|
|
||||||
function validPlan(value: unknown): boolean {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.name === "string"
|
|
||||||
&& typeof value.description === "string"
|
|
||||||
&& Array.isArray(value.args) && value.args.every((arg) => typeof arg === "string")
|
|
||||||
&& (value.source === "user" || value.source === "project" || value.source === "inline")
|
|
||||||
&& typeof value.filePath === "string"
|
|
||||||
&& Array.isArray(value.steps) && value.steps.every(validPlanStep);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validPlanStep(value: unknown): boolean {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.id === "string"
|
|
||||||
&& typeof value.agent === "string"
|
|
||||||
&& typeof value.task === "string"
|
|
||||||
&& Array.isArray(value.needs) && value.needs.every((need) => typeof need === "string")
|
|
||||||
&& (value.each === undefined || typeof value.each === "string")
|
|
||||||
&& (value.model === undefined || typeof value.model === "string")
|
|
||||||
&& (value.cwd === undefined || typeof value.cwd === "string");
|
|
||||||
}
|
|
||||||
|
|
||||||
function finiteNumber(value: unknown): boolean {
|
|
||||||
return typeof value === "number" && Number.isFinite(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validJournalItem(value: unknown): value is WorkflowJournalItem {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.item === "number" && Number.isInteger(value.item) && value.item >= 1
|
|
||||||
&& typeof value.input === "string"
|
|
||||||
&& typeof value.inputHash === "string"
|
|
||||||
&& typeof value.status === "string" && taskStatuses.has(value.status)
|
|
||||||
&& typeof value.attempts === "number" && Number.isInteger(value.attempts) && value.attempts >= 0
|
|
||||||
&& typeof value.output === "string"
|
|
||||||
&& typeof value.outputTruncated === "boolean"
|
|
||||||
&& typeof value.outputBytesOmitted === "number" && value.outputBytesOmitted >= 0
|
|
||||||
&& (value.startedAt === undefined || finiteNumber(value.startedAt))
|
|
||||||
&& (value.finishedAt === undefined || finiteNumber(value.finishedAt));
|
|
||||||
}
|
|
||||||
|
|
||||||
function validJournalStep(value: unknown): value is WorkflowJournalStep {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.id === "string"
|
|
||||||
&& typeof value.inputHash === "string"
|
|
||||||
&& typeof value.status === "string" && taskStatuses.has(value.status)
|
|
||||||
&& typeof value.attempts === "number" && Number.isInteger(value.attempts) && value.attempts >= 0
|
|
||||||
&& typeof value.output === "string"
|
|
||||||
&& typeof value.outputTruncated === "boolean"
|
|
||||||
&& typeof value.outputBytesOmitted === "number" && value.outputBytesOmitted >= 0
|
|
||||||
&& (value.startedAt === undefined || finiteNumber(value.startedAt))
|
|
||||||
&& (value.finishedAt === undefined || finiteNumber(value.finishedAt))
|
|
||||||
&& Array.isArray(value.items) && value.items.every(validJournalItem);
|
|
||||||
}
|
|
||||||
|
|
||||||
function validJournal(value: unknown): value is WorkflowJournal {
|
|
||||||
if (!record(value)) return false;
|
|
||||||
return typeof value.jobId === "string"
|
|
||||||
&& typeof value.status === "string" && jobStatuses.has(value.status)
|
|
||||||
&& validPlan(value.plan)
|
|
||||||
&& record(value.args) && Object.values(value.args).every((arg) => typeof arg === "string")
|
|
||||||
&& Array.isArray(value.steps) && value.steps.every(validJournalStep)
|
|
||||||
&& validUsage(value.usage)
|
|
||||||
&& finiteNumber(value.createdAt)
|
|
||||||
&& (value.startedAt === undefined || finiteNumber(value.startedAt))
|
|
||||||
&& (value.finishedAt === undefined || finiteNumber(value.finishedAt))
|
|
||||||
&& (value.errorMessage === undefined || typeof value.errorMessage === "string");
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One journal record per run.
|
* One journal record per run.
|
||||||
*
|
*
|
||||||
@@ -167,8 +53,8 @@ function validJournal(value: unknown): value is WorkflowJournal {
|
|||||||
export function extractWorkflowJournals(entries: unknown[]): WorkflowJournal[] {
|
export function extractWorkflowJournals(entries: unknown[]): WorkflowJournal[] {
|
||||||
const byJob = new Map<string, WorkflowJournal>();
|
const byJob = new Map<string, WorkflowJournal>();
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
if (!record(entry) || entry.type !== "custom" || entry.customType !== WORKFLOW_RUN_ENTRY || !record(entry.data)) continue;
|
if (!record(entry) || entry.type !== "custom" || entry.customType !== WORKFLOW_RUN_ENTRY) continue;
|
||||||
if (entry.data.version !== 1 || !validJournal(entry.data.journal)) continue;
|
if (!Value.Check(PersistedWorkflowJournalSchema, entry.data)) continue;
|
||||||
byJob.set(entry.data.journal.jobId, structuredClone(entry.data.journal));
|
byJob.set(entry.data.journal.jobId, structuredClone(entry.data.journal));
|
||||||
}
|
}
|
||||||
return Array.from(byJob.values());
|
return Array.from(byJob.values());
|
||||||
|
|||||||
+205
-4
@@ -1,12 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* TypeBox request schemas for the subagent tools.
|
* TypeBox schemas for the subagent tools and the persisted records.
|
||||||
*
|
*
|
||||||
* These are the single source of truth for the wire/JSON shape of an
|
* The request schemas are the single source of truth for the wire/JSON shape
|
||||||
* invocation request. `prepare.ts` consumes the inferred static types; the
|
* of an invocation request. The record schemas are the single source of truth
|
||||||
* tool registration in `index.ts` can hand the schemas straight to Pi.
|
* for what a session restores: the job snapshot, the workflow journal, and the
|
||||||
|
* entry envelopes around them (ADR 0004 makes the journal the future-replay
|
||||||
|
* contract). Every persisted type is `Static<>` of its schema, so a shape that
|
||||||
|
* drifts from its validator fails to compile.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { Type, type Static } from "typebox";
|
import { Type, type Static } from "typebox";
|
||||||
|
import { WorkflowPlanSchema } from "./workflow-plan.ts";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Which agent directories an invocation may read.
|
* Which agent directories an invocation may read.
|
||||||
@@ -142,3 +146,200 @@ export const UltraParams = Type.Object(
|
|||||||
);
|
);
|
||||||
|
|
||||||
export type UltraParamsType = Static<typeof UltraParams>;
|
export type UltraParamsType = Static<typeof UltraParams>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persisted records.
|
||||||
|
*
|
||||||
|
* Session entries are JSON, so every persisted value is a plain JSON shape.
|
||||||
|
* The status and mode unions are schemas rather than hand-written sets: the
|
||||||
|
* types and the restore validator both come from here.
|
||||||
|
*/
|
||||||
|
export const InvocationModeSchema = Type.Union([
|
||||||
|
Type.Literal("single"),
|
||||||
|
Type.Literal("parallel"),
|
||||||
|
Type.Literal("chain"),
|
||||||
|
Type.Literal("workflow"),
|
||||||
|
]);
|
||||||
|
export type InvocationMode = Static<typeof InvocationModeSchema>;
|
||||||
|
|
||||||
|
export const JobStatusSchema = Type.Union([
|
||||||
|
Type.Literal("queued"),
|
||||||
|
Type.Literal("running"),
|
||||||
|
Type.Literal("cancelling"),
|
||||||
|
Type.Literal("succeeded"),
|
||||||
|
Type.Literal("failed"),
|
||||||
|
Type.Literal("cancelled"),
|
||||||
|
Type.Literal("interrupted"),
|
||||||
|
]);
|
||||||
|
export type JobStatus = Static<typeof JobStatusSchema>;
|
||||||
|
|
||||||
|
export const TaskStatusSchema = Type.Union([
|
||||||
|
Type.Literal("queued"),
|
||||||
|
Type.Literal("running"),
|
||||||
|
Type.Literal("succeeded"),
|
||||||
|
Type.Literal("failed"),
|
||||||
|
Type.Literal("skipped"),
|
||||||
|
Type.Literal("cancelled"),
|
||||||
|
Type.Literal("interrupted"),
|
||||||
|
]);
|
||||||
|
export type TaskStatus = Static<typeof TaskStatusSchema>;
|
||||||
|
|
||||||
|
export const UsageStatsSchema = Type.Object(
|
||||||
|
{
|
||||||
|
input: Type.Number(),
|
||||||
|
output: Type.Number(),
|
||||||
|
cacheRead: Type.Number(),
|
||||||
|
cacheWrite: Type.Number(),
|
||||||
|
cost: Type.Number(),
|
||||||
|
contextTokens: Type.Number(),
|
||||||
|
turns: Type.Number(),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type UsageStats = Static<typeof UsageStatsSchema>;
|
||||||
|
|
||||||
|
export const TaskActivitySchema = Type.Object(
|
||||||
|
{
|
||||||
|
kind: Type.Union([Type.Literal("text"), Type.Literal("toolCall"), Type.Literal("toolResult")]),
|
||||||
|
summary: Type.String(),
|
||||||
|
timestamp: Type.Number(),
|
||||||
|
isError: Type.Optional(Type.Boolean()),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type TaskActivity = Static<typeof TaskActivitySchema>;
|
||||||
|
export type TaskActivityKind = TaskActivity["kind"];
|
||||||
|
|
||||||
|
export const TaskSnapshotSchema = Type.Object(
|
||||||
|
{
|
||||||
|
agent: Type.String(),
|
||||||
|
agentSource: Type.Union([Type.Literal("user"), Type.Literal("project"), Type.Literal("unknown")]),
|
||||||
|
task: Type.String(),
|
||||||
|
cwd: Type.String(),
|
||||||
|
step: Type.Optional(Type.Integer()),
|
||||||
|
stepId: Type.Optional(Type.String()),
|
||||||
|
item: Type.Optional(Type.Integer()),
|
||||||
|
itemValue: Type.Optional(Type.String()),
|
||||||
|
status: TaskStatusSchema,
|
||||||
|
exitCode: Type.Union([Type.Number(), Type.Null()]),
|
||||||
|
output: Type.String(),
|
||||||
|
outputTruncated: Type.Boolean(),
|
||||||
|
outputBytesOmitted: Type.Number(),
|
||||||
|
stderr: Type.String(),
|
||||||
|
stderrTruncated: Type.Boolean(),
|
||||||
|
usage: UsageStatsSchema,
|
||||||
|
model: Type.Optional(Type.String()),
|
||||||
|
stopReason: Type.Optional(Type.String()),
|
||||||
|
errorMessage: Type.Optional(Type.String()),
|
||||||
|
terminationSignal: Type.Optional(Type.String()),
|
||||||
|
/** Optional for snapshots persisted before activity was added. */
|
||||||
|
activity: Type.Optional(Type.Array(TaskActivitySchema)),
|
||||||
|
startedAt: Type.Optional(Type.Number()),
|
||||||
|
finishedAt: Type.Optional(Type.Number()),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type TaskSnapshot = Static<typeof TaskSnapshotSchema>;
|
||||||
|
|
||||||
|
export const JobSnapshotSchema = Type.Object(
|
||||||
|
{
|
||||||
|
id: Type.String(),
|
||||||
|
mode: InvocationModeSchema,
|
||||||
|
agentScope: AgentScopeSchema,
|
||||||
|
projectAgentsDir: Type.Union([Type.String(), Type.Null()]),
|
||||||
|
projectAgentsDirs: Type.Array(Type.String()),
|
||||||
|
status: JobStatusSchema,
|
||||||
|
plannedTaskCount: Type.Integer(),
|
||||||
|
results: Type.Array(TaskSnapshotSchema),
|
||||||
|
usage: UsageStatsSchema,
|
||||||
|
createdAt: Type.Number(),
|
||||||
|
startedAt: Type.Optional(Type.Number()),
|
||||||
|
finishedAt: Type.Optional(Type.Number()),
|
||||||
|
errorMessage: Type.Optional(Type.String()),
|
||||||
|
timedOut: Type.Optional(Type.Boolean()),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type JobSnapshot = Static<typeof JobSnapshotSchema>;
|
||||||
|
|
||||||
|
/** One fanned-out item child of an each-step, as the journal records it. */
|
||||||
|
export const WorkflowJournalItemSchema = Type.Object(
|
||||||
|
{
|
||||||
|
/** One-based item index within the step's fan-out. */
|
||||||
|
item: Type.Integer({ minimum: 1 }),
|
||||||
|
/** The source line this item was fanned out from. */
|
||||||
|
input: Type.String(),
|
||||||
|
/** Stable across identical item inputs, so a replay layer can key on it. */
|
||||||
|
inputHash: Type.String(),
|
||||||
|
status: TaskStatusSchema,
|
||||||
|
/** Children started for this item; always 0 or 1 while no retry exists. */
|
||||||
|
attempts: Type.Integer({ minimum: 0 }),
|
||||||
|
output: Type.String(),
|
||||||
|
outputTruncated: Type.Boolean(),
|
||||||
|
outputBytesOmitted: Type.Number({ minimum: 0 }),
|
||||||
|
startedAt: Type.Optional(Type.Number()),
|
||||||
|
finishedAt: Type.Optional(Type.Number()),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type WorkflowJournalItem = Static<typeof WorkflowJournalItemSchema>;
|
||||||
|
|
||||||
|
export const WorkflowJournalStepSchema = Type.Object(
|
||||||
|
{
|
||||||
|
id: Type.String(),
|
||||||
|
/** Stable across identical step inputs, so a replay layer can key on it. */
|
||||||
|
inputHash: Type.String(),
|
||||||
|
status: TaskStatusSchema,
|
||||||
|
/** Children started for this step; always 0 or 1 while no retry exists. */
|
||||||
|
attempts: Type.Integer({ minimum: 0 }),
|
||||||
|
output: Type.String(),
|
||||||
|
outputTruncated: Type.Boolean(),
|
||||||
|
outputBytesOmitted: Type.Number({ minimum: 0 }),
|
||||||
|
startedAt: Type.Optional(Type.Number()),
|
||||||
|
finishedAt: Type.Optional(Type.Number()),
|
||||||
|
/** One row per each-step item, in item order; empty for steps that do not fan out. */
|
||||||
|
items: Type.Array(WorkflowJournalItemSchema),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type WorkflowJournalStep = Static<typeof WorkflowJournalStepSchema>;
|
||||||
|
|
||||||
|
/** The persisted per-run record; ADR 0004 names it the future-replay contract. */
|
||||||
|
export const WorkflowJournalSchema = Type.Object(
|
||||||
|
{
|
||||||
|
jobId: Type.String(),
|
||||||
|
status: JobStatusSchema,
|
||||||
|
plan: WorkflowPlanSchema,
|
||||||
|
args: Type.Record(Type.String(), Type.String()),
|
||||||
|
steps: Type.Array(WorkflowJournalStepSchema),
|
||||||
|
usage: UsageStatsSchema,
|
||||||
|
createdAt: Type.Number(),
|
||||||
|
startedAt: Type.Optional(Type.Number()),
|
||||||
|
finishedAt: Type.Optional(Type.Number()),
|
||||||
|
errorMessage: Type.Optional(Type.String()),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type WorkflowJournal = Static<typeof WorkflowJournalSchema>;
|
||||||
|
|
||||||
|
/** The session entry envelope around one job snapshot. */
|
||||||
|
export const PersistedJobSchema = Type.Object(
|
||||||
|
{
|
||||||
|
version: Type.Literal(1),
|
||||||
|
sessionId: Type.String(),
|
||||||
|
job: JobSnapshotSchema,
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type PersistedJob = Static<typeof PersistedJobSchema>;
|
||||||
|
|
||||||
|
/** The session entry envelope around one workflow journal. */
|
||||||
|
export const PersistedWorkflowJournalSchema = Type.Object(
|
||||||
|
{
|
||||||
|
version: Type.Literal(1),
|
||||||
|
sessionId: Type.String(),
|
||||||
|
journal: WorkflowJournalSchema,
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
export type PersistedWorkflowJournal = Static<typeof PersistedWorkflowJournalSchema>;
|
||||||
+18
-116
@@ -1,11 +1,25 @@
|
|||||||
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
|
||||||
import type { Message } from "@earendil-works/pi-ai";
|
import type { Message } from "@earendil-works/pi-ai";
|
||||||
import type { AgentConfig, AgentScope } from "./agents.ts";
|
import type { AgentConfig, AgentScope } from "./agents.ts";
|
||||||
import type { WorkflowPlan } from "./workflow-plan.ts";
|
import type { InvocationMode, JobSnapshot, JobStatus, TaskStatus, UsageStats, WorkflowJournal } from "./schemas.ts";
|
||||||
|
|
||||||
export type InvocationMode = "single" | "parallel" | "chain" | "workflow";
|
/**
|
||||||
export type JobStatus = "queued" | "running" | "cancelling" | "succeeded" | "failed" | "cancelled" | "interrupted";
|
* Persisted record types live with their TypeBox schemas in `schemas.ts`.
|
||||||
export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "interrupted";
|
* Re-exported here so the rest of the extension keeps one types module.
|
||||||
|
*/
|
||||||
|
export type {
|
||||||
|
InvocationMode,
|
||||||
|
JobSnapshot,
|
||||||
|
JobStatus,
|
||||||
|
TaskActivity,
|
||||||
|
TaskActivityKind,
|
||||||
|
TaskSnapshot,
|
||||||
|
TaskStatus,
|
||||||
|
UsageStats,
|
||||||
|
WorkflowJournal,
|
||||||
|
WorkflowJournalItem,
|
||||||
|
WorkflowJournalStep,
|
||||||
|
} from "./schemas.ts";
|
||||||
|
|
||||||
export interface DispatchDefaults {
|
export interface DispatchDefaults {
|
||||||
model?: string;
|
model?: string;
|
||||||
@@ -35,16 +49,6 @@ export interface PreparedInvocation {
|
|||||||
dispatchDefaults: DispatchDefaults;
|
dispatchDefaults: DispatchDefaults;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UsageStats {
|
|
||||||
input: number;
|
|
||||||
output: number;
|
|
||||||
cacheRead: number;
|
|
||||||
cacheWrite: number;
|
|
||||||
cost: number;
|
|
||||||
contextTokens: number;
|
|
||||||
turns: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RunResult {
|
export interface RunResult {
|
||||||
agent: string;
|
agent: string;
|
||||||
agentSource: "user" | "project" | "unknown";
|
agentSource: "user" | "project" | "unknown";
|
||||||
@@ -76,44 +80,6 @@ export interface TaskRunner {
|
|||||||
run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult>;
|
run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise<RunResult>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type TaskActivityKind = "text" | "toolCall" | "toolResult";
|
|
||||||
|
|
||||||
/** A bounded, display-safe summary of one child message or tool interaction. */
|
|
||||||
export interface TaskActivity {
|
|
||||||
kind: TaskActivityKind;
|
|
||||||
summary: string;
|
|
||||||
timestamp: number;
|
|
||||||
isError?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface TaskSnapshot {
|
|
||||||
agent: string;
|
|
||||||
agentSource: "user" | "project" | "unknown";
|
|
||||||
task: string;
|
|
||||||
cwd: string;
|
|
||||||
step?: number;
|
|
||||||
stepId?: string;
|
|
||||||
item?: number;
|
|
||||||
/** The source line behind an each-step item child. */
|
|
||||||
itemValue?: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
exitCode: number | null;
|
|
||||||
output: string;
|
|
||||||
outputTruncated: boolean;
|
|
||||||
outputBytesOmitted: number;
|
|
||||||
stderr: string;
|
|
||||||
stderrTruncated: boolean;
|
|
||||||
usage: UsageStats;
|
|
||||||
model?: string;
|
|
||||||
stopReason?: string;
|
|
||||||
errorMessage?: string;
|
|
||||||
terminationSignal?: string;
|
|
||||||
/** Recent display activity. Optional for snapshots persisted before activity was added. */
|
|
||||||
activity?: TaskActivity[];
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Identity fields shared by a task's prepared form, result, and snapshot. */
|
/** Identity fields shared by a task's prepared form, result, and snapshot. */
|
||||||
export interface TaskIdentity {
|
export interface TaskIdentity {
|
||||||
agent: string;
|
agent: string;
|
||||||
@@ -126,23 +92,6 @@ export interface TaskIdentity {
|
|||||||
itemValue?: string;
|
itemValue?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface JobSnapshot {
|
|
||||||
id: string;
|
|
||||||
mode: InvocationMode;
|
|
||||||
agentScope: AgentScope;
|
|
||||||
projectAgentsDir: string | null;
|
|
||||||
projectAgentsDirs: string[];
|
|
||||||
status: JobStatus;
|
|
||||||
plannedTaskCount: number;
|
|
||||||
results: TaskSnapshot[];
|
|
||||||
usage: UsageStats;
|
|
||||||
createdAt: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
errorMessage?: string;
|
|
||||||
timedOut?: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface SyncOutcome {
|
export interface SyncOutcome {
|
||||||
status: JobStatus;
|
status: JobStatus;
|
||||||
results: RunResult[];
|
results: RunResult[];
|
||||||
@@ -162,53 +111,6 @@ export interface SyncRunOptions {
|
|||||||
onUpdate?: (outcome: SyncOutcome) => void;
|
onUpdate?: (outcome: SyncOutcome) => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** One fanned-out item child of an each-step, as the journal records it. */
|
|
||||||
export interface WorkflowJournalItem {
|
|
||||||
/** One-based item index within the step's fan-out. */
|
|
||||||
item: number;
|
|
||||||
/** The source line this item was fanned out from. */
|
|
||||||
input: string;
|
|
||||||
/** Stable across identical item inputs, so a replay layer can key on it. */
|
|
||||||
inputHash: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
/** Children started for this item; always 0 or 1 while no retry exists. */
|
|
||||||
attempts: number;
|
|
||||||
output: string;
|
|
||||||
outputTruncated: boolean;
|
|
||||||
outputBytesOmitted: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WorkflowJournalStep {
|
|
||||||
id: string;
|
|
||||||
/** Stable across identical step inputs, so a replay layer can key on it. */
|
|
||||||
inputHash: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
/** Children started for this step; always 0 or 1 while no retry exists. */
|
|
||||||
attempts: number;
|
|
||||||
output: string;
|
|
||||||
outputTruncated: boolean;
|
|
||||||
outputBytesOmitted: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
/** One row per each-step item, in item order; empty for steps that do not fan out. */
|
|
||||||
items: WorkflowJournalItem[];
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WorkflowJournal {
|
|
||||||
jobId: string;
|
|
||||||
status: JobStatus;
|
|
||||||
plan: WorkflowPlan;
|
|
||||||
args: Record<string, string>;
|
|
||||||
steps: WorkflowJournalStep[];
|
|
||||||
usage: UsageStats;
|
|
||||||
createdAt: number;
|
|
||||||
startedAt?: number;
|
|
||||||
finishedAt?: number;
|
|
||||||
errorMessage?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ManagerOptions {
|
export interface ManagerOptions {
|
||||||
maxWorkers?: number;
|
maxWorkers?: number;
|
||||||
maxActiveJobs?: number;
|
maxActiveJobs?: number;
|
||||||
|
|||||||
+95
-64
@@ -12,6 +12,8 @@
|
|||||||
import * as fs from "node:fs";
|
import * as fs from "node:fs";
|
||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from "@earendil-works/pi-coding-agent";
|
||||||
|
import { Type, type Static } from "typebox";
|
||||||
|
import { Value } from "typebox/value";
|
||||||
|
|
||||||
export const MAX_WORKFLOW_STEPS = 64;
|
export const MAX_WORKFLOW_STEPS = 64;
|
||||||
export const MAX_EXPANDED_CHILDREN = 256;
|
export const MAX_EXPANDED_CHILDREN = 256;
|
||||||
@@ -20,31 +22,59 @@ export const MAX_EXPANDED_CHILDREN = 256;
|
|||||||
* Where a plan came from. `inline` plans are authored at run time and have no
|
* Where a plan came from. `inline` plans are authored at run time and have no
|
||||||
* file; their stable `filePath` below is provenance, not a path to read.
|
* file; their stable `filePath` below is provenance, not a path to read.
|
||||||
*/
|
*/
|
||||||
export type WorkflowSource = "user" | "project" | "inline";
|
export const WorkflowSourceSchema = Type.Union([
|
||||||
|
Type.Literal("user"),
|
||||||
|
Type.Literal("project"),
|
||||||
|
Type.Literal("inline"),
|
||||||
|
]);
|
||||||
|
export type WorkflowSource = Static<typeof WorkflowSourceSchema>;
|
||||||
export type WorkflowScope = "user" | "project" | "both";
|
export type WorkflowScope = "user" | "project" | "both";
|
||||||
|
|
||||||
/** Stable provenance literal for a plan with no file behind it. */
|
/** Stable provenance literal for a plan with no file behind it. */
|
||||||
export const INLINE_WORKFLOW_FILE_PATH = "ultra:inline";
|
export const INLINE_WORKFLOW_FILE_PATH = "ultra:inline";
|
||||||
|
|
||||||
export interface WorkflowStep {
|
const IDENTIFIER_SOURCE = "^[A-Za-z_][A-Za-z0-9_-]*$";
|
||||||
id: string;
|
/** A string with at least one non-whitespace character: "nonempty" for YAML. */
|
||||||
agent: string;
|
const NONBLANK = "\\S";
|
||||||
task: string;
|
const IDENTIFIER = new RegExp(IDENTIFIER_SOURCE);
|
||||||
needs: string[];
|
|
||||||
/** Source step id for an each-step, normalized from `{steps.<id>.output}`. */
|
|
||||||
each?: string;
|
|
||||||
model?: string;
|
|
||||||
cwd?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WorkflowPlan {
|
/**
|
||||||
name: string;
|
* The canonical step shape: the one field list.
|
||||||
description: string;
|
*
|
||||||
args: string[];
|
* Parsing validates raw frontmatter against this schema, the journal hashes
|
||||||
steps: WorkflowStep[];
|
* plan steps whole, and the persisted plan restores them. A new step field is
|
||||||
source: WorkflowSource;
|
* declared here once and reaches every consumer, including the input hash,
|
||||||
filePath: string;
|
* with no second copy to keep in sync.
|
||||||
}
|
*/
|
||||||
|
export const WorkflowStepSchema = Type.Object(
|
||||||
|
{
|
||||||
|
id: Type.String({ minLength: 1, pattern: IDENTIFIER_SOURCE }),
|
||||||
|
agent: Type.String({ minLength: 1, pattern: NONBLANK }),
|
||||||
|
task: Type.String({ minLength: 1, pattern: NONBLANK }),
|
||||||
|
needs: Type.Array(Type.String({ minLength: 1, pattern: IDENTIFIER_SOURCE })),
|
||||||
|
/** Source step id for an each-step, normalized from `{steps.<id>.output}`. */
|
||||||
|
each: Type.Optional(Type.String({ minLength: 1, pattern: IDENTIFIER_SOURCE })),
|
||||||
|
model: Type.Optional(Type.String({ minLength: 1, pattern: NONBLANK })),
|
||||||
|
cwd: Type.Optional(Type.String({ minLength: 1, pattern: NONBLANK })),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
export type WorkflowStep = Static<typeof WorkflowStepSchema>;
|
||||||
|
|
||||||
|
export const WorkflowPlanSchema = Type.Object(
|
||||||
|
{
|
||||||
|
name: Type.String({ minLength: 1, pattern: NONBLANK }),
|
||||||
|
description: Type.String({ minLength: 1, pattern: NONBLANK }),
|
||||||
|
args: Type.Array(Type.String({ minLength: 1, pattern: IDENTIFIER_SOURCE })),
|
||||||
|
steps: Type.Array(WorkflowStepSchema),
|
||||||
|
source: WorkflowSourceSchema,
|
||||||
|
filePath: Type.String({ minLength: 1 }),
|
||||||
|
},
|
||||||
|
{ additionalProperties: false },
|
||||||
|
);
|
||||||
|
|
||||||
|
export type WorkflowPlan = Static<typeof WorkflowPlanSchema>;
|
||||||
|
|
||||||
export interface ParseWorkflowOptions {
|
export interface ParseWorkflowOptions {
|
||||||
source: WorkflowSource;
|
source: WorkflowSource;
|
||||||
@@ -110,8 +140,6 @@ export function workflowValidationError(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const TOP_LEVEL_FIELDS = ["name", "description", "args", "steps"] as const;
|
const TOP_LEVEL_FIELDS = ["name", "description", "args", "steps"] as const;
|
||||||
const STEP_FIELDS = ["id", "agent", "task", "needs", "each", "model", "cwd"] as const;
|
|
||||||
const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_-]*$/;
|
|
||||||
const EACH_STRING = /^\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}$/;
|
const EACH_STRING = /^\{steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output\}$/;
|
||||||
const EACH_KEY = /^steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output$/;
|
const EACH_KEY = /^steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output$/;
|
||||||
const ARG_REFERENCE = /\{args\.([A-Za-z_][A-Za-z0-9_-]*)\}/g;
|
const ARG_REFERENCE = /\{args\.([A-Za-z_][A-Za-z0-9_-]*)\}/g;
|
||||||
@@ -180,6 +208,26 @@ function unknownFields(record: Record<string, unknown>, allowed: readonly string
|
|||||||
return Object.keys(record).filter((key) => !allowedSet.has(key));
|
return Object.keys(record).filter((key) => !allowedSet.has(key));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Say why a step failed the canonical schema, naming the field.
|
||||||
|
*
|
||||||
|
* The schema owns which fields exist and what they accept; this only phrases
|
||||||
|
* the violation in the parser's vocabulary so the error still points at the
|
||||||
|
* offending key.
|
||||||
|
*/
|
||||||
|
function stepViolation(label: string, violation: { instancePath: string; keyword: string }): string {
|
||||||
|
const [field = "", index] = violation.instancePath.split("/").slice(1);
|
||||||
|
if (field === "id" && violation.keyword === "pattern") {
|
||||||
|
return `${label}.id must be a valid step id (letters, digits, "_" or "-", not starting with a digit).`;
|
||||||
|
}
|
||||||
|
if (field === "needs") {
|
||||||
|
return index === undefined
|
||||||
|
? `${label}.needs must be a list of step ids.`
|
||||||
|
: `${label}.needs[${index}] must be a nonempty step id.`;
|
||||||
|
}
|
||||||
|
return `${label}.${field} must be a nonempty string.`;
|
||||||
|
}
|
||||||
|
|
||||||
export function parseWorkflow(content: string, options: ParseWorkflowOptions): WorkflowPlan {
|
export function parseWorkflow(content: string, options: ParseWorkflowOptions): WorkflowPlan {
|
||||||
const { source, filePath } = options;
|
const { source, filePath } = options;
|
||||||
let name: string | undefined;
|
let name: string | undefined;
|
||||||
@@ -257,60 +305,43 @@ export function parseWorkflow(content: string, options: ParseWorkflowOptions): W
|
|||||||
fail(`too many steps (${stepList.length}). Max is ${MAX_WORKFLOW_STEPS} per workflow.`);
|
fail(`too many steps (${stepList.length}). Max is ${MAX_WORKFLOW_STEPS} per workflow.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const stepFieldNames = Object.keys(WorkflowStepSchema.properties);
|
||||||
const steps: WorkflowStep[] = stepList.map((raw: unknown, index: number) => {
|
const steps: WorkflowStep[] = stepList.map((raw: unknown, index: number) => {
|
||||||
if (!isRecord(raw)) fail(`steps[${index}] must be a mapping.`);
|
if (!isRecord(raw)) fail(`steps[${index}] must be a mapping.`);
|
||||||
const stepRecord = raw as Record<string, unknown>;
|
const stepRecord = raw as Record<string, unknown>;
|
||||||
const id = stepRecord.id;
|
const rawId = stepRecord.id;
|
||||||
if (typeof id !== "string" || id.trim().length === 0) fail(`steps[${index}].id must be a nonempty string.`);
|
const label = typeof rawId === "string" && rawId.trim().length > 0
|
||||||
if (!IDENTIFIER.test(id)) {
|
? `steps[${index}] ("${rawId}")`
|
||||||
fail(`steps[${index}].id "${id}" is not a valid step id (letters, digits, "_" or "-", not starting with a digit).`);
|
: `steps[${index}]`;
|
||||||
}
|
const stepId = typeof rawId === "string" && rawId.trim().length > 0 ? rawId : undefined;
|
||||||
const label = `steps[${index}] ("${id}")`;
|
|
||||||
|
|
||||||
const extraFields = unknownFields(stepRecord, STEP_FIELDS);
|
const extraFields = unknownFields(stepRecord, stepFieldNames);
|
||||||
if (extraFields.length > 0) {
|
if (extraFields.length > 0) {
|
||||||
fail(`${label} has unknown field${extraFields.length === 1 ? "" : "s"} ${extraFields.map((key) => `"${key}"`).join(", ")}. Allowed fields: ${STEP_FIELDS.join(", ")}.`, id);
|
fail(`${label} has unknown field${extraFields.length === 1 ? "" : "s"} ${extraFields.map((key) => `"${key}"`).join(", ")}. Allowed fields: ${stepFieldNames.join(", ")}.`, stepId);
|
||||||
}
|
}
|
||||||
|
|
||||||
const agent = stepRecord.agent;
|
// `needs` default to none; the two YAML spellings of `each` both collapse
|
||||||
if (typeof agent !== "string" || agent.trim().length === 0) fail(`${label}.agent must be a nonempty string.`, id);
|
// to the source step id, so the schema checks one canonical form.
|
||||||
const task = stepRecord.task;
|
const each = parseEachReference(stepRecord.each);
|
||||||
if (typeof task !== "string" || task.trim().length === 0) fail(`${label}.task must be a nonempty string.`, id);
|
if (stepRecord.each !== undefined && each === undefined) {
|
||||||
|
fail(`${label}.each must be a "{steps.<id>.output}" reference, got ${JSON.stringify(stepRecord.each)}.`, stepId);
|
||||||
const needs: string[] = [];
|
}
|
||||||
if (stepRecord.needs !== undefined) {
|
const candidate: Record<string, unknown> = {
|
||||||
if (!Array.isArray(stepRecord.needs)) fail(`${label}.needs must be a list of step ids.`, id);
|
...stepRecord,
|
||||||
for (const [needIndex, need] of stepRecord.needs.entries()) {
|
needs: stepRecord.needs ?? [],
|
||||||
if (typeof need !== "string" || need.trim().length === 0) fail(`${label}.needs[${needIndex}] must be a nonempty step id.`, id);
|
each,
|
||||||
needs.push(need);
|
};
|
||||||
}
|
if (!Value.Check(WorkflowStepSchema, candidate)) {
|
||||||
|
const [violation] = Value.Errors(WorkflowStepSchema, candidate);
|
||||||
|
fail(violation ? stepViolation(label, violation) : `${label} is not a valid step.`, stepId);
|
||||||
}
|
}
|
||||||
|
|
||||||
let each: string | undefined;
|
const step = candidate;
|
||||||
if (stepRecord.each !== undefined) {
|
if (step.each === undefined && step.task.includes("{item}")) {
|
||||||
each = parseEachReference(stepRecord.each);
|
fail(`${label}.task contains {item}, but {item} is only valid in a step with \`each\`.`, stepId);
|
||||||
if (each === undefined) {
|
|
||||||
fail(`${label}.each must be a "{steps.<id>.output}" reference, got ${JSON.stringify(stepRecord.each)}.`, id);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if (each === undefined && task.includes("{item}")) {
|
|
||||||
fail(`${label}.task contains {item}, but {item} is only valid in a step with \`each\`.`, id);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let model: string | undefined;
|
return { id: step.id, agent: step.agent, task: step.task, needs: step.needs, each: step.each, model: step.model, cwd: step.cwd };
|
||||||
const modelValue = stepRecord.model;
|
|
||||||
if (modelValue !== undefined) {
|
|
||||||
if (typeof modelValue !== "string" || modelValue.trim().length === 0) fail(`${label}.model must be a nonempty string when provided.`, id);
|
|
||||||
model = modelValue;
|
|
||||||
}
|
|
||||||
let cwd: string | undefined;
|
|
||||||
const cwdValue = stepRecord.cwd;
|
|
||||||
if (cwdValue !== undefined) {
|
|
||||||
if (typeof cwdValue !== "string" || cwdValue.trim().length === 0) fail(`${label}.cwd must be a nonempty string when provided.`, id);
|
|
||||||
cwd = cwdValue;
|
|
||||||
}
|
|
||||||
|
|
||||||
return { id, agent, task, needs, each, model, cwd };
|
|
||||||
});
|
});
|
||||||
|
|
||||||
const byId = new Map<string, WorkflowStep>();
|
const byId = new Map<string, WorkflowStep>();
|
||||||
|
|||||||
+8
-24
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
import { truncateUtf8Head } from "./output.ts";
|
import { truncateUtf8Head } from "./output.ts";
|
||||||
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
import type { JobSnapshot, PreparedInvocation, PreparedTask } from "./types.ts";
|
||||||
import { workflowValidationError, type WorkflowLimits, type WorkflowPlan } from "./workflow-plan.ts";
|
import { workflowValidationError, type WorkflowLimits, type WorkflowPlan, type WorkflowStep } from "./workflow-plan.ts";
|
||||||
|
|
||||||
/** The design ceiling for one run, independent of the global worker pool. */
|
/** The design ceiling for one run, independent of the global worker pool. */
|
||||||
export const WORKFLOW_MAX_CONCURRENCY = 4;
|
export const WORKFLOW_MAX_CONCURRENCY = 4;
|
||||||
@@ -17,30 +17,20 @@ export const WORKFLOW_MAX_CONCURRENCY = 4;
|
|||||||
/** Standard task-output budget: one prior output may not crowd out the rest. */
|
/** Standard task-output budget: one prior output may not crowd out the rest. */
|
||||||
export const MAX_INTERPOLATED_STEP_OUTPUT_BYTES = 50 * 1024;
|
export const MAX_INTERPOLATED_STEP_OUTPUT_BYTES = 50 * 1024;
|
||||||
|
|
||||||
/** Expanded step prompts are bounded to keep the child brief sane. */
|
|
||||||
export const MAX_EXPANDED_STEP_PROMPT_BYTES = 100 * 1024;
|
|
||||||
|
|
||||||
export interface ExpandedWorkflowStep {
|
|
||||||
id: string;
|
|
||||||
agent: string;
|
|
||||||
needs: string[];
|
|
||||||
task: string;
|
|
||||||
each?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** The run's plan at start; each-steps resolve their item children at release. */
|
/** The run's plan at start; each-steps resolve their item children at release. */
|
||||||
export interface StartPlan {
|
export interface StartPlan {
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
args: string[];
|
args: string[];
|
||||||
steps: ExpandedWorkflowStep[];
|
steps: WorkflowStep[];
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface PreparedWorkflowStep {
|
/** Expanded step prompts are bounded to keep the child brief sane. */
|
||||||
id: string;
|
export const MAX_EXPANDED_STEP_PROMPT_BYTES = 100 * 1024;
|
||||||
needs: string[];
|
|
||||||
|
/** A step plus the agent brief it resolves to; the step shape stays canonical. */
|
||||||
|
export interface PreparedWorkflowStep extends Pick<WorkflowStep, "id" | "needs" | "each"> {
|
||||||
template: string;
|
template: string;
|
||||||
each?: string;
|
|
||||||
prepared: PreparedTask;
|
prepared: PreparedTask;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -95,13 +85,7 @@ export function expandWorkflowPlan(plan: WorkflowPlan): StartPlan {
|
|||||||
name: plan.name,
|
name: plan.name,
|
||||||
description: plan.description,
|
description: plan.description,
|
||||||
args: [...plan.args],
|
args: [...plan.args],
|
||||||
steps: plan.steps.map((step) => ({
|
steps: plan.steps.map((step) => ({ ...step, needs: [...step.needs] })),
|
||||||
id: step.id,
|
|
||||||
agent: step.agent,
|
|
||||||
needs: [...step.needs],
|
|
||||||
task: step.task,
|
|
||||||
each: step.each,
|
|
||||||
})),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,187 @@
|
|||||||
|
/**
|
||||||
|
* Round-trip property for the persisted record schemas.
|
||||||
|
*
|
||||||
|
* The persisted shapes are TypeBox schemas; restore accepts exactly what
|
||||||
|
* `Value.Check` accepts. This property puts generated snapshots through
|
||||||
|
* persist → restore and requires the value to come back equal, so a schema
|
||||||
|
* that drifts from its type (or from what the manager writes) fails here.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import test from "node:test";
|
||||||
|
import fc from "fast-check";
|
||||||
|
import {
|
||||||
|
extractJobSnapshots,
|
||||||
|
extractWorkflowJournals,
|
||||||
|
persistedJob,
|
||||||
|
persistedWorkflowJournal,
|
||||||
|
SUBAGENT_JOB_ENTRY,
|
||||||
|
WORKFLOW_RUN_ENTRY,
|
||||||
|
} from "../src/persistence.ts";
|
||||||
|
import type {
|
||||||
|
JobSnapshot,
|
||||||
|
TaskActivity,
|
||||||
|
TaskSnapshot,
|
||||||
|
UsageStats,
|
||||||
|
WorkflowJournal,
|
||||||
|
WorkflowJournalItem,
|
||||||
|
WorkflowJournalStep,
|
||||||
|
} from "../src/types.ts";
|
||||||
|
import type { WorkflowPlan, WorkflowStep } from "../src/workflow-plan.ts";
|
||||||
|
|
||||||
|
const identifier = fc.stringMatching(/^[A-Za-z_][A-Za-z0-9_-]{0,8}$/);
|
||||||
|
const text = fc.string({ maxLength: 40 });
|
||||||
|
const nonblank = fc.string({ maxLength: 40 }).filter((value) => /\S/.test(value));
|
||||||
|
const finite = fc.integer({ min: 0, max: 1_000_000 });
|
||||||
|
const optional = <T>(arb: fc.Arbitrary<T>): fc.Arbitrary<T | undefined> => fc.option(arb, { nil: undefined });
|
||||||
|
const status = fc.constantFrom("queued", "running", "succeeded", "failed", "skipped", "cancelled", "interrupted");
|
||||||
|
|
||||||
|
const usageArb: fc.Arbitrary<UsageStats> = fc.record({
|
||||||
|
input: finite,
|
||||||
|
output: finite,
|
||||||
|
cacheRead: finite,
|
||||||
|
cacheWrite: finite,
|
||||||
|
cost: finite,
|
||||||
|
contextTokens: finite,
|
||||||
|
turns: finite,
|
||||||
|
});
|
||||||
|
|
||||||
|
const activityArb: fc.Arbitrary<TaskActivity> = fc.record({
|
||||||
|
kind: fc.constantFrom("text", "toolCall", "toolResult"),
|
||||||
|
summary: text,
|
||||||
|
timestamp: finite,
|
||||||
|
isError: optional(fc.boolean()),
|
||||||
|
});
|
||||||
|
|
||||||
|
const taskArb: fc.Arbitrary<TaskSnapshot> = fc.record({
|
||||||
|
agent: text,
|
||||||
|
agentSource: fc.constantFrom("user", "project", "unknown"),
|
||||||
|
task: text,
|
||||||
|
cwd: text,
|
||||||
|
step: optional(fc.integer({ min: 1, max: 10 })),
|
||||||
|
stepId: optional(text),
|
||||||
|
item: optional(fc.integer({ min: 1, max: 10 })),
|
||||||
|
itemValue: optional(text),
|
||||||
|
status,
|
||||||
|
exitCode: fc.oneof(fc.integer(), fc.constant(null)),
|
||||||
|
output: text,
|
||||||
|
outputTruncated: fc.boolean(),
|
||||||
|
outputBytesOmitted: finite,
|
||||||
|
stderr: text,
|
||||||
|
stderrTruncated: fc.boolean(),
|
||||||
|
usage: usageArb,
|
||||||
|
model: optional(text),
|
||||||
|
stopReason: optional(text),
|
||||||
|
errorMessage: optional(text),
|
||||||
|
terminationSignal: optional(text),
|
||||||
|
activity: optional(fc.array(activityArb, { maxLength: 3 })),
|
||||||
|
startedAt: optional(finite),
|
||||||
|
finishedAt: optional(finite),
|
||||||
|
});
|
||||||
|
|
||||||
|
const jobArb: fc.Arbitrary<JobSnapshot> = fc.record({
|
||||||
|
id: text,
|
||||||
|
mode: fc.constantFrom("single", "parallel", "chain", "workflow"),
|
||||||
|
agentScope: fc.constantFrom("user", "project", "both"),
|
||||||
|
projectAgentsDir: fc.oneof(text, fc.constant(null)),
|
||||||
|
projectAgentsDirs: fc.array(text, { maxLength: 3 }),
|
||||||
|
status: fc.constantFrom("queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"),
|
||||||
|
plannedTaskCount: fc.nat({ max: 100 }),
|
||||||
|
results: fc.array(taskArb, { maxLength: 3 }),
|
||||||
|
usage: usageArb,
|
||||||
|
createdAt: finite,
|
||||||
|
startedAt: optional(finite),
|
||||||
|
finishedAt: optional(finite),
|
||||||
|
errorMessage: optional(text),
|
||||||
|
timedOut: optional(fc.boolean()),
|
||||||
|
});
|
||||||
|
|
||||||
|
const stepArb: fc.Arbitrary<WorkflowStep> = fc.record({
|
||||||
|
id: identifier,
|
||||||
|
agent: nonblank,
|
||||||
|
task: nonblank,
|
||||||
|
needs: fc.array(identifier, { maxLength: 3 }),
|
||||||
|
each: optional(identifier),
|
||||||
|
model: optional(nonblank),
|
||||||
|
cwd: optional(nonblank),
|
||||||
|
});
|
||||||
|
|
||||||
|
const planArb: fc.Arbitrary<WorkflowPlan> = fc.record({
|
||||||
|
name: nonblank,
|
||||||
|
description: nonblank,
|
||||||
|
args: fc.array(identifier, { maxLength: 3 }),
|
||||||
|
steps: fc.array(stepArb, { maxLength: 3 }),
|
||||||
|
source: fc.constantFrom("user", "project", "inline"),
|
||||||
|
filePath: nonblank,
|
||||||
|
});
|
||||||
|
|
||||||
|
const argsArb = fc
|
||||||
|
.uniqueArray(fc.tuple(identifier, text), { maxLength: 3, selector: ([key]) => key })
|
||||||
|
.filter((entries) => entries.every(([key]) => key !== "__proto__"))
|
||||||
|
.map((entries) => Object.fromEntries(entries) as Record<string, string>);
|
||||||
|
|
||||||
|
const itemArb: fc.Arbitrary<WorkflowJournalItem> = fc.record({
|
||||||
|
item: fc.integer({ min: 1, max: 100 }),
|
||||||
|
input: text,
|
||||||
|
inputHash: text,
|
||||||
|
status,
|
||||||
|
attempts: fc.nat({ max: 5 }),
|
||||||
|
output: text,
|
||||||
|
outputTruncated: fc.boolean(),
|
||||||
|
outputBytesOmitted: finite,
|
||||||
|
startedAt: optional(finite),
|
||||||
|
finishedAt: optional(finite),
|
||||||
|
});
|
||||||
|
|
||||||
|
const journalStepArb: fc.Arbitrary<WorkflowJournalStep> = fc.record({
|
||||||
|
id: text,
|
||||||
|
inputHash: text,
|
||||||
|
status,
|
||||||
|
attempts: fc.nat({ max: 5 }),
|
||||||
|
output: text,
|
||||||
|
outputTruncated: fc.boolean(),
|
||||||
|
outputBytesOmitted: finite,
|
||||||
|
startedAt: optional(finite),
|
||||||
|
finishedAt: optional(finite),
|
||||||
|
items: fc.array(itemArb, { maxLength: 3 }),
|
||||||
|
});
|
||||||
|
|
||||||
|
const journalArb: fc.Arbitrary<WorkflowJournal> = fc.record({
|
||||||
|
jobId: text,
|
||||||
|
status: fc.constantFrom("queued", "running", "cancelling", "succeeded", "failed", "cancelled", "interrupted"),
|
||||||
|
plan: planArb,
|
||||||
|
args: argsArb,
|
||||||
|
steps: fc.array(journalStepArb, { maxLength: 3 }),
|
||||||
|
usage: usageArb,
|
||||||
|
createdAt: finite,
|
||||||
|
startedAt: optional(finite),
|
||||||
|
finishedAt: optional(finite),
|
||||||
|
errorMessage: optional(text),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** What the session store does to a record: JSON drops absent optionals. */
|
||||||
|
function stored<T>(value: T): T {
|
||||||
|
return JSON.parse(JSON.stringify(value)) as T;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("property: a persisted job snapshot round-trips through restore", () => {
|
||||||
|
fc.assert(
|
||||||
|
fc.property(jobArb, (generated) => {
|
||||||
|
const job = stored(generated);
|
||||||
|
const entry = { type: "custom", customType: SUBAGENT_JOB_ENTRY, data: persistedJob("session-a", job) };
|
||||||
|
assert.deepEqual(extractJobSnapshots([entry]), [job]);
|
||||||
|
}),
|
||||||
|
{ numRuns: 150 },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("property: a persisted workflow journal round-trips through restore", () => {
|
||||||
|
fc.assert(
|
||||||
|
fc.property(journalArb, (generated) => {
|
||||||
|
const journal = stored(generated);
|
||||||
|
const entry = { type: "custom", customType: WORKFLOW_RUN_ENTRY, data: persistedWorkflowJournal("session-a", journal) };
|
||||||
|
assert.deepEqual(extractWorkflowJournals([entry]), [journal]);
|
||||||
|
}),
|
||||||
|
{ numRuns: 150 },
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@ import * as os from "node:os";
|
|||||||
import * as path from "node:path";
|
import * as path from "node:path";
|
||||||
import test, { after } from "node:test";
|
import test, { after } from "node:test";
|
||||||
import fc from "fast-check";
|
import fc from "fast-check";
|
||||||
import { buildWorkflowJournal, workflowItemInputHash, workflowStepInputHash, type WorkflowJournalRun } from "../src/journal.ts";
|
import { buildWorkflowJournal, WORKFLOW_HASH_PAYLOAD_VERSION, workflowItemInputHash, workflowStepInputHash, type WorkflowJournalRun } from "../src/journal.ts";
|
||||||
import type { InternalTask } from "../src/job-state.ts";
|
import type { InternalTask } from "../src/job-state.ts";
|
||||||
import { SubagentManager } from "../src/manager.ts";
|
import { SubagentManager } from "../src/manager.ts";
|
||||||
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts";
|
||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
WORKFLOW_RUN_ENTRY,
|
WORKFLOW_RUN_ENTRY,
|
||||||
} from "../src/persistence.ts";
|
} from "../src/persistence.ts";
|
||||||
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
import { prepareWorkflowInvocation, type PrepareContext } from "../src/prepare.ts";
|
||||||
import { parseWorkflow, type WorkflowPlan } from "../src/workflow-plan.ts";
|
import { parseWorkflow, type WorkflowPlan, type WorkflowSource } from "../src/workflow-plan.ts";
|
||||||
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/types.ts";
|
import { emptyUsage, type JobSnapshot, type TaskSnapshot, type TaskStatus, type WorkflowJournal, type WorkflowJournalItem, type WorkflowJournalStep } from "../src/types.ts";
|
||||||
import { FakeRunner } from "./helpers.ts";
|
import { FakeRunner } from "./helpers.ts";
|
||||||
|
|
||||||
@@ -50,9 +50,16 @@ function makeWorkspace(agentNames = ["scout"]): { cwd: string; ctx: PrepareConte
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function makePlan(steps: Array<Record<string, unknown>>, args: string[] = []): WorkflowPlan {
|
function makePlan(
|
||||||
|
steps: Array<Record<string, unknown>>,
|
||||||
|
args: string[] = [],
|
||||||
|
provenance: { source?: WorkflowSource; filePath?: string } = {},
|
||||||
|
): WorkflowPlan {
|
||||||
const content = `---\n${JSON.stringify({ name: "test-workflow", description: "Test workflow", args, steps }, null, 2)}\n---\n\nNotes.\n`;
|
const content = `---\n${JSON.stringify({ name: "test-workflow", description: "Test workflow", args, steps }, null, 2)}\n---\n\nNotes.\n`;
|
||||||
return parseWorkflow(content, { source: "user", filePath: "/tmp/test-workflow.md" });
|
return parseWorkflow(content, {
|
||||||
|
source: provenance.source ?? "user",
|
||||||
|
filePath: provenance.filePath ?? "/tmp/test-workflow.md",
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function pending(runner: FakeRunner, stepId: string) {
|
function pending(runner: FakeRunner, stepId: string) {
|
||||||
@@ -250,6 +257,20 @@ test("step input hashes are stable across identical inputs and change with args
|
|||||||
workflowStepInputHash(first, "scan", { target: "src" }),
|
workflowStepInputHash(first, "scan", { target: "src" }),
|
||||||
);
|
);
|
||||||
assert.notEqual(workflowStepInputHash(first, "ghost", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
assert.notEqual(workflowStepInputHash(first, "ghost", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
||||||
|
|
||||||
|
// Whole steps are hashed: a step field beyond the brief still moves the hash.
|
||||||
|
const withCwd = makePlan([{ id: "scan", agent: "scout", task: "scan {args.target}", cwd: "src" }], ["target"]);
|
||||||
|
assert.notEqual(workflowStepInputHash(withCwd, "scan", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
||||||
|
|
||||||
|
// Provenance is not an input: the same plan copied elsewhere hashes alike.
|
||||||
|
const elsewhere = makePlan(steps, ["target"], { source: "project", filePath: "/repo/.pi/workflows/test-workflow.md" });
|
||||||
|
assert.equal(workflowStepInputHash(elsewhere, "scan", { target: "src" }), workflowStepInputHash(first, "scan", { target: "src" }));
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the input-hash payload carries the replay-contract version", () => {
|
||||||
|
// Nothing replays today (ADR 0004 journal-only); the marker only separates
|
||||||
|
// hash eras, so moving it is a deliberate migration, never a refactor.
|
||||||
|
assert.equal(WORKFLOW_HASH_PAYLOAD_VERSION, 2);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("journals hash the step inputs, not the outputs, so identical runs agree", async () => {
|
test("journals hash the step inputs, not the outputs, so identical runs agree", async () => {
|
||||||
|
|||||||
Reference in new issue
Block a user