diff --git a/src/journal.ts b/src/journal.ts index fa95f33..685e4e1 100644 --- a/src/journal.ts +++ b/src/journal.ts @@ -19,7 +19,7 @@ import type { WorkflowJournalItem, WorkflowJournalStep, } 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"; /** @@ -39,23 +39,20 @@ function canonical(value: unknown): string { return JSON.stringify(value); } -function planInputs(plan: WorkflowPlan): unknown { - // Provenance (source, filePath) is where the plan came from, not what it asks - // for; the same plan copied elsewhere keeps its step hashes. - return { - name: plan.name, - description: plan.description, - args: plan.args, - steps: plan.steps.map((step: WorkflowStep) => ({ - id: step.id, - agent: step.agent, - task: step.task, - needs: step.needs, - each: step.each, - model: step.model, - cwd: step.cwd, - })), - }; +/** + * Bumped when the hash payload changes shape, so a future replay layer can tell + * which era a persisted hash came from. Version 2 hashed whole plan steps. + */ +export const WORKFLOW_HASH_PAYLOAD_VERSION = 2; + +/** + * The plan as the replay contract sees it: steps whole, so a new step field is + * hashed by default. Provenance (source, filePath) is where the plan came from, + * not what it asks for; the same plan copied elsewhere keeps its step hashes. + */ +function planHashInput(plan: WorkflowPlan): Omit { + const { source: _source, filePath: _filePath, ...inputs } = plan; + return inputs; } /** @@ -65,7 +62,7 @@ function planInputs(plan: WorkflowPlan): unknown { * identical hashes across runs. */ export function workflowStepInputHash(plan: WorkflowPlan, stepId: string, args: Readonly>): 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")}`; } @@ -81,7 +78,7 @@ export function workflowItemInputHash( args: Readonly>, item: 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")}`; } diff --git a/src/persistence.ts b/src/persistence.ts index c1c2501..320167a 100644 --- a/src/persistence.ts +++ b/src/persistence.ts @@ -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 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 { return { version: 1, sessionId, job: structuredClone(job) }; } @@ -27,136 +33,16 @@ function record(value: unknown): value is Record { 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[] { const snapshots: JobSnapshot[] = []; for (const entry of entries) { - if (!record(entry) || entry.type !== "custom" || entry.customType !== SUBAGENT_JOB_ENTRY || !record(entry.data)) continue; - if (entry.data.version !== 1 || !validJob(entry.data.job)) continue; + if (!record(entry) || entry.type !== "custom" || entry.customType !== SUBAGENT_JOB_ENTRY) continue; + if (!Value.Check(PersistedJobSchema, entry.data)) continue; snapshots.push(structuredClone(entry.data.job)); } 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. * @@ -167,8 +53,8 @@ function validJournal(value: unknown): value is WorkflowJournal { export function extractWorkflowJournals(entries: unknown[]): WorkflowJournal[] { const byJob = new Map(); for (const entry of entries) { - if (!record(entry) || entry.type !== "custom" || entry.customType !== WORKFLOW_RUN_ENTRY || !record(entry.data)) continue; - if (entry.data.version !== 1 || !validJournal(entry.data.journal)) continue; + if (!record(entry) || entry.type !== "custom" || entry.customType !== WORKFLOW_RUN_ENTRY) continue; + if (!Value.Check(PersistedWorkflowJournalSchema, entry.data)) continue; byJob.set(entry.data.journal.jobId, structuredClone(entry.data.journal)); } return Array.from(byJob.values()); diff --git a/src/schemas.ts b/src/schemas.ts index 76c1cc7..b6aefc7 100644 --- a/src/schemas.ts +++ b/src/schemas.ts @@ -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 - * invocation request. `prepare.ts` consumes the inferred static types; the - * tool registration in `index.ts` can hand the schemas straight to Pi. + * The request schemas are the single source of truth for the wire/JSON shape + * of an invocation request. The record schemas are the single source of truth + * 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 { WorkflowPlanSchema } from "./workflow-plan.ts"; /** * Which agent directories an invocation may read. @@ -142,3 +146,200 @@ export const UltraParams = Type.Object( ); export type UltraParamsType = Static; + +/** + * 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; + +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; + +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; + +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; + +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; +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; + +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; + +/** 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; + +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; + +/** 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; + +/** 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; + +/** 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; diff --git a/src/types.ts b/src/types.ts index 2cf3279..3fcaf17 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,11 +1,25 @@ import type { ThinkingLevel } from "@earendil-works/pi-agent-core"; import type { Message } from "@earendil-works/pi-ai"; 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"; -export type TaskStatus = "queued" | "running" | "succeeded" | "failed" | "skipped" | "cancelled" | "interrupted"; +/** + * Persisted record types live with their TypeBox schemas in `schemas.ts`. + * 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 { model?: string; @@ -35,16 +49,6 @@ export interface PreparedInvocation { dispatchDefaults: DispatchDefaults; } -export interface UsageStats { - input: number; - output: number; - cacheRead: number; - cacheWrite: number; - cost: number; - contextTokens: number; - turns: number; -} - export interface RunResult { agent: string; agentSource: "user" | "project" | "unknown"; @@ -76,44 +80,6 @@ export interface TaskRunner { run(task: PreparedTask, defaults: DispatchDefaults, options: RunOptions): Promise; } -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. */ export interface TaskIdentity { agent: string; @@ -126,23 +92,6 @@ export interface TaskIdentity { 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 { status: JobStatus; results: RunResult[]; @@ -162,53 +111,6 @@ export interface SyncRunOptions { 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; - steps: WorkflowJournalStep[]; - usage: UsageStats; - createdAt: number; - startedAt?: number; - finishedAt?: number; - errorMessage?: string; -} - export interface ManagerOptions { maxWorkers?: number; maxActiveJobs?: number; diff --git a/src/workflow-plan.ts b/src/workflow-plan.ts index cbcb5b0..e4195d8 100644 --- a/src/workflow-plan.ts +++ b/src/workflow-plan.ts @@ -12,6 +12,8 @@ import * as fs from "node:fs"; import * as path from "node:path"; 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_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 * 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; export type WorkflowScope = "user" | "project" | "both"; /** Stable provenance literal for a plan with no file behind it. */ export const INLINE_WORKFLOW_FILE_PATH = "ultra:inline"; -export interface WorkflowStep { - id: string; - agent: string; - task: string; - needs: string[]; - /** Source step id for an each-step, normalized from `{steps..output}`. */ - each?: string; - model?: string; - cwd?: string; -} +const IDENTIFIER_SOURCE = "^[A-Za-z_][A-Za-z0-9_-]*$"; +/** A string with at least one non-whitespace character: "nonempty" for YAML. */ +const NONBLANK = "\\S"; +const IDENTIFIER = new RegExp(IDENTIFIER_SOURCE); -export interface WorkflowPlan { - name: string; - description: string; - args: string[]; - steps: WorkflowStep[]; - source: WorkflowSource; - filePath: string; -} +/** + * The canonical step shape: the one field list. + * + * Parsing validates raw frontmatter against this schema, the journal hashes + * plan steps whole, and the persisted plan restores them. A new step field is + * declared here once and reaches every consumer, including the input hash, + * 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..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; + +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; export interface ParseWorkflowOptions { source: WorkflowSource; @@ -110,8 +140,6 @@ export function workflowValidationError( } 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_KEY = /^steps\.([A-Za-z_][A-Za-z0-9_-]*)\.output$/; const ARG_REFERENCE = /\{args\.([A-Za-z_][A-Za-z0-9_-]*)\}/g; @@ -180,6 +208,26 @@ function unknownFields(record: Record, allowed: readonly string 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 { const { source, filePath } = options; 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.`); } + const stepFieldNames = Object.keys(WorkflowStepSchema.properties); const steps: WorkflowStep[] = stepList.map((raw: unknown, index: number) => { if (!isRecord(raw)) fail(`steps[${index}] must be a mapping.`); const stepRecord = raw as Record; - const id = stepRecord.id; - if (typeof id !== "string" || id.trim().length === 0) fail(`steps[${index}].id must be a nonempty string.`); - if (!IDENTIFIER.test(id)) { - fail(`steps[${index}].id "${id}" is not a valid step id (letters, digits, "_" or "-", not starting with a digit).`); - } - const label = `steps[${index}] ("${id}")`; + const rawId = stepRecord.id; + const label = typeof rawId === "string" && rawId.trim().length > 0 + ? `steps[${index}] ("${rawId}")` + : `steps[${index}]`; + const stepId = typeof rawId === "string" && rawId.trim().length > 0 ? rawId : undefined; - const extraFields = unknownFields(stepRecord, STEP_FIELDS); + const extraFields = unknownFields(stepRecord, stepFieldNames); 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; - if (typeof agent !== "string" || agent.trim().length === 0) fail(`${label}.agent must be a nonempty string.`, id); - const task = stepRecord.task; - if (typeof task !== "string" || task.trim().length === 0) fail(`${label}.task must be a nonempty string.`, id); - - const needs: string[] = []; - if (stepRecord.needs !== undefined) { - if (!Array.isArray(stepRecord.needs)) fail(`${label}.needs must be a list of step ids.`, id); - for (const [needIndex, need] of stepRecord.needs.entries()) { - if (typeof need !== "string" || need.trim().length === 0) fail(`${label}.needs[${needIndex}] must be a nonempty step id.`, id); - needs.push(need); - } + // `needs` default to none; the two YAML spellings of `each` both collapse + // to the source step id, so the schema checks one canonical form. + const each = parseEachReference(stepRecord.each); + if (stepRecord.each !== undefined && each === undefined) { + fail(`${label}.each must be a "{steps..output}" reference, got ${JSON.stringify(stepRecord.each)}.`, stepId); + } + const candidate: Record = { + ...stepRecord, + needs: stepRecord.needs ?? [], + each, + }; + 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; - if (stepRecord.each !== undefined) { - each = parseEachReference(stepRecord.each); - if (each === undefined) { - fail(`${label}.each must be a "{steps..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); + const step = candidate; + if (step.each === undefined && step.task.includes("{item}")) { + fail(`${label}.task contains {item}, but {item} is only valid in a step with \`each\`.`, stepId); } - let model: string | undefined; - 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 }; + return { id: step.id, agent: step.agent, task: step.task, needs: step.needs, each: step.each, model: step.model, cwd: step.cwd }; }); const byId = new Map(); diff --git a/src/workflow-run.ts b/src/workflow-run.ts index 5b9ee52..08fe0cf 100644 --- a/src/workflow-run.ts +++ b/src/workflow-run.ts @@ -9,7 +9,7 @@ import { truncateUtf8Head } from "./output.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. */ 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. */ 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. */ export interface StartPlan { name: string; description: string; args: string[]; - steps: ExpandedWorkflowStep[]; + steps: WorkflowStep[]; } -export interface PreparedWorkflowStep { - id: string; - needs: string[]; +/** Expanded step prompts are bounded to keep the child brief sane. */ +export const MAX_EXPANDED_STEP_PROMPT_BYTES = 100 * 1024; + +/** A step plus the agent brief it resolves to; the step shape stays canonical. */ +export interface PreparedWorkflowStep extends Pick { template: string; - each?: string; prepared: PreparedTask; } @@ -95,13 +85,7 @@ export function expandWorkflowPlan(plan: WorkflowPlan): StartPlan { name: plan.name, description: plan.description, args: [...plan.args], - steps: plan.steps.map((step) => ({ - id: step.id, - agent: step.agent, - needs: [...step.needs], - task: step.task, - each: step.each, - })), + steps: plan.steps.map((step) => ({ ...step, needs: [...step.needs] })), }; } diff --git a/test/persistence.test.ts b/test/persistence.test.ts new file mode 100644 index 0000000..29b4e83 --- /dev/null +++ b/test/persistence.test.ts @@ -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 = (arb: fc.Arbitrary): fc.Arbitrary => fc.option(arb, { nil: undefined }); +const status = fc.constantFrom("queued", "running", "succeeded", "failed", "skipped", "cancelled", "interrupted"); + +const usageArb: fc.Arbitrary = fc.record({ + input: finite, + output: finite, + cacheRead: finite, + cacheWrite: finite, + cost: finite, + contextTokens: finite, + turns: finite, +}); + +const activityArb: fc.Arbitrary = fc.record({ + kind: fc.constantFrom("text", "toolCall", "toolResult"), + summary: text, + timestamp: finite, + isError: optional(fc.boolean()), +}); + +const taskArb: fc.Arbitrary = 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 = 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 = 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 = 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); + +const itemArb: fc.Arbitrary = 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 = 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 = 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(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 }, + ); +}); diff --git a/test/workflow-journal.test.ts b/test/workflow-journal.test.ts index 6d7a1f9..f9db872 100644 --- a/test/workflow-journal.test.ts +++ b/test/workflow-journal.test.ts @@ -4,7 +4,7 @@ import * as os from "node:os"; import * as path from "node:path"; import test, { after } from "node:test"; 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 { SubagentManager } from "../src/manager.ts"; import { MAX_TASK_OUTPUT_BYTES, truncateUtf8Head } from "../src/output.ts"; @@ -17,7 +17,7 @@ import { WORKFLOW_RUN_ENTRY, } from "../src/persistence.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 { FakeRunner } from "./helpers.ts"; @@ -50,9 +50,16 @@ function makeWorkspace(agentNames = ["scout"]): { cwd: string; ctx: PrepareConte }; } -function makePlan(steps: Array>, args: string[] = []): WorkflowPlan { +function makePlan( + steps: Array>, + 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`; - 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) { @@ -250,6 +257,20 @@ test("step input hashes are stable across identical inputs and change with args 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 () => {