/** * Persistence for taskflow definitions and run state. * * Definitions: .pi/taskflows/.json (project) * ~/.pi/agent/taskflows/.json (user) * Run state: .pi/taskflows/runs//.json * Index: .pi/taskflows/runs/index.json (lookup accelerator) * * Legacy layout (v0.0.8 and earlier): * .pi/taskflows/runs/.json (flat, still readable) * * v0.0.9 refactor: per-flow subdirectory layout + lightweight index + file * lock + TTL/cap cleanup. Full backward compatibility with the flat layout * is maintained: loadRun and listRuns still discover legacy flat files. */ import type { Taskflow } from "./schema.ts"; import { type DirectoryIdentity } from "./cwd-bridge.ts"; import type { UsageStats } from "./usage.ts"; import type { DeclaredDeps } from "./flowir/meta.ts"; import type { ScorerResult } from "./scorers.ts"; import type { FlowMeta } from "./library/types.ts"; export interface SavedFlow { name: string; scope: "user" | "project"; /** Canonical physical definition path captured by the stable loader. */ filePath: string; /** Identity of the canonical definition directory at load time. */ sourceDirIdentity: DirectoryIdentity; def: Taskflow; } /** * Outcome of loading a user-authored file from disk. Failure is discriminated * by `reason` so callers can tell the user *why* it failed (and where): * * - `missing` — the file does not exist / is unreadable. * - `unparseable`— the file exists but failed to parse; `detail` carries the * underlying error (e.g. a V8 `SyntaxError` with byte offset * + line/column), so flow authors can fix it in seconds. * * This replaces the old `T | null` contract that collapsed both cases into * `null` and produced messages like "not found or unparseable" — which hid the * real cause and the exact position of a malformed token. */ export type LoadResult = { ok: true; value: T; } | { ok: false; reason: "missing" | "unparseable"; path: string; detail: string; }; /** Build a single-line, user-facing message from a failed `LoadResult`. */ export declare function describeLoadFailure(r: Extract, { ok: false; }>, what: string): string; /** @internal */ export type PhaseStatus = "pending" | "running" | "done" | "failed" | "skipped"; export interface PhaseState { id: string; status: PhaseStatus; /** Persisted execution policy for dynamically promoted phases. Parent-level * terminal accounting cannot look these ids up in the original definition. */ optional?: boolean; output?: string; /** True only when a failed phase's output contains a genuine partial answer * rather than a transport diagnostic/placeholder. */ partialOutput?: true; json?: unknown; usage?: UsageStats; model?: string; error?: string; inputHash?: string; /** When this result was served from cache instead of executed: * 'cross-run' = restored from the persistent cross-run store; * 'run-only' = within-run resume (a prior attempt with the same inputHash). * A phase with this set spent no new tokens this run. */ cacheHit?: "cross-run" | "run-only"; startedAt?: number; endedAt?: number; /** Live fan-out progress for map/parallel phases. */ subProgress?: { done: number; total: number; running: number; failed: number; }; /** Latest activity line from the running subagent(s). */ liveText?: string; /** Gate verdict (gate phases only). */ gate?: { verdict: "pass" | "block"; reason?: string; /** Deterministic scorer results (score gates only). Present whenever the * gate declared `score` and the scorers actually ran. `combined` is the * [0,1] combined score; `threshold` echoes the configured cutoff. */ scores?: { results: ScorerResult[]; combined: number; threshold?: number; }; }; /** True when this phase declared `idempotent: false` (irreversible side * effects). Such a phase is never cached (in any scope) and transient * provider errors are not auto-retried. De facto mutually exclusive with * `cacheHit` (caching is disabled for side-effecting phases). */ sideEffect?: true; /** Total subagent attempts incl. retries (when > calls, a retry happened). */ attempts?: number; /** True when the phase's `timeout` cap expired and the subagent was aborted. * The phase fails (status "failed") — this marker distinguishes a timeout * from an ordinary failure for renderers and post-hoc inspection. */ timedOut?: boolean; /** True when a map/parallel fan-out was cut short by the budget cap, or by the * dynamic sub-flow fan-out safety limit (MAX_DYNAMIC_MAP_ITEMS). */ budgetTruncated?: boolean; /** Human-in-the-loop outcome (approval phases only). */ approval?: { decision: "approve" | "reject" | "edit"; note?: string; auto?: boolean; }; /** Loop iteration accounting (loop phases only). `reflexion` is the last * failure summary injected into an iteration (audit trail for reflexion loops). * `failures` records each failed iteration's (sanitized) error — useful when a * reflexion loop continues past failures and only the terminal one would * otherwise survive in `error`. Bounded (most-recent kept). */ loop?: { iterations: number; stop: "until" | "converged" | "maxIterations" | "failed" | "aborted"; reflexion?: string; failures?: Array<{ iteration: number; error: string; }>; }; /** Tournament outcome (tournament phases only). */ tournament?: { variants: number; winner: number; mode: "best" | "aggregate"; reason?: string; }; /** Set when a `flow { def }` inline sub-flow definition could not be resolved, * parsed, validated, or verified. The phase fails-open: this records why. */ defError?: string; /** Child states promoted by an expand:graft phase. Retained on the expand * result so a within-run resume cache hit can restore the same parent DAG. */ promotedPhases?: Record; /** Non-fatal diagnostic warnings accumulated during this phase (e.g. * unresolved interpolation placeholders, suspicious templates). */ warnings?: string[]; /** Observed readSet (M3): the upstream phase outputs this phase actually * consumed at interpolation time — not what it *declared* to depend on * (dependsOn), but what it truly *read* (`{steps.X...}`). Each entry * carries the version (= the read phase's inputHash) it consumed, so a * later staleness check (M4/M5) can tell whether the upstream has moved. * This is the overstory "observed readSet@version" moat: no other * orchestrator records what a result actually depended on. */ reads?: Array<{ stepId: string; version?: string; }>; /** Truncated previews of interpolated strings used to execute this phase, * useful when diagnosing why a model saw a literal placeholder. */ interpolation?: Array<{ source: string; text: string; missing?: string[]; }>; /** Prompt-size diagnostics for this phase's subagent call(s). Durable * (persisted) so post-hoc inspection can surface oversized prompts and * account for input size in reduce rounds. `calls` has one entry per * resolved subagent prompt (one for an agent phase; multiple for a tree * reduce). `reduceInputs` carries aggregate stats over the inputs being * reduced (reduce phases only). The token estimate is a conservative * `ceil(chars/4)` approximation, NOT a real tokenizer count. */ promptStats?: { calls: Array<{ bytes: number; chars: number; estTokens: number; }>; reduceInputs?: { count: number; totalBytes: number; totalChars: number; totalEstTokens: number; }; }; } export interface RunState { runId: string; flowName: string; def: Taskflow; args: Record; status: "running" | "completed" | "failed" | "paused" | "blocked"; phases: Record; createdAt: number; updatedAt: number; cwd: string; /** Canonical source file for a saved flow or defineFile invocation. Runtime * provenance only: inline definitions omit it, and flow data cannot set it. */ flowSourceFile?: string; /** Physical identity of `dirname(flowSourceFile)` captured atomically with the * definition. Revalidated immediately before a flow-relative script spawn. */ flowSourceDirIdentity?: DirectoryIdentity; /** Root identity captured by a host when it creates the run. This closes the * detached launch window, but does not itself grant/taint cwd-bridge use. */ invocationRootSnapshot?: DirectoryIdentity; /** Immutable root binding set only after this run actually activates the cwd * bridge. Its presence is the persisted authority/taint marker. */ cwdRootBinding?: DirectoryIdentity; /** OS PID of a detached runner process (set only for background runs). */ pid?: number; /** Foreground host instance that owns a running checkpoint. startedAt is * audit metadata, not an OS birth token. Missing/unobservable owner identity * must never be interpreted as proof that execution stopped. */ foregroundOwner?: { version: 1; pid: number; instanceId: string; startedAt: number; approvalWait?: string[]; }; /** Audit of the narrow approval checkpoint recovered into this fork. */ foregroundInterruption?: { kind: "approval-owner-exit"; ownerPid: number; ownerInstanceId: string; detectedAt: number; }; /** True for runs spawned via `detach: true` (background execution). */ detached?: boolean; /** Wall-clock launch time for detached lifecycle/orphan diagnostics. */ detachedStartedAt?: number; /** Version of the durable detached-control protocol understood by the * worker. Missing means a legacy detached run that cannot safely accept * cross-request lifecycle commands. */ detachedControlVersion?: number; /** Unforgeable identity for one detached worker instance. Unlike a PID, this * value cannot be silently reused by an unrelated OS process. */ detachedInstanceId?: string; /** Retention policy frozen at detached dispatch so crash/orphan writes do * not silently fall back to another session's defaults. */ detachedRetention?: { maxKeep: number; maxAgeDays: number; }; /** Durable audit record for the cancellation request that paused this run. */ detachedCancel?: { requestedAt: number; reason?: string; }; /** Final output persisted by a detached runner for later wait/status calls. */ finalOutput?: string; /** Phase whose output supplied `finalOutput`, when attributable. */ outputSourcePhaseId?: string; /** Content fingerprint of the desugared flow definition (overstory hash * algorithm). Folded into every phase's cache key so a structural change * to the flow always invalidates cross-run cache hits — and an identical * re-run always reuses them. Filled once at run start; persisted for * audit/resume consistency. */ flowDefHash?: string | "failed"; /** Per-phase *declared* dependency footprint (M2), synthesized at compile * time from `{steps.X}` interpolation refs via `compileTaskflowToIR`. * This is the *declared* plane — distinct from the *observed* readSet * (`PhaseState.reads`, captured at runtime). Recompute staleness uses the * **union** (observed ∪ declared) so a declared-but-unobserved edge (e.g. * a `when` ref that never fired) still propagates. JSON-safe `Record` * shape so it round-trips through persistence. Audit/provenance only — * recompute derives this fresh from `def` so old runs (pre-H1) also get * union semantics. */ declaredDeps?: Record; /** Per-phase structural sub-fingerprints (M6). Computed once per run * alongside `flowDefHash`. Each value is either a precise per-phase hash * (when sound) or the whole-flow `flowDefHash` (fallback for * shareContext / `flow` phases). Folded into the cross-run cache key as * `v3:phasefp:` so editing phase B invalidates only B + its * transitive dependents. Audit/resume only — recompute derives fresh. */ phaseFingerprints?: Record; /** Package version of the engine that created/wrote this run (best-effort * audit). Absent on pre-0.2.0-metadata runs. */ packageVersion?: string; /** Git commit the engine dist was built from (`"unknown"` in source/dev * checkouts). Audit only; never used to gate behavior. */ gitCommit?: string; /** Which host wrote this run: `"pi"` for the Pi adapter, or the MCP host * identity (`"codex"`/`"claude"`/`"opencode"`/`"grok"`) for MCP runs. */ host?: string; /** Run-state schema version (see CURRENT_RUN_STATE_SCHEMA_VERSION). Absent * on pre-0.2.0-metadata runs (treated as the baseline). */ schemaVersion?: number; /** When this run is a resume fork (0.2.0 dogfood issue 5): the runId of the * parent run this one forked from. Absent for ordinary runs. */ parentRunId?: string; } export interface RunIndexEntry { runId: string; flowName: string; /** Invocation cwd used to bind user-private detached lifecycle records. * Absent on historical indexes; callers must retain a safe fallback. */ cwd?: string; status: RunState["status"]; createdAt: number; updatedAt: number; /** Path relative to runsRoot, e.g. "test-flow/test-roundtrip-001.json". */ relPath: string; /** Which host wrote this run (0.2.0 dogfood issue 4): "pi" or the MCP * host identity. Absent on pre-0.2.0-metadata runs. */ host?: string; /** Package version of the engine that wrote this run (audit). Absent on * pre-0.2.0-metadata runs. */ packageVersion?: string; /** Parent runId when this run is a resume fork (issue 5). Absent for * ordinary runs. */ parentRunId?: string; } export declare const DEFAULT_KEPT_RUNS = 100; export declare const DEFAULT_RUN_AGE_DAYS = 30; /** * Sanitise a flow name into a safe directory name. Same regex used by * saveFlow/newRunId — but that regex keeps `.` in its allow-list, so a * flowName of "." or ".." would pass through unchanged and let `flowRunDir` * resolve OUTSIDE the runs root (write-side path traversal). `def.name` is * internally derived and TypeBox only enforces Type.String() with no charset, * so a Taskflow literally named ".." is schema-valid. We therefore reject * bare-dot / leading-dot components after the character substitution so the * write path can never escape runs/ (risk-reviewer v0.0.9 audit, H1). */ export declare function safeFlowDirName(flowName: string): string; /** Return the path to a run's deterministic-replay trace (append-only JSONL). * Sibling to `.json` in the same per-flow dir. Best-effort: the file * only exists if a TraceSink was injected for the run. */ export declare function traceFilePath(runsRoot: string, flowName: string, runId: string): string; /** * Validate that a runId looks safe before performing any filesystem access. * Legitimate runIds are produced by newRunId() and contain only [A-Za-z0-9._-]. */ export declare function validateRunId(runId: string): boolean; /** * Execute `fn` while holding a file lock. Guarantees release even on throw. */ export declare function withLock(lockPath: string, fn: () => T, timeoutMs?: number): T; /** * Extract a RunIndexEntry from a RunState + computed relative path. * Exported for tests; pure. */ export declare function extractIndexEntry(state: RunState, relPath: string): RunIndexEntry; /** Tighter cap for included phase instructions (not the flow DAG itself). */ export declare const MAX_TASK_FILE_BYTES = 262144; export interface LoadedDefineFile { value: unknown; filePath: string; sourceDirIdentity: DirectoryIdentity; } /** Inline each `taskFile` into `task` and delete the field. Trusted loaders only. */ export declare function materializeTaskFiles(def: unknown, provenance: { filePath: string; sourceDirIdentity: DirectoryIdentity; }): LoadResult; /** Stable defineFile loader used by execution hosts that need source provenance. */ export declare function readDefineFileWithSource(filePath: string, allowedRootReal?: string | readonly string[]): LoadResult; export declare function readDefineFile(filePath: string): LoadResult; /** Internal-but-exported for tests: walk-up `.pi` finder with home-dir stop. */ export declare function findProjectFlowsDir(cwd: string, create?: boolean): string | null; /** List all saved flows (project overrides user on name collision). */ export declare function listFlows(cwd: string): SavedFlow[]; export declare function getFlow(cwd: string, name: string): SavedFlow | null; /** * Resolve a saved flow by name with diagnosable failure. Unlike `getFlow` * (which returns `null` for both "no such flow" and "file exists but corrupt", * because corrupt files are excluded from `listFlows`), this consumes the same * bounded discovery snapshot and reports a matching corrupt candidate without * rescanning the namespace. */ export declare function getFlowDiagnosed(cwd: string, name: string): LoadResult; export declare function saveFlow(cwd: string, def: Taskflow, scope?: "user" | "project"): { filePath: string; }; /** Path to a flow's library sidecar. Uses the SAME safeFlowDirName as the flow * file itself (N1 fix) so path-safety normalization is consistent. */ export declare function sidecarPathFor(cwd: string, flowName: string, scope?: "user" | "project"): string; /** Read a flow's library sidecar. Returns a `LoadResult`; missing/unparseable * are discriminated by `reason`. */ export declare function readMeta(cwd: string, flowName: string): LoadResult; /** Read a sidecar next to a specific flow file (avoids name→scope lookup when * we already have the SavedFlow from listFlows). */ export declare function readMetaNextTo(flowFilePath: string): LoadResult; /** Write a flow + its sidecar atomically (same withLock critical section — R2). * Embedding (Phase 2) is computed by the caller BEFORE this call and passed in * via meta; this function does only synchronous I/O under the lock (R2R3). */ export declare function saveFlowWithMeta(cwd: string, def: Taskflow, meta: FlowMeta, scope?: "user" | "project"): { filePath: string; metaPath: string; }; /** Bump reuseCount/lastUsedAt for a flow's sidecar. Idempotent under the flow * lock. If no sidecar exists yet, creates a minimal one carrying just the * reuse bookkeeping (structural fields are filled next time the flow is * re-saved with deriveMeta). Returns the new reuseCount, or null if the flow * itself doesn't exist. */ export declare function bumpReuseInSidecar(cwd: string, flowName: string): number | null; export declare function runsDir(cwd: string): string; /** * User-private control directory for one invocation root. * * Cancellation and process-registry markers must not live below a repository: * a checked-out `.pi` tree can contain symlinks controlled by project content. * Bind the control plane to the canonical directory identity and keep only its * digest in the user agent directory, so sibling worktrees remain isolated. */ export declare function detachedControlDir(cwd: string): string; /** Root dir for the cross-run memoization cache (sibling of `runs`). */ export declare function cacheDir(cwd: string): string; export declare function newRunId(flowName: string): string; /** * Persist a run state to disk. * * v0.0.9: writes to `runs//.json` (per-flow * subdirectory) and updates the lightweight index. Uses a per-run file lock * to prevent concurrent writes to the same runId. After the write, runs * opportunistic cleanup of expired terminal runs. * * F-009: shallow-clones state before stamping updatedAt to avoid mutating the * caller's reference. */ export declare function saveRun(state: RunState, cleanup?: { maxKeep?: number; maxAgeDays?: number; }): void; /** * Load a single run by runId. * * Lookup chain (fast → slow): * 1. INDEX — read index.json, find entry with matching runId, read via relPath. * 2. SUBDIR SCAN — for each subdirectory in runsDir, check /.json. * 3. FLAT FALLBACK — check runsDir/.json directly (legacy layout). * * All existing path-traversal, symlink, and realpath guards are preserved for * every path touched. */ /** * Diagnosable variant of `loadRun`. Returns a `LoadResult` so callers can tell * the user *why* a runId didn't resolve: a file exists for it but is corrupt * (`reason: "unparseable"`, with the parse error in `detail`) versus genuinely * absent (`reason: "missing"`). Used by user-facing paths (resume / show / * provenance / why-stale / recompute). Internal polling keeps the plain * `loadRun` (RunState | null) for API stability. */ export declare function loadRunDiagnosed(cwd: string, runId: string): LoadResult; export declare function loadRun(cwd: string, runId: string): RunState | null; /** * List recent runs, sorted by updatedAt descending. * * v0.0.9: reads from index first, then merges any legacy flat files not yet in * the index. If the index is missing/corrupt, calls rebuildIndex for * self-healing. * * F-010: drops records with non-numeric/NaN updatedAt before sorting. */ export declare function listRuns(cwd: string, limit?: number): RunState[]; /** Stable hash of a phase's resolved task + inputs, for resume caching. */ export declare function hashInput(...parts: string[]): string; /** * Check whether a process with the given PID is still alive. * Uses signal 0 (no signal sent) — succeeds if the process exists and we have * permission to signal it, throws ESRCH if it doesn't exist. */ export type ProcessLiveness = "alive" | "dead" | "unknown"; export declare function probeProcess(pid: number, signalZero?: (pid: number, signal: 0) => unknown): ProcessLiveness; /** Back-compatible boolean probe. Unknown is conservatively treated as alive. */ export declare function isProcessAlive(pid: number): boolean; /** * Write a file atomically: write to a unique temp file in the same directory, * then rename over the target (rename is atomic on the same filesystem). Prevents * a crash or concurrent write from leaving a half-written, corrupt JSON file. */ export declare function writeFileAtomic(filePath: string, data: string, guard?: () => void): void; //# sourceMappingURL=store.d.ts.map