pi-better-harness 0.53.0 → 0.54.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/README.md +24 -0
- package/extensions/settings/copy.ts +3 -0
- package/extensions/settings/page.ts +1 -1
- package/extensions/task-context/dynamic-workflow-runtime.ts +185 -0
- package/extensions/task-context/dynamic-workflow-view.ts +176 -0
- package/extensions/task-context/dynamic-workflow.ts +142 -0
- package/extensions/task-context/index.ts +99 -13
- package/extensions/task-context/plan-presentation.ts +1 -1
- package/extensions/task-context/plan-widget.ts +5 -2
- package/extensions/task-context/workflow-diagram.ts +72 -0
- package/extensions/task-context/workflow-plan.ts +99 -56
- package/lib/instructions.mjs +18 -10
- package/node_modules/pi-better-background-tasks/package.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
- package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-goal/package.json +1 -1
- package/node_modules/pi-better-goal/src/command-binding.ts +10 -3
- package/node_modules/pi-better-goal/src/index.ts +9 -8
- package/node_modules/pi-better-goal/src/task-context.ts +2 -0
- package/node_modules/pi-better-goal/src/workflow-gates.ts +3 -1
- package/node_modules/pi-better-subagents/index.ts +7 -2
- package/node_modules/pi-better-subagents/output-payload.ts +2 -0
- package/node_modules/pi-better-subagents/package.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
- package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
- package/node_modules/pi-better-subagents/tools.ts +3 -2
- package/node_modules/pi-better-subagents/workflow-assignment.ts +35 -0
- package/package.json +4 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.54.0] - 2026-11-25
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Run task-defined workflows and display their progress in Todo. (#904)
|
|
8
|
+
- Show the Rush review and fix loop alongside delivery progress. A shipped unit counts as reviewed only when its recorded review matches the delivered commit.
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
|
|
12
|
+
- Reject a replacement Todo when reopening an Outcome that owns a workflow plan. Keep the original plan available to its scheduler.
|
|
13
|
+
- Skip the instructions lock for unmarked dotfiles during sync and disable, so read-only dotfile directories can keep Harness instructions off.
|
|
14
|
+
- Bundle Goal 0.16.2, Background Tasks 0.20.3, and Subagents 0.38.0 with Server 0.7.3.
|
|
15
|
+
|
|
3
16
|
## [0.53.0] - 2026-11-23
|
|
4
17
|
|
|
5
18
|
### Added
|
package/README.md
CHANGED
|
@@ -65,6 +65,30 @@ Existing Plan session histories restore as Todo. Workflow task-plan files and
|
|
|
65
65
|
revision checks stay unchanged; skills continue using their own records when the
|
|
66
66
|
optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
|
|
67
67
|
|
|
68
|
+
### Dynamic workflows
|
|
69
|
+
|
|
70
|
+
Run `/dynamic-workflow` to plan the current task once. In `/harness-settings`,
|
|
71
|
+
**Automatic dynamic workflows** defaults to **off**. **On** lets the planning agent
|
|
72
|
+
start a workflow. **Adaptive** lets it handle simple requests directly and use a
|
|
73
|
+
workflow for dependencies, role handoffs or repeated review. The command works
|
|
74
|
+
in every mode and keeps your saved preference.
|
|
75
|
+
|
|
76
|
+
The agent records an objective, acceptance criteria, required outputs and task
|
|
77
|
+
dependencies. Todo shows tasks on the left and dependencies and review loops on the right.
|
|
78
|
+
Task icons distinguish ready (○), working (●), waiting (·), optional standby (–),
|
|
79
|
+
failed (×), and completed (✓) steps. In mouse-enabled Pi, click a task to highlight
|
|
80
|
+
its stage and inspect its latest result. Use `/todo expand` to show every task.
|
|
81
|
+
Below 36 terminal columns, the diagram follows the list.
|
|
82
|
+
Independent tasks can run together. A join waits for each prerequisite's output.
|
|
83
|
+
If a reviewer requests changes, the revision opens and the revised artifact
|
|
84
|
+
returns to review. Delivery waits for approval of the current version.
|
|
85
|
+
|
|
86
|
+
The agent can select an inspected catalog role or named agent for a step.
|
|
87
|
+
The ordinary subagent launch applies the catalog skills and current permissions.
|
|
88
|
+
Harness associates the returned assignment and its verified result with the step.
|
|
89
|
+
Resume the session branch to continue from its saved outputs. A bound Goal also
|
|
90
|
+
requires evidence for its objective. A standalone workflow can finish on its own.
|
|
91
|
+
|
|
68
92
|
The separate **Project work ledger** setting enables a durable project-scoped
|
|
69
93
|
record of the overall outcome, boundaries, and high-level items. It stays off by
|
|
70
94
|
default; turning it off removes ledger views and hints without deleting records.
|
|
@@ -17,6 +17,9 @@ export const controlCopy = new Map<string, SettingCopy>([
|
|
|
17
17
|
label: "Foreground wait guard",
|
|
18
18
|
description: "Blocks recognized shell waits, such as watching CI or following logs. Pi gets a prompt to run them in the background so the session stays responsive.",
|
|
19
19
|
}],
|
|
20
|
+
["dynamic-workflow", {
|
|
21
|
+
description: "Choose when Pi can plan a workflow automatically. Adaptive uses workflows for dependencies, handoffs or review. /dynamic-workflow starts one run in every mode.",
|
|
22
|
+
}],
|
|
20
23
|
["outcome-todo", {
|
|
21
24
|
label: "Outcome and Todo tools",
|
|
22
25
|
description: "Lets Pi record what the session should deliver and track its progress as a checklist.",
|
|
@@ -19,7 +19,7 @@ const callbackDescription = (source: "session" | "default") => [
|
|
|
19
19
|
|
|
20
20
|
// Keep each package page beside the controls used for the same task.
|
|
21
21
|
const taskOrder = [
|
|
22
|
-
"setting:outcome-todo", "setting:goal-auto-start", "link:goal", "setting:outcome-todo-ledger",
|
|
22
|
+
"setting:outcome-todo", "setting:dynamic-workflow", "setting:goal-auto-start", "link:goal", "setting:outcome-todo-ledger",
|
|
23
23
|
"link:subagents", "link:agents", "link:sandbox",
|
|
24
24
|
"setting:tool-call-guard", "setting:background-review-interval", CALLBACK_SETTING_ID,
|
|
25
25
|
"setting:navigator-view", "setting:navigator-sticky", "setting:outcome-todo-display",
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { reconstructGoalSnapshot } from "pi-better-goal/src/goal-state.ts";
|
|
3
|
+
import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.js";
|
|
4
|
+
import { advanceWorkflow, defineWorkflow, DYNAMIC_ENTRY, dynamicParameters, phase, readDynamic,
|
|
5
|
+
type Attempt, type CatalogChoice, type DynamicState, type WorkflowRun } from "./dynamic-workflow.js";
|
|
6
|
+
import { WORKFLOW_ASSIGNMENT, type WorkflowAssignmentRequest } from "pi-better-subagents/workflow-assignment.ts";
|
|
7
|
+
import { DELEGATION_MODE_REQUEST } from "pi-better-subagents/delegation.ts";
|
|
8
|
+
import { describeRun } from "./dynamic-workflow-view.js";
|
|
9
|
+
|
|
10
|
+
const modes = ["off", "on", "adaptive"] as const;
|
|
11
|
+
type Mode = typeof modes[number];
|
|
12
|
+
const planning = "Analyze the user's current intent. Use dynamic_workflow action define with the actual objective, observable criteria and task-specific steps. Express real dependencies and parallel branches. Where delegation is permitted, inspect suitable entries with agents_catalog before selecting their canonical ids. Use stages and review/revision only where the task needs them. Bind goalId only for the Goal this work delivers.";
|
|
13
|
+
const execution = "Read get_todo to resume the accepted workflow. Work each ready step, then submit its required output using the current runId and revision. For a catalog item, call subagent_spawn with workflow:{runId,step}, its selected role or agent, inheriting catalog settings. Inspect subagent_result after its callback. For review or revision, submit the current artifactVersion and findings or output. Finish with evidence for each objective criterion.";
|
|
14
|
+
|
|
15
|
+
function catalogChoice(ctx: ExtensionContext, id: string): CatalogChoice {
|
|
16
|
+
for (const entry of [...ctx.sessionManager.getBranch()].reverse()) {
|
|
17
|
+
if (entry.type !== "message" || entry.message.role !== "toolResult" || entry.message.toolName !== "agents_catalog") continue;
|
|
18
|
+
const view = entry.message.details?.view;
|
|
19
|
+
if (view?.id !== id) continue;
|
|
20
|
+
const exposure = view.skills?.effective;
|
|
21
|
+
const error = !view.found || !view.definitionValid || !view.catalogLaunchable || view.launchable === false || exposure?.mode === "error"
|
|
22
|
+
? exposure?.error ?? view.launchabilityReason ?? "Catalog entry unavailable." : undefined;
|
|
23
|
+
return { id, skills: exposure && exposure.mode !== "discovery" ? exposure.paths : null, error };
|
|
24
|
+
}
|
|
25
|
+
return { id, skills: null, error: "Inspect " + id + " with agents_catalog, then retry the step." };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function registerDynamicWorkflow(pi: ExtensionAPI, owner: (ctx: ExtensionContext) => string | null, changed: () => void) {
|
|
29
|
+
let mode: Mode = "off";
|
|
30
|
+
let state: DynamicState | undefined;
|
|
31
|
+
let activeContext: ExtensionContext | undefined;
|
|
32
|
+
const run = () => state && "run" in state ? state.run : undefined;
|
|
33
|
+
const pending = () => !!state && "pending" in state;
|
|
34
|
+
const restore = (ctx: ExtensionContext) => {
|
|
35
|
+
activeContext = ctx;
|
|
36
|
+
state = readDynamic(ctx.sessionManager.getBranch());
|
|
37
|
+
};
|
|
38
|
+
const save = (next: DynamicState) => {
|
|
39
|
+
pi.appendEntry(DYNAMIC_ENTRY, next);
|
|
40
|
+
state = next;
|
|
41
|
+
changed();
|
|
42
|
+
};
|
|
43
|
+
const persist = (next: WorkflowRun) => save({ version: 1, run: next });
|
|
44
|
+
const clear = () => save({ version: 1, clear: true });
|
|
45
|
+
const setting = {
|
|
46
|
+
id: "dynamic-workflow", label: "Automatic dynamic workflows", values: [...modes], get: () => mode,
|
|
47
|
+
change(value: string) {
|
|
48
|
+
if (!modes.includes(value as Mode)) throw new Error("Unknown dynamic workflow mode.");
|
|
49
|
+
mode = updateHarnessSetting("dynamicWorkflow", () => value as Mode);
|
|
50
|
+
changed();
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
const loadMode = () => {
|
|
54
|
+
const saved = readHarnessSetting<Mode>("dynamicWorkflow");
|
|
55
|
+
mode = saved && modes.includes(saved) ? saved : "off";
|
|
56
|
+
};
|
|
57
|
+
const active = () => { const current = run(); return !!current && !current.evidence; };
|
|
58
|
+
const available = () => mode !== "off" || pending() || active();
|
|
59
|
+
const guidance = () => {
|
|
60
|
+
if (active()) return execution;
|
|
61
|
+
if (pending() || mode === "on") return planning;
|
|
62
|
+
if (mode === "adaptive") return "Handle simple single-action requests directly. For tasks with dependencies, role handoffs, parallel work or repeated review, consider a dynamic workflow. " + planning;
|
|
63
|
+
return undefined;
|
|
64
|
+
};
|
|
65
|
+
pi.registerCommand("dynamic-workflow", {
|
|
66
|
+
description: "Plan one workflow for the current task, or continue its active run",
|
|
67
|
+
handler: async (args, ctx) => {
|
|
68
|
+
restore(ctx);
|
|
69
|
+
const existingOwner = owner(ctx);
|
|
70
|
+
if (existingOwner) { ctx.ui.notify(existingOwner + " owns this Todo.", "warning"); return; }
|
|
71
|
+
const resume = active();
|
|
72
|
+
if (!resume && !pending()) save({ version: 1, pending: true });
|
|
73
|
+
pi.sendMessage({ customType: DYNAMIC_ENTRY + ":requested", display: true,
|
|
74
|
+
content: [resume ? "Continue the current dynamic workflow." : "Plan a dynamic workflow for the current task.", args.trim()].filter(Boolean).join("\n") },
|
|
75
|
+
{ triggerTurn: true, deliverAs: "followUp" });
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
pi.registerTool({
|
|
79
|
+
name: "dynamic_workflow", label: "Dynamic workflow", description: "Define the task workflow once, record step results and versioned review verdicts, retry a failed assignment, or finish with objective evidence.",
|
|
80
|
+
parameters: dynamicParameters,
|
|
81
|
+
async execute(_key, input, _signal, _update, ctx) {
|
|
82
|
+
restore(ctx);
|
|
83
|
+
if (owner(ctx)) throw new Error(owner(ctx) + " owns the Todo.");
|
|
84
|
+
const current = run();
|
|
85
|
+
let next: WorkflowRun;
|
|
86
|
+
if (input.action === "define") {
|
|
87
|
+
if (current && !current.evidence) throw new Error("A workflow is already active.");
|
|
88
|
+
if (mode === "off" && !pending()) throw new Error("Automatic workflows are off. Use /dynamic-workflow for this task.");
|
|
89
|
+
if (!input.definition) throw new Error("Supply a workflow definition.");
|
|
90
|
+
const goal = reconstructGoalSnapshot(ctx.sessionManager.getBranch());
|
|
91
|
+
const goalId = input.definition.goalId ?? (goal?.status === "active" && goal.objective === input.definition.objective ? goal.goalId : undefined);
|
|
92
|
+
if (goalId && (goal?.goalId !== goalId || goal.status !== "active")) throw new Error("Bind only to the active Goal.");
|
|
93
|
+
const ids = [...new Set(input.definition.steps.flatMap(s => s.catalog ? [s.catalog] : []))];
|
|
94
|
+
next = defineWorkflow({ ...input.definition, goalId }, ids.map(id => catalogChoice(ctx, id)));
|
|
95
|
+
} else {
|
|
96
|
+
if (!current) throw new Error("No accepted workflow.");
|
|
97
|
+
next = advanceWorkflow(current, input);
|
|
98
|
+
if (input.action === "retry") {
|
|
99
|
+
const id = next.steps.find(s => s.id === input.step)?.catalog;
|
|
100
|
+
if (id) next.catalogChoices = next.catalogChoices.map(c => c.id === id ? catalogChoice(ctx, id) : c);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
persist(next);
|
|
104
|
+
return { content: [{ type: "text", text: describeRun(next) }], details: { run: next } };
|
|
105
|
+
},
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
function recordWorker(current: WorkflowRun, stepId: string, worker: Attempt) {
|
|
109
|
+
persist({ ...current, revision: current.revision + 1, workers: { ...current.workers, [stepId]: worker } });
|
|
110
|
+
}
|
|
111
|
+
const unsubscribe = pi.events.on(WORKFLOW_ASSIGNMENT, (event: unknown) => {
|
|
112
|
+
const request = event as WorkflowAssignmentRequest;
|
|
113
|
+
const { input, ref } = request;
|
|
114
|
+
const ctx = activeContext;
|
|
115
|
+
const origin = request.ctx.sessionManager;
|
|
116
|
+
const originLeaf = origin.getLeafId?.();
|
|
117
|
+
if (!ctx || ctx.sessionManager.getSessionId() !== origin.getSessionId() ||
|
|
118
|
+
(originLeaf && !ctx.sessionManager.getBranch().some(entry => entry.id === originLeaf))) {
|
|
119
|
+
request.error = "The workflow assignment belongs to another session branch.";
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
restore(ctx);
|
|
123
|
+
const current = run();
|
|
124
|
+
const s = current?.steps.find(step => step.id === ref.step);
|
|
125
|
+
if (!current || ref.runId !== current.id || !s?.catalog || owner(ctx)) {
|
|
126
|
+
request.error = "No matching active workflow assignment.";
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
const state = phase(current, s);
|
|
130
|
+
if (state !== "ready") { request.error = s.title + " is " + state; return; }
|
|
131
|
+
const modeRequest: { mode?: string } = {};
|
|
132
|
+
pi.events.emit(DELEGATION_MODE_REQUEST, modeRequest);
|
|
133
|
+
const selected = s.catalog.startsWith("role.") ? "role" : "agent";
|
|
134
|
+
const value = selected === "role" ? s.catalog.slice(5) : s.catalog;
|
|
135
|
+
let error: string | undefined;
|
|
136
|
+
if (modeRequest.mode === "manual") error = "Automatic workflow delegation is disabled in manual mode.";
|
|
137
|
+
else if ((input[selected] !== value && input[selected] !== s.catalog) || input[selected === "role" ? "agent" : "role"] !== undefined
|
|
138
|
+
|| input.session_id !== undefined || input.session_name !== undefined || input.skills !== undefined || input.clean === true) error = "Use the selected catalog entry and inherit its skills.";
|
|
139
|
+
recordWorker(current, s.id, { callId: request.callId, error });
|
|
140
|
+
if (error) { request.error = error; return; }
|
|
141
|
+
const needs = new Set(s.dependsOn);
|
|
142
|
+
const reviewer = s.review ? s : current.steps.find(item => item.review?.revision === s.id);
|
|
143
|
+
if (reviewer?.review) {
|
|
144
|
+
needs.add(reviewer.id);
|
|
145
|
+
needs.add(reviewer.review.artifact);
|
|
146
|
+
needs.add(reviewer.review.revision);
|
|
147
|
+
}
|
|
148
|
+
const prior = current.history.filter(h => needs.has(h.step)).map(h => h.step + ": " + h.result);
|
|
149
|
+
const prompt = [input.prompt, "Objective: " + current.objective, "Assignment: " + s.title,
|
|
150
|
+
"Required output: " + s.output, ...prior].join("\n");
|
|
151
|
+
request.admission = { prompt, settled(receipt) {
|
|
152
|
+
// Re-read the selected branch after asynchronous admission. A fork or a
|
|
153
|
+
// simultaneous independent launch may have changed the latest snapshot.
|
|
154
|
+
if (!activeContext || activeContext.sessionManager.getSessionId() !== origin.getSessionId()) return;
|
|
155
|
+
restore(activeContext);
|
|
156
|
+
const latest = run();
|
|
157
|
+
if (latest?.id === current.id && latest.workers[s.id]?.callId === request.callId) {
|
|
158
|
+
recordWorker(latest, s.id, { callId: request.callId, ...receipt });
|
|
159
|
+
}
|
|
160
|
+
} };
|
|
161
|
+
});
|
|
162
|
+
pi.on("tool_result", (event, ctx) => {
|
|
163
|
+
if (event.toolName !== "subagent_result") return;
|
|
164
|
+
restore(ctx);
|
|
165
|
+
const current = run();
|
|
166
|
+
if (!current || current.evidence) return;
|
|
167
|
+
const claim = Object.entries(current.workers).find(([, w]) => w.runId && w.runId === event.input.id);
|
|
168
|
+
if (!claim) return;
|
|
169
|
+
const [stepId, worker] = claim;
|
|
170
|
+
const details = event.details as { hasFinalAnswer?: boolean; outcome?: { outcome?: { outcome?: string; reason?: string } }; assignment?: { attemptId?: string; state?: string; reason?: string; verified?: boolean } } | undefined;
|
|
171
|
+
const a = details?.assignment;
|
|
172
|
+
if (event.isError || !a?.verified || a.attemptId !== worker.runId) return;
|
|
173
|
+
if (a.state === "completed" && !worker.result) {
|
|
174
|
+
const body = event.content.flatMap(b => b.type === "text" ? [b.text] : []).join("\n");
|
|
175
|
+
const durable = details?.outcome?.outcome;
|
|
176
|
+
const result = durable?.outcome === "succeeded" ? durable.reason : details?.hasFinalAnswer ? body : undefined;
|
|
177
|
+
if (result?.trim()) recordWorker(current, stepId, { ...worker, result });
|
|
178
|
+
else if (details?.hasFinalAnswer === false && !worker.error) recordWorker(current, stepId, { ...worker, error: "The worker finished without returning the required output." });
|
|
179
|
+
}
|
|
180
|
+
if ((a.state === "failed" || a.state === "cancelled") && !worker.error) {
|
|
181
|
+
recordWorker(current, stepId, { ...worker, error: a.reason || a.state });
|
|
182
|
+
}
|
|
183
|
+
});
|
|
184
|
+
return { run, pending, available, restore, setting, loadMode, guidance, clear, dispose: () => { activeContext = undefined; if (typeof unsubscribe === "function") unsubscribe(); } };
|
|
185
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
import { truncateToWidth, visibleWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
|
|
2
|
+
import { compactRowIndices, planText, type PlanRenderTheme } from "./plan-presentation.js";
|
|
3
|
+
import { renderCompactTaskHeader, type CompactTaskHeader } from "./compact-task-header.js";
|
|
4
|
+
import { phase, reviewState, type Step, type WorkflowRun } from "./dynamic-workflow.js";
|
|
5
|
+
|
|
6
|
+
const marker = { ready: "○", working: "●", waiting: "·", failed: "×", complete: "✓", standby: "–" } as const;
|
|
7
|
+
const status = { ready: "pending", working: "in_progress", waiting: "pending", failed: "failed", complete: "completed", standby: "skipped" } as const;
|
|
8
|
+
|
|
9
|
+
type Part = { text: string; color: string; selected?: boolean };
|
|
10
|
+
const colors = { ready: "accent", working: "accent", waiting: "muted", failed: "error", complete: "success", standby: "dim" } as const;
|
|
11
|
+
const wire = (text: string): Part => ({ text, color: "dim" });
|
|
12
|
+
type Node = { members: Step[]; label: Part; parents: string[]; revision?: string };
|
|
13
|
+
|
|
14
|
+
function diagramNodes(run: WorkflowRun, selected?: string): Node[] {
|
|
15
|
+
const groups = new Map<string, Step[]>();
|
|
16
|
+
const fixes = new Set(run.steps.map(s => s.review?.revision));
|
|
17
|
+
for (const s of run.steps) {
|
|
18
|
+
// Only coalesce parallel siblings. Different prerequisites within one
|
|
19
|
+
// named stage must stay visible as distinct edges.
|
|
20
|
+
const key = s.stage && !s.review && !fixes.has(s.id)
|
|
21
|
+
? JSON.stringify([s.stage, [...s.dependsOn ?? []].sort()]) : s.id;
|
|
22
|
+
const members = groups.get(key) ?? [];
|
|
23
|
+
members.push(s);
|
|
24
|
+
groups.set(key, members);
|
|
25
|
+
}
|
|
26
|
+
return [...groups.values()].map(members => {
|
|
27
|
+
const first = members[0]!;
|
|
28
|
+
const states = members.map(s => phase(run, s));
|
|
29
|
+
const state = (["failed", "working", "ready", "waiting", "complete", "standby"] as const)
|
|
30
|
+
.find(candidate => states.includes(candidate))!;
|
|
31
|
+
const name = planText(first.stage ?? first.title);
|
|
32
|
+
const detail = members.length > 1 ? " [" + members.map((s, i) => s.id + " " + marker[states[i]!]).join(" ∥ ") + "]" : "";
|
|
33
|
+
const label = { text: marker[state] + " " + name + detail, color: colors[state], selected: members.some(s => s.id === selected) };
|
|
34
|
+
return { members, label, parents: first.dependsOn ?? [], revision: first.review?.revision };
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function diagram(nodes: Node[], width: number): Part[][] {
|
|
39
|
+
const byId = new Map(nodes.flatMap(node => node.members.map(step => [step.id, node] as const)));
|
|
40
|
+
const fixes = new Set(nodes.map(node => node.revision));
|
|
41
|
+
const main = nodes.filter(node => !fixes.has(node.members[0]!.id));
|
|
42
|
+
const path: Node[] = [];
|
|
43
|
+
let next = main.filter(node => !node.parents.length);
|
|
44
|
+
while (next.length === 1) {
|
|
45
|
+
const current = next[0]!;
|
|
46
|
+
path.push(current);
|
|
47
|
+
next = main.filter(node => node.parents.length === current.members.length && node.parents.every(id => byId.get(id) === current));
|
|
48
|
+
}
|
|
49
|
+
if (path.length === main.length) {
|
|
50
|
+
const top: Part[] = [];
|
|
51
|
+
const loops: Part[][] = [];
|
|
52
|
+
let x = 0;
|
|
53
|
+
for (const [i, node] of path.entries()) {
|
|
54
|
+
top.push(node.label);
|
|
55
|
+
const size = visibleWidth(node.label.text);
|
|
56
|
+
if (node.revision) {
|
|
57
|
+
const fix = byId.get(node.revision)!.label;
|
|
58
|
+
const fixSize = visibleWidth(fix.text);
|
|
59
|
+
const span = Math.max(size + 2, fixSize + 6);
|
|
60
|
+
const indent = " ".repeat(x);
|
|
61
|
+
top.push(wire(" " + "─".repeat(span - size - 1) + "┬"));
|
|
62
|
+
loops.push([wire(indent + "↑" + " ".repeat(span - 1) + "│")],
|
|
63
|
+
[wire(indent + "└─ "), fix, wire(" ←" + "─".repeat(span - fixSize - 5) + "┘")]);
|
|
64
|
+
x += span + 1;
|
|
65
|
+
} else x += size;
|
|
66
|
+
if (i < path.length - 1) { top.push(wire(" ─→ ")); x += 4; }
|
|
67
|
+
}
|
|
68
|
+
if (x <= width) return [top, ...loops];
|
|
69
|
+
// Preserve edge direction without wrapping connectors away from their nodes.
|
|
70
|
+
return path.flatMap((node, i) => {
|
|
71
|
+
const lines = [[wire(i ? "↓ " : ""), node.label]];
|
|
72
|
+
if (node.revision) lines.push([wire(" ↳ "), byId.get(node.revision)!.label], [wire(" ↺ " + (node.members[0]!.stage ?? node.members[0]!.title))]);
|
|
73
|
+
return lines;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return nodes.map(node => {
|
|
77
|
+
const parents = node.parents.map(id => {
|
|
78
|
+
const parent = byId.get(id)!;
|
|
79
|
+
return parent.members.length > 1 ? id : parent.members[0]!.stage ?? parent.members[0]!.title;
|
|
80
|
+
});
|
|
81
|
+
return [wire(parents.length ? parents.join(" + ") + " → " : ""), node.label,
|
|
82
|
+
...(node.revision ? [wire(" ↔ "), byId.get(node.revision)!.label] : [])];
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
type WorkflowTheme = PlanRenderTheme & { underline?(text: string): string };
|
|
87
|
+
|
|
88
|
+
export interface DynamicFrame {
|
|
89
|
+
lines: string[];
|
|
90
|
+
stepAt(x: number, y: number): string | undefined;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function renderDynamicFrame(run: WorkflowRun, width: number, theme: WorkflowTheme, expanded: boolean, header: CompactTaskHeader, selected?: string): DynamicFrame {
|
|
94
|
+
const size = Math.max(1, Math.floor(width));
|
|
95
|
+
const rows = run.steps.map(step => {
|
|
96
|
+
const state = phase(run, step);
|
|
97
|
+
return { step, state, status: status[state] };
|
|
98
|
+
});
|
|
99
|
+
const completed = rows.filter(row => row.state === "complete").length;
|
|
100
|
+
const total = rows.filter(row => row.state !== "standby").length;
|
|
101
|
+
const lines = renderCompactTaskHeader(completed + "/" + total, size, theme, {
|
|
102
|
+
...header, subtitle: run.objective, runtime: header.runtime ?? { status: run.evidence ? "complete" : "active" },
|
|
103
|
+
});
|
|
104
|
+
|
|
105
|
+
// Leave room for both a task title and a dependency edge. Tiny terminals use the full line for each.
|
|
106
|
+
const split = size >= 36;
|
|
107
|
+
const listWidth = split ? Math.min(38, Math.floor(size / 3)) : size;
|
|
108
|
+
const gutter = theme.fg("dim", " │ ");
|
|
109
|
+
const graphWidth = split ? size - listWidth - 3 : size;
|
|
110
|
+
const highlight = (text: string) => theme.underline?.(text) ?? theme.fg("accent", text);
|
|
111
|
+
const graph = diagram(diagramNodes(run, selected), graphWidth).flatMap(parts => {
|
|
112
|
+
const text = parts.map(p => {
|
|
113
|
+
const styled = theme.fg(p.color, planText(p.text));
|
|
114
|
+
return p.selected ? highlight(styled) : styled;
|
|
115
|
+
}).join("");
|
|
116
|
+
return wrapTextWithAnsi(text, graphWidth);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
const visible = expanded ? rows.map((_, i) => i) : compactRowIndices(rows);
|
|
120
|
+
const tasks: { line: string; id?: string }[] = [];
|
|
121
|
+
let previous = -1;
|
|
122
|
+
const omitted = (count: number) => tasks.push({ line: theme.fg("dim", " … " + count + " more") });
|
|
123
|
+
for (const i of visible) {
|
|
124
|
+
if (i > previous + 1) omitted(i - previous - 1);
|
|
125
|
+
const { step, state } = rows[i]!;
|
|
126
|
+
const title = theme.fg("text", planText(step.title));
|
|
127
|
+
const line = theme.fg(colors[state], marker[state]) + " " + (step.id === selected ? highlight(title) : title);
|
|
128
|
+
tasks.push({ id: step.id, line: truncateToWidth(line, listWidth) });
|
|
129
|
+
previous = i;
|
|
130
|
+
}
|
|
131
|
+
if (previous < rows.length - 1) omitted(rows.length - previous - 1);
|
|
132
|
+
|
|
133
|
+
const firstRow = lines.length;
|
|
134
|
+
if (split) {
|
|
135
|
+
for (let i = 0; i < Math.max(tasks.length, graph.length); i++) {
|
|
136
|
+
const left = tasks[i]?.line ?? "";
|
|
137
|
+
lines.push(left + " ".repeat(Math.max(0, listWidth - visibleWidth(left))) + gutter + (graph[i] ?? ""));
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
lines.push(...tasks.map(t => t.line), ...graph);
|
|
141
|
+
}
|
|
142
|
+
const step = run.steps.find(s => s.id === selected);
|
|
143
|
+
if (step) {
|
|
144
|
+
const entry = run.history.filter(h => h.step === step.id).at(-1);
|
|
145
|
+
const result = entry?.result ?? "Required: " + step.output;
|
|
146
|
+
const caption = [step.id, step.catalog, result].filter(Boolean).join(" · ");
|
|
147
|
+
lines.push(theme.fg("muted", planText(caption)));
|
|
148
|
+
}
|
|
149
|
+
return {
|
|
150
|
+
lines: lines.map(line => truncateToWidth(line, size)),
|
|
151
|
+
stepAt: (x, y) => x >= 0 && x < listWidth ? tasks[y - firstRow]?.id : undefined,
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
export function renderDynamic(run: WorkflowRun, width: number, theme: WorkflowTheme, expanded: boolean, header: CompactTaskHeader) {
|
|
156
|
+
return renderDynamicFrame(run, width, theme, expanded, header).lines;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
export function describeRun(run: WorkflowRun): string {
|
|
160
|
+
const lines = [run.objective, `runId ${run.id} · revision ${run.revision} · ${run.evidence ? "finished" : "active"}`,
|
|
161
|
+
...run.criteria.map(c => "Acceptance: " + c)];
|
|
162
|
+
for (const s of run.steps) {
|
|
163
|
+
lines.push(`${s.id} [${phase(run, s)}] ${s.title}${s.stage ? " · " + s.stage : ""}${s.dependsOn?.length ? " ← " + s.dependsOn.join(" + ") : ""}. Required output: ${s.output}`);
|
|
164
|
+
if (s.review) lines.push(` Review ${s.review.artifact} v${reviewState(run, s).version}; changes_requested → ${s.review.revision} → ${s.id}.`);
|
|
165
|
+
const choice = run.catalogChoices.find(c => c.id === s.catalog);
|
|
166
|
+
const worker = Object.hasOwn(run.workers, s.id) ? run.workers[s.id] : undefined;
|
|
167
|
+
if (choice) {
|
|
168
|
+
lines.push(` ${choice.id} · skills: ${choice.skills?.join(", ") || (choice.skills ? "none" : "discovery")}. subagent_spawn workflow: ${JSON.stringify({ runId: run.id, step: s.id })}`);
|
|
169
|
+
if (choice.error) lines.push(" " + choice.error);
|
|
170
|
+
if (worker) lines.push(" Assignment: " + (worker.error ?? worker.result ?? worker.runId ?? worker.callId));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
for (const h of run.history) lines.push(`Recorded ${h.step}${h.version ? " v" + h.version : ""}${h.verdict ? " " + h.verdict : ""}${h.worker?.runId ? " (" + h.worker.runId + ")" : ""}: ${h.result}`);
|
|
174
|
+
for (const item of run.evidence ?? []) lines.push(item.criterion + ": " + item.result);
|
|
175
|
+
return lines.join("\n");
|
|
176
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
3
|
+
import { Type, type Static } from "typebox";
|
|
4
|
+
import { validatePlanInput } from "./plan-state.js";
|
|
5
|
+
|
|
6
|
+
const text = Type.String({ minLength: 1, pattern: "\\S" });
|
|
7
|
+
const id = Type.String({ pattern: "^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$" });
|
|
8
|
+
const definitionSchema = Type.Object({
|
|
9
|
+
objective: text,
|
|
10
|
+
criteria: Type.Array(text, { minItems: 1, description: "Observable acceptance criteria for the user's objective." }),
|
|
11
|
+
goalId: Type.Optional(text),
|
|
12
|
+
steps: Type.Array(Type.Object({
|
|
13
|
+
id, title: text, output: text,
|
|
14
|
+
dependsOn: Type.Optional(Type.Array(id)),
|
|
15
|
+
stage: Type.Optional(text),
|
|
16
|
+
catalog: Type.Optional(Type.String({ description: "Canonical inspected role.* or agent.* id. Omit for foreground work." })),
|
|
17
|
+
review: Type.Optional(Type.Object({ artifact: id, revision: id }, { description: "Review the artifact step's output. On findings, open the revision step, then review the new version. Delivery depends on this review." })),
|
|
18
|
+
}), { minItems: 1, maxItems: 50 }),
|
|
19
|
+
});
|
|
20
|
+
const evidenceSchema = Type.Array(Type.Object({ criterion: text, result: text }));
|
|
21
|
+
export const dynamicParameters = Type.Object({
|
|
22
|
+
action: StringEnum(["define", "submit", "retry", "finish"] as const),
|
|
23
|
+
definition: Type.Optional(definitionSchema),
|
|
24
|
+
runId: Type.Optional(text), revision: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
25
|
+
step: Type.Optional(id), result: Type.Optional(text),
|
|
26
|
+
verdict: Type.Optional(StringEnum(["passed", "changes_requested"] as const)),
|
|
27
|
+
artifactVersion: Type.Optional(Type.Integer({ minimum: 1 })),
|
|
28
|
+
evidence: Type.Optional(evidenceSchema),
|
|
29
|
+
});
|
|
30
|
+
export type Definition = Static<typeof definitionSchema>;
|
|
31
|
+
export type DynamicInput = Static<typeof dynamicParameters>;
|
|
32
|
+
export type Step = Definition["steps"][number];
|
|
33
|
+
export type CatalogChoice = { id: string; skills: string[] | null; error?: string };
|
|
34
|
+
export type Attempt = { callId: string; runId?: string; result?: string; error?: string };
|
|
35
|
+
type History = { step: string; result: string; version?: number; verdict?: DynamicInput["verdict"]; worker?: Attempt };
|
|
36
|
+
export interface WorkflowRun extends Definition {
|
|
37
|
+
id: string; revision: number;
|
|
38
|
+
history: History[];
|
|
39
|
+
workers: Record<string, Attempt>;
|
|
40
|
+
catalogChoices: CatalogChoice[];
|
|
41
|
+
evidence?: Static<typeof evidenceSchema>;
|
|
42
|
+
}
|
|
43
|
+
export type BranchEntry = { type: string; customType?: string; data?: unknown };
|
|
44
|
+
export const DYNAMIC_ENTRY = "pi-better-harness:dynamic-workflow";
|
|
45
|
+
export type DynamicState = { version: 1; pending: true } | { version: 1; run: WorkflowRun } | { version: 1; clear: true };
|
|
46
|
+
export function readDynamic(entries: readonly BranchEntry[], goalId?: string): DynamicState | undefined {
|
|
47
|
+
for (let i = entries.length - 1; i >= 0; i--) {
|
|
48
|
+
const e = entries[i]!;
|
|
49
|
+
if (e.type !== "custom" || e.customType !== DYNAMIC_ENTRY) continue;
|
|
50
|
+
const state = e.data as DynamicState | undefined;
|
|
51
|
+
if (state?.version === 1 && (!goalId || ("run" in state && state.run.goalId === goalId))) return state;
|
|
52
|
+
}
|
|
53
|
+
return undefined;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function defineWorkflow(input: Definition, choices: CatalogChoice[]): WorkflowRun {
|
|
57
|
+
if (new Set(input.criteria).size !== input.criteria.length) throw new Error("Objective criteria must be distinct.");
|
|
58
|
+
const error = validatePlanInput(input.steps.map(s => ({ id: s.id, step: s.title, dependsOn: s.dependsOn, status: "pending" })));
|
|
59
|
+
if (error) throw new Error(error);
|
|
60
|
+
const fixes = new Set<string>();
|
|
61
|
+
const byId = new Map(input.steps.map(step => [step.id, step]));
|
|
62
|
+
for (const step of input.steps) {
|
|
63
|
+
if (!step.review) continue;
|
|
64
|
+
const { artifact, revision } = step.review;
|
|
65
|
+
const fix = byId.get(revision);
|
|
66
|
+
if (!step.dependsOn?.includes(artifact) || !fix || fix.review || fix.dependsOn?.length || fixes.has(revision)
|
|
67
|
+
|| byId.get(artifact)?.review || input.steps.some(s => s.dependsOn?.includes(revision))) {
|
|
68
|
+
throw new Error("A review must depend on its artifact and own a separate revision step with no ordinary dependencies or dependents.");
|
|
69
|
+
}
|
|
70
|
+
fixes.add(revision);
|
|
71
|
+
}
|
|
72
|
+
return { ...input, id: randomUUID(), revision: 1, history: [], workers: {}, catalogChoices: choices };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function reviewState(run: WorkflowRun, reviewer: Step) {
|
|
76
|
+
const review = reviewer.review!;
|
|
77
|
+
const changes = run.history.filter(h => h.step === review.revision);
|
|
78
|
+
const version = changes.length + 1;
|
|
79
|
+
const verdict = run.history.find(h => h.step === reviewer.id && h.version === version);
|
|
80
|
+
const artifact = changes.at(-1) ?? run.history.find(h => h.step === review.artifact);
|
|
81
|
+
return { version, verdict, artifact };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function phase(run: WorkflowRun, step: Step): "ready" | "waiting" | "complete" | "standby" | "working" | "failed" {
|
|
85
|
+
const reviewer = run.steps.find(s => s.review?.revision === step.id);
|
|
86
|
+
if (reviewer) {
|
|
87
|
+
const { verdict } = reviewState(run, reviewer);
|
|
88
|
+
if (verdict?.verdict !== "changes_requested") return run.history.some(h => h.step === step.id) ? "complete" : "standby";
|
|
89
|
+
} else if (step.review) {
|
|
90
|
+
const { verdict } = reviewState(run, step);
|
|
91
|
+
if (verdict?.verdict === "passed") return "complete";
|
|
92
|
+
if (verdict?.verdict === "changes_requested") return "waiting";
|
|
93
|
+
} else if (run.history.some(h => h.step === step.id)) return "complete";
|
|
94
|
+
|
|
95
|
+
// A completed prerequisite has a recorded output, or a passing current review.
|
|
96
|
+
if (step.dependsOn?.some(dep => {
|
|
97
|
+
const parent = run.steps.find(s => s.id === dep)!;
|
|
98
|
+
return parent.review ? reviewState(run, parent).verdict?.verdict !== "passed" : !run.history.some(h => h.step === dep);
|
|
99
|
+
})) return "waiting";
|
|
100
|
+
const choice = run.catalogChoices.find(c => c.id === step.catalog);
|
|
101
|
+
const worker = Object.hasOwn(run.workers, step.id) ? run.workers[step.id] : undefined;
|
|
102
|
+
if (choice?.error || worker?.error) return "failed";
|
|
103
|
+
if (worker) return "working";
|
|
104
|
+
return "ready";
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function openWork(run: WorkflowRun): string[] {
|
|
108
|
+
return run.steps.filter(step => !["complete", "standby"].includes(phase(run, step))).map(s => s.title);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function advanceWorkflow(current: WorkflowRun, input: DynamicInput): WorkflowRun {
|
|
112
|
+
if (input.runId !== current.id || input.revision !== current.revision) throw new Error("Workflow changed. Read get_todo for its current runId and revision.");
|
|
113
|
+
if (current.evidence) throw new Error("Workflow already finished.");
|
|
114
|
+
const run = structuredClone(current);
|
|
115
|
+
if (input.action === "finish") {
|
|
116
|
+
const open = openWork(run);
|
|
117
|
+
if (open.length) throw new Error("Outstanding steps: " + open.join(", "));
|
|
118
|
+
const missing = run.criteria.filter(c => !input.evidence?.some(e => e.criterion === c && e.result.trim()));
|
|
119
|
+
if (missing.length) throw new Error("Missing objective evidence: " + missing.join(", "));
|
|
120
|
+
run.evidence = input.evidence;
|
|
121
|
+
} else {
|
|
122
|
+
const step = run.steps.find(s => s.id === input.step);
|
|
123
|
+
if (!step) throw new Error("Unknown workflow step.");
|
|
124
|
+
const state = phase(run, step);
|
|
125
|
+
if (input.action === "retry") {
|
|
126
|
+
if (state !== "failed") throw new Error("Only a failed assignment can be retried.");
|
|
127
|
+
delete run.workers[step.id];
|
|
128
|
+
} else {
|
|
129
|
+
if (input.action !== "submit" || !["ready", "working"].includes(state)) throw new Error(step.title + " is " + state + ".");
|
|
130
|
+
const worker = Object.hasOwn(run.workers, step.id) ? run.workers[step.id] : undefined;
|
|
131
|
+
if (step.catalog && !worker?.result) throw new Error("Inspect this step's successful subagent_result before submitting its output.");
|
|
132
|
+
if (!input.result?.trim()) throw new Error("Supply the required output: " + step.output);
|
|
133
|
+
const reviewer = step.review ? step : run.steps.find(s => s.review?.revision === step.id);
|
|
134
|
+
if (reviewer && input.artifactVersion !== reviewState(run, reviewer).version) throw new Error("Review or revise the current artifact version.");
|
|
135
|
+
if (step.review ? !input.verdict : input.verdict !== undefined) throw new Error("Only a review step takes a required verdict.");
|
|
136
|
+
run.history.push({ step: step.id, result: input.result, version: input.artifactVersion, verdict: input.verdict, worker });
|
|
137
|
+
delete run.workers[step.id];
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
run.revision++;
|
|
141
|
+
return run;
|
|
142
|
+
}
|