pi-better-harness 0.53.0 → 0.55.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.
Files changed (64) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +40 -0
  3. package/extensions/settings/copy.ts +3 -0
  4. package/extensions/settings/index.ts +8 -0
  5. package/extensions/settings/page.ts +1 -1
  6. package/extensions/settings/supervisor.ts +64 -0
  7. package/extensions/supervisor/commitments.ts +126 -0
  8. package/extensions/supervisor/decisions.ts +80 -0
  9. package/extensions/supervisor/evidence.ts +53 -0
  10. package/extensions/supervisor/index.ts +206 -0
  11. package/extensions/supervisor/shared-fault.ts +62 -0
  12. package/extensions/task-context/dynamic-workflow-runtime.ts +185 -0
  13. package/extensions/task-context/dynamic-workflow-view.ts +86 -0
  14. package/extensions/task-context/dynamic-workflow.ts +142 -0
  15. package/extensions/task-context/index.ts +100 -13
  16. package/extensions/task-context/plan-presentation.ts +30 -10
  17. package/extensions/task-context/plan-widget.ts +5 -2
  18. package/extensions/task-context/workflow-diagram.ts +68 -0
  19. package/extensions/task-context/workflow-plan.ts +159 -57
  20. package/extensions/task-context/workflow-view.ts +74 -0
  21. package/lib/instructions.mjs +18 -10
  22. package/node_modules/pi-better-background-tasks/package.json +1 -1
  23. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  24. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  25. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  26. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  27. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  28. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  29. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  30. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  31. package/node_modules/pi-better-background-tasks/src/ci-observation.ts +118 -0
  32. package/node_modules/pi-better-background-tasks/src/managed-client.ts +6 -2
  33. package/node_modules/pi-better-background-tasks/src/managed-frontend.ts +36 -6
  34. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +24 -0
  35. package/node_modules/pi-better-background-tasks/src/shared-operation-coordinator/assignment-observation.mjs +1 -0
  36. package/node_modules/pi-better-goal/package.json +1 -1
  37. package/node_modules/pi-better-goal/src/assignment-inbox.mjs +4 -0
  38. package/node_modules/pi-better-goal/src/command-binding.ts +10 -3
  39. package/node_modules/pi-better-goal/src/index.ts +9 -8
  40. package/node_modules/pi-better-goal/src/shared-assignment-observation.mjs +1 -0
  41. package/node_modules/pi-better-goal/src/task-context.ts +2 -0
  42. package/node_modules/pi-better-goal/src/workflow-gates.ts +3 -1
  43. package/node_modules/pi-better-subagents/catalog-schema.ts +1 -0
  44. package/node_modules/pi-better-subagents/docs/agent-catalog.md +1 -0
  45. package/node_modules/pi-better-subagents/index.ts +7 -2
  46. package/node_modules/pi-better-subagents/output-payload.ts +2 -0
  47. package/node_modules/pi-better-subagents/package.json +1 -1
  48. package/node_modules/pi-better-subagents/roles/role.supervisor.md +16 -0
  49. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  50. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  51. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  52. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  53. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  54. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  55. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  56. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  57. package/node_modules/pi-better-subagents/shared-catalog.ts +14 -2
  58. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-inbox.mjs +4 -0
  59. package/node_modules/pi-better-subagents/shared-operation-coordinator/assignment-observation.mjs +1 -0
  60. package/node_modules/pi-better-subagents/supervisor-client.d.mts +11 -0
  61. package/node_modules/pi-better-subagents/supervisor-client.mjs +34 -0
  62. package/node_modules/pi-better-subagents/tools.ts +3 -2
  63. package/node_modules/pi-better-subagents/workflow-assignment.ts +35 -0
  64. package/package.json +6 -5
package/CHANGELOG.md CHANGED
@@ -1,5 +1,28 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.55.0] - 2026-11-25
4
+
5
+ ### Added
6
+
7
+ - Enable Agent Supervisor in Harness settings to recover interrupted CI observation, diagnose stalled Outcomes and shared daemon faults, review scope, consolidate authorization requests, and follow up on recovery commitments. Each scenario is opt-in. (#896)
8
+
9
+ ### Fixed
10
+
11
+ - Bound task plans and dynamic workflows now share a Todo view. At 36 terminal columns or wider, the task list appears to the left of the workflow diagram and review loops. In narrower terminals the diagram follows the list. Long provider status text stays within the compact list. (#908)
12
+
13
+ ## [0.54.0] - 2026-11-25
14
+
15
+ ### Added
16
+
17
+ - Run task-defined workflows and display their progress in Todo. (#904)
18
+ - 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.
19
+
20
+ ### Fixed
21
+
22
+ - Reject a replacement Todo when reopening an Outcome that owns a workflow plan. Keep the original plan available to its scheduler.
23
+ - Skip the instructions lock for unmarked dotfiles during sync and disable, so read-only dotfile directories can keep Harness instructions off.
24
+ - Bundle Goal 0.16.2, Background Tasks 0.20.3, and Subagents 0.38.0 with Server 0.7.3.
25
+
3
26
  ## [0.53.0] - 2026-11-23
4
27
 
5
28
  ### Added
package/README.md CHANGED
@@ -61,10 +61,37 @@ enables it. Existing active, paused or budget-limited Goals stay unchanged, and
61
61
  restoring state or toggling settings never starts work. The outcome and Todo are
62
62
  preserved; subsequent continuation follows the existing Goal controls.
63
63
 
64
+ Todo uses the same workflow view for a bound task plan and a dynamic workflow.
65
+ It shows tasks on the left and the workflow diagram on the right. Below 36 terminal
66
+ columns, the diagram follows the task list.
67
+
64
68
  Existing Plan session histories restore as Todo. Workflow task-plan files and
65
69
  revision checks stay unchanged; skills continue using their own records when the
66
70
  optional interface is off. See the [usage guide](docs/usage.md#outcome--todo).
67
71
 
72
+ ### Dynamic workflows
73
+
74
+ Run `/dynamic-workflow` to plan the current task once. In `/harness-settings`,
75
+ **Automatic dynamic workflows** defaults to **off**. **On** lets the planning agent
76
+ start a workflow. **Adaptive** lets it handle simple requests directly and use a
77
+ workflow for dependencies, role handoffs or repeated review. The command works
78
+ in every mode and keeps your saved preference.
79
+
80
+ The agent records an objective, acceptance criteria, required outputs and task
81
+ dependencies. The diagram shows dependencies and review loops.
82
+ Task icons distinguish ready (○), working (●), waiting (·), optional standby (–),
83
+ failed (×), and completed (✓) steps. In mouse-enabled Pi, click a task to highlight
84
+ its stage and inspect its latest result. Use `/todo expand` to show every task.
85
+ Independent tasks can run together. A join waits for each prerequisite's output.
86
+ If a reviewer requests changes, the revision opens and the revised artifact
87
+ returns to review. Delivery waits for approval of the current version.
88
+
89
+ The agent can select an inspected catalog role or named agent for a step.
90
+ The ordinary subagent launch applies the catalog skills and current permissions.
91
+ Harness associates the returned assignment and its verified result with the step.
92
+ Resume the session branch to continue from its saved outputs. A bound Goal also
93
+ requires evidence for its objective. A standalone workflow can finish on its own.
94
+
68
95
  The separate **Project work ledger** setting enables a durable project-scoped
69
96
  record of the overall outcome, boundaries, and high-level items. It stays off by
70
97
  default; turning it off removes ledger views and hints without deleting records.
@@ -319,6 +346,19 @@ The hub is TUI-only and is included by the installer. To load the settings exten
319
346
  pi -e ./packages/pi-better-harness/extensions/settings/index.ts
320
347
  ```
321
348
 
349
+ ### Agent Supervisor
350
+
351
+ Open **Supervisor mode** in `/harness-settings`. Turn it on and select the scenarios to run. First use starts with an empty selection. Settings apply to sessions sharing the Pi agent directory. Turning the mode off preserves the selection and lets existing tasks continue.
352
+
353
+ | Scenario | What the owner receives |
354
+ | --- | --- |
355
+ | CI observation recovery | A suggestion to resume observation of the original GitHub run when its local watcher exits and a fresh check confirms the run is active. Use `supervisor_consult` for the managed observer. |
356
+ | Diagnose stalled Outcomes | A diagnostic review after repeated identical successful repository reads return the same evidence throughout the stall interval. |
357
+ | Review Outcome scope | A review of changed Todo steps against the latest user instruction and Outcome. The owner chooses which steps to keep or prune. Use `supervisor_review` for an on-demand review. |
358
+ | Shared daemon fault diagnosis | A shared read-plane diagnosis with an owner-specific verification step when a runtime read fails and the daemon confirms degraded or rebuilding inventory. |
359
+ | Consolidate authorization requests | Owners in a trusted workspace can use `supervisor_request_decision` for the same proposal. The dialog shows the reference, operation, host, resource, side effect, workspace and validity period. Execution still needs the permissions normally required by the tool. |
360
+ | Follow up on recovery commitments | Use `supervisor_followup` to record the action, expected verification and actual tool results. Read progress with `/supervisor-followup`. Request one reminder with `/supervisor-followup remind <id> <minutes>`. |
361
+
322
362
  ## When To Use
323
363
 
324
364
  Use the installer when you want every core extension with standalone package identities. Install an individual package instead when you only need the sandbox, subagents, shell task supervision, synchronous SSH, goal tracking, or model routing. Outcome & Todo is available through Harness.
@@ -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.",
@@ -1,6 +1,7 @@
1
1
  import { getAgentDir, type ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
2
  import { currentInstructions, manageInstructions, validateInstructionsPrompt } from "../../lib/instructions.mjs";
3
3
  import { readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
4
+ import { openSupervisorSettings } from "./supervisor.ts";
4
5
  import { chooseHarnessSetting } from "./page.ts";
5
6
  import { createSettingsRegistry } from "./registry.ts";
6
7
  import { changeCallbackSetting, getCallbackSettings, saveCallbackDefault } from "pi-better-background-tasks/src/shared-callback-batcher.ts";
@@ -45,6 +46,8 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
45
46
  change: mode => changeCallbackSetting(pi, ctx, mode),
46
47
  save: () => saveCallbackDefault(readSettings().mode),
47
48
  }, registry.controls(), view, [
49
+ { id: "supervisor:open", label: "Supervisor mode", currentValue: "Open", values: ["Open"],
50
+ description: "Choose the supervision scenarios shared by this agent directory." },
48
51
  { id: "instructions:toggle", label: "Harness instructions", currentValue: state, values: [state],
49
52
  description: "Toggle the global APPEND_SYSTEM.md block. Applies on startup or /reload." },
50
53
  ...(prompt === undefined ? [] : [{ id: "instructions:edit", label: "Instructions prompt", currentValue: "Edit",
@@ -55,6 +58,11 @@ export default function harnessSettingsExtension(pi: ExtensionAPI): void {
55
58
  return;
56
59
  }
57
60
  if (!selected) return;
61
+ if (selected === "supervisor:open") {
62
+ try { await openSupervisorSettings(ctx); }
63
+ catch (error) { ctx.ui.notify(`Supervisor mode: ${error instanceof Error ? error.message : String(error)}`, "error"); }
64
+ continue;
65
+ }
58
66
  if (selected.startsWith("instructions:")) {
59
67
  try {
60
68
  if (readError) throw readError;
@@ -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,64 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { statSync } from "node:fs";
3
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
4
+ import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from "../shared-harness-settings.ts";
5
+
6
+ const key = "supervisorMode";
7
+ const options = new Map([
8
+ ["ci-observation", "CI observation recovery"],
9
+ ["stall-diagnosis", "Diagnose stalled Outcomes"],
10
+ ["scope-review", "Review Outcome scope"],
11
+ ["shared-fault", "Shared daemon fault diagnosis"],
12
+ ["shared-decisions", "Consolidate authorization requests"],
13
+ ["commitment-followup", "Follow up on recovery commitments"],
14
+ ]);
15
+
16
+ function decode(raw: unknown): { enabled: boolean; scenarios: string[]; revision?: string } {
17
+ if (raw === undefined) return { enabled: false, scenarios: [] };
18
+ if (typeof raw !== "object" || raw === null || !("enabled" in raw) ||
19
+ typeof raw.enabled !== "boolean" || !("scenarios" in raw) || !Array.isArray(raw.scenarios) ||
20
+ !raw.scenarios.every((id: unknown) => typeof id === "string")) {
21
+ throw new Error("Invalid Supervisor mode settings.");
22
+ }
23
+ return { enabled: raw.enabled, scenarios: raw.scenarios, revision: "revision" in raw && typeof raw.revision === "string" ? raw.revision : undefined };
24
+ }
25
+
26
+ // Atomic settings writes replace the inode. Avoid locking and parsing on every observed tool.
27
+ let cache: { stamp: string; scenarios: string[]; revision: string } | undefined;
28
+ export function enabledScenarios(): string[] {
29
+ try {
30
+ const path = harnessSettingsPath();
31
+ const file = statSync(path, { throwIfNoEntry: false });
32
+ if (!file) return [];
33
+ const stamp = [path, file.dev, file.ino, file.ctimeMs, file.size].join("/");
34
+ if (cache?.stamp === stamp) return cache.scenarios;
35
+ const setting = decode(readHarnessSetting(key));
36
+ cache = { stamp, revision: setting.revision ?? "initial", scenarios: setting.enabled ? setting.scenarios : [] };
37
+ return cache.scenarios;
38
+ } catch { return []; }
39
+ }
40
+
41
+ export function scenarioRevision(scenario: string) {
42
+ if (enabledScenarios().includes(scenario)) return cache?.revision;
43
+ }
44
+
45
+ export async function openSupervisorSettings(ctx: Pick<ExtensionCommandContext, "ui">): Promise<void> {
46
+ while (true) {
47
+ const { enabled, scenarios } = decode(readHarnessSetting(key));
48
+ const mode = enabled ? "Turn Supervisor mode off" : "Turn Supervisor mode on";
49
+ const rows = [...options].map(([id, label]) => ({ id, selected: scenarios.includes(id), label: `[${scenarios.includes(id) ? "x" : " "}] ${label}` }));
50
+ const choices = enabled ? [mode, ...rows.map(row => row.label)] : [mode];
51
+ const choice = await ctx.ui.select("Supervisor mode", choices);
52
+ const row = rows.find(item => item.label === choice);
53
+ if (choice === undefined) return;
54
+ updateHarnessSetting(key, raw => {
55
+ const current = decode(raw);
56
+ if (choice === mode) return current.enabled === !enabled ? raw : { ...current, enabled: !enabled, revision: randomUUID() };
57
+ if (!current.enabled || !row) return raw;
58
+ const updated = new Set(current.scenarios);
59
+ if (row.selected) updated.delete(row.id);
60
+ else updated.add(row.id);
61
+ return updated.size === current.scenarios.length ? raw : { ...current, scenarios: [...updated], revision: randomUUID() };
62
+ });
63
+ }
64
+ }
@@ -0,0 +1,126 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { StringEnum } from "@earendil-works/pi-ai";
3
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { enabledScenarios } from "../settings/supervisor.ts";
6
+ import { OUTCOME_ENTRY } from "../task-context/outcome-state.ts";
7
+
8
+ const ENTRY = "pi-better-harness:supervisor-commitment";
9
+ type Status = "accepted" | "attempted" | "failed" | "verified";
10
+ type Commitment = { id: string; outcome: string; action: string; verification: string; status: Status;
11
+ evidence?: string; observed?: string; reminder?: number };
12
+ type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
13
+ function outcomeId(branch: Branch) {
14
+ for (let i = branch.length - 1; i >= 0; i--) {
15
+ const e = branch[i]!;
16
+ if (e.type === "custom" && e.customType === OUTCOME_ENTRY)
17
+ return (e.data as { outcome?: { status?: string } })?.outcome?.status === "active" ? e.id : undefined;
18
+ }
19
+ }
20
+ function records(branch: Branch) {
21
+ const outcome = outcomeId(branch);
22
+ const items = new Map<string, Commitment>();
23
+ if (!outcome) return items;
24
+ for (const e of branch) {
25
+ if (e.type !== "custom" || e.customType !== ENTRY) continue;
26
+ const item = e.data as Commitment;
27
+ if (item?.outcome === outcome && typeof item.id === "string") items.set(item.id, item);
28
+ }
29
+ return items;
30
+ }
31
+ function describe(c: Commitment) {
32
+ return [`${c.id} · ${c.status}: ${c.action}`, `Verify: ${c.verification}`, c.observed, c.evidence && `Tool result: ${c.evidence}`,
33
+ c.reminder && `Reminder: ${new Date(c.reminder).toISOString()}`].filter(Boolean).join("\n");
34
+ }
35
+ export function registerCommitments(pi: ExtensionAPI, onFailure: (ctx: ExtensionContext, evidence: string) => void) {
36
+ let timer: ReturnType<typeof setTimeout> | undefined;
37
+ const enabled = () => enabledScenarios().includes("commitment-followup");
38
+ function clear() { clearTimeout(timer); timer = undefined; }
39
+ function schedule(ctx: ExtensionContext) {
40
+ clear();
41
+ if (!enabled()) return;
42
+ const due = [...records(ctx.sessionManager.getBranch()).values()]
43
+ .filter(c => c.status !== "verified" && c.reminder !== undefined).sort((a, b) => a.reminder! - b.reminder!)[0];
44
+ if (!due) return;
45
+ timer = setTimeout(() => {
46
+ if (!enabled()) return;
47
+ const current = records(ctx.sessionManager.getBranch()).get(due.id);
48
+ if (current?.reminder === due.reminder && current?.status !== "verified") {
49
+ pi.appendEntry(ENTRY, { ...current, reminder: undefined });
50
+ pi.sendMessage({ customType: ENTRY, content: describe({ ...due, reminder: undefined }), display: true }, { triggerTurn: false });
51
+ }
52
+ schedule(ctx);
53
+ }, Math.max(0, due.reminder! - Date.now()));
54
+ timer.unref();
55
+ }
56
+ pi.on("session_shutdown", clear);
57
+ pi.on("session_start", (_e, ctx) => schedule(ctx));
58
+ pi.on("session_tree", (_e, ctx) => schedule(ctx));
59
+ pi.on("agent_start", (_e, ctx) => schedule(ctx));
60
+ pi.registerCommand("supervisor-followup", {
61
+ description: "Show recovery commitments, or request one reminder with: remind <id> <minutes>",
62
+ handler: async (args, ctx) => {
63
+ if (!enabled()) return ctx.ui.notify("Commitment follow-up is disabled.", "info");
64
+ const items = records(ctx.sessionManager.getBranch());
65
+ if (!args.trim()) return ctx.ui.notify([...items.values()].map(describe).join("\n\n") || "No recorded recovery commitments.", "info");
66
+ const match = /^remind\s+(\S+)\s+(\d+)$/.exec(args.trim());
67
+ const c = match && items.get(match[1]!);
68
+ const minutes = match && Number(match[2]);
69
+ if (!c || c.status === "verified" || !minutes || minutes > 1440)
70
+ return ctx.ui.notify("Use remind <open commitment id> <1–1440 minutes>.", "warning");
71
+ pi.appendEntry(ENTRY, { ...c, reminder: Date.now() + minutes * 60_000 });
72
+ schedule(ctx);
73
+ ctx.ui.notify(`Reminder scheduled in ${minutes} minutes.`, "info");
74
+ },
75
+ });
76
+ pi.registerTool({
77
+ name: "supervisor_followup", label: "Recovery commitments",
78
+ description: "Record an agreed recovery and its expected verification, or check progress without sending another reminder. Attach the tool call ID for attempts and a separate successful verification. Use status to answer follow-up questions.",
79
+ parameters: Type.Object({
80
+ action: StringEnum(["accept", "attempt", "verify", "status"] as const), id: Type.Optional(Type.String()),
81
+ recovery: Type.Optional(Type.String({ maxLength: 500 })), verification: Type.Optional(Type.String({ maxLength: 500 })),
82
+ toolCallId: Type.Optional(Type.String({ maxLength: 256 })), observation: Type.Optional(Type.String({ maxLength: 500 })),
83
+ }),
84
+ async execute(_id, p, _signal, _update, ctx) {
85
+ const reply = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
86
+ if (!enabled()) return reply("Commitment follow-up is disabled.");
87
+ const branch = ctx.sessionManager.getBranch();
88
+ const outcome = outcomeId(branch);
89
+ if (!outcome) return reply("No active Outcome.");
90
+ const items = records(branch);
91
+ if (p.action === "status" && !p.id) return reply([...items.values()].map(describe).join("\n\n") || "No recorded commitments.");
92
+ if (p.action === "accept") {
93
+ const action = p.recovery?.trim(), verification = p.verification?.trim();
94
+ if (!action || !verification) throw new Error("Supply the recovery action and its verification condition.");
95
+ const existing = [...items.values()].find(c => c.action === action && c.verification === verification && c.status !== "verified");
96
+ if (existing) return reply(describe(existing));
97
+ const c: Commitment = { id: randomUUID(), outcome, status: "accepted", action, verification };
98
+ pi.appendEntry(ENTRY, c);
99
+ return reply(describe(c));
100
+ }
101
+ const c = items.get(p.id ?? "");
102
+ if (!c) throw new Error("Unknown commitment in this Outcome.");
103
+ if (p.action === "status") return reply(describe(c));
104
+
105
+ const latest = branch.map(e => e.type === "custom" && e.customType === ENTRY && (e.data as Commitment)?.id === c.id).lastIndexOf(true);
106
+ const evidence = branch.slice(latest + 1).find(e => e.type === "message" && e.message.role === "toolResult" &&
107
+ e.message.toolCallId === p.toolCallId && !e.message.toolName.startsWith("supervisor_"));
108
+ if (c.evidence === p.toolCallId && c.evidence) {
109
+ if (p.action === "verify" && c.status === "attempted") throw new Error("Verification requires a separate observed result.");
110
+ return reply(describe(c));
111
+ }
112
+ if (!evidence || evidence.type !== "message" || evidence.message.role !== "toolResult") throw new Error("Provide a new tool result from this branch after the last commitment update.");
113
+ if (c.status === "verified" || p.action === "verify" && c.status !== "attempted") throw new Error("Record a successful attempt before verification.");
114
+ if (!p.observation?.trim()) throw new Error("Describe what the tool result establishes.");
115
+ const next: Commitment = { ...c, status: evidence.message.isError ? "failed" : p.action === "verify" ? "verified" : "attempted",
116
+ evidence: evidence.message.toolCallId, observed: p.observation.trim() };
117
+ if (next.status === "verified") delete next.reminder;
118
+ pi.appendEntry(ENTRY, next);
119
+ schedule(ctx);
120
+ if (next.status === "failed") onFailure(ctx, JSON.stringify({
121
+ commitment: next.id, failedRecovery: next.action, expected: next.verification, observed: next.observed,
122
+ }));
123
+ return reply(describe(next));
124
+ },
125
+ });
126
+ }
@@ -0,0 +1,80 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { Type } from "typebox";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import type { openSupervisorClient } from "pi-better-subagents/supervisor-client.mjs";
5
+ import { scenarioRevision } from "../settings/supervisor.ts";
6
+ import { digest, scopeEvidence } from "./evidence.ts";
7
+
8
+ const ENTRY = "pi-better-harness:supervisor-decision";
9
+ type DecisionRecord = { owner: string; proposal: string; outcome: string; status: string; expires?: number; result?: string; successful?: boolean };
10
+
11
+ export function registerDecisionTool(pi: ExtensionAPI, connect: typeof openSupervisorClient) {
12
+ const field = (description: string) => Type.String({ minLength: 1, maxLength: 200, description });
13
+ pi.registerTool({
14
+ name: "supervisor_request_decision",
15
+ label: "Supervisor decision",
16
+ description: "Ask the user once about a proposed action shared by owners in this trusted workspace. Reuse the same exact proposal when checking back. Apply the normal tool permission checks when acting. Once the covered effect has been checked, record its observed tool result using verifyToolCallId.",
17
+ parameters: Type.Object({
18
+ reference: field("Stable identifier for this proposed change, shared by the affected owners."),
19
+ operation: field("Exact action requiring a decision."), host: field("Exact host or service."),
20
+ verifyToolCallId: Type.Optional(field("Original tool result that verified the authorized effect in this session.")),
21
+ resource: field("Concrete resource affected."), effect: field("Exact side effect to authorize."),
22
+ }),
23
+ async execute(_id, { verifyToolCallId, ...proposal }, abort, _update, ctx) {
24
+ const reply = (status: string) => ({ content: [{ type: "text" as const, text: `Supervisor decision: ${status}` }], details: { status } });
25
+ const setting = scenarioRevision("shared-decisions");
26
+ if (!setting) return reply("disabled");
27
+ const session = ctx.sessionManager.getSessionId();
28
+ const branch = ctx.sessionManager.getBranch();
29
+ const scope = scopeEvidence(branch);
30
+ const revision = scope?.revision;
31
+ if (!scope || !revision || !ctx.isProjectTrusted()) return reply("requires an active Outcome in a trusted workspace");
32
+ const current = () => ctx.sessionManager.getSessionId() === session &&
33
+ scopeEvidence(ctx.sessionManager.getBranch())?.revision === revision && scenarioRevision("shared-decisions") === setting;
34
+ const key = digest(JSON.stringify([proposal.reference, proposal.operation, proposal.host, proposal.resource, proposal.effect]));
35
+ const index = branch.map(e => {
36
+ if (e.type !== "custom" || e.customType !== ENTRY) return false;
37
+ const r = e.data as DecisionRecord;
38
+ return r.proposal === key && r.outcome === scope.outcomeId && r.owner === session;
39
+ }).lastIndexOf(true);
40
+ const entry = branch[index];
41
+ const last = entry?.type === "custom" ? entry.data as DecisionRecord : undefined;
42
+ if (verifyToolCallId) {
43
+ if (last?.status !== "approved") return reply("no approved decision in this Outcome");
44
+ if (last.result === verifyToolCallId) return reply(last.successful ? "verified" : "verification failed");
45
+ const proof = branch.slice(index + 1).find(e => e.type === "message" && e.message.role === "toolResult" &&
46
+ e.message.toolCallId === verifyToolCallId && !e.message.toolName.startsWith("supervisor_"));
47
+ if (proof?.type !== "message" || proof.message.role !== "toolResult") return reply("missing observed result after approval");
48
+ pi.appendEntry(ENTRY, { ...last, result: verifyToolCallId, successful: !proof.message.isError } satisfies DecisionRecord);
49
+ return reply(proof.message.isError ? "verification failed" : "verified");
50
+ }
51
+ const deadline = AbortSignal.timeout(125_000);
52
+ const signal = abort ? AbortSignal.any([deadline, abort]) : deadline;
53
+ const client = await connect(pi, ctx, signal);
54
+ try {
55
+ let result = await client.decision(ctx.hasUI ? "decision-request" : "decision-query", proposal);
56
+ if (result.status === "ask") {
57
+ const token = result.token;
58
+ const lines = Object.entries(proposal).map(([k, v]) => `${k}: ${v}`);
59
+ const scope = `${lines.join("\n")}\n\nApplies for ${result.durationMinutes} minutes to owners requesting this exact action in ${result.workspace}.`;
60
+ const choice = current() && !signal.aborted ? await ctx.ui.select(scope, ["Approve", "Deny"], { signal, timeout: result.timeoutMs }) : undefined;
61
+ const answer = !current() || signal.aborted || !choice ? "cancelled" : choice === "Approve" ? "approved" : "denied";
62
+ result = await client.decision("decision-answer", proposal, token, answer);
63
+ } else {
64
+ // Other owners wait for this question's answer without opening another dialog.
65
+ while (result.status === "pending" && current() && !signal.aborted) {
66
+ await delay(1500, undefined, { signal });
67
+ result = await client.decision("decision-query", proposal);
68
+ }
69
+ }
70
+ if (!current()) return reply("stale");
71
+ if (result.status === "approved" || result.status === "denied") {
72
+ if (last?.status !== result.status || last.expires !== result.expires)
73
+ pi.appendEntry(ENTRY, { owner: session, proposal: key, outcome: scope.outcomeId, status: result.status, expires: result.expires } satisfies DecisionRecord);
74
+ else if (last.result) return reply(`${result.status} · ${last.successful ? "verified" : "verification failed"}`);
75
+ }
76
+ return reply(result.status);
77
+ } finally { client.close(); }
78
+ },
79
+ });
80
+ }
@@ -0,0 +1,53 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { ExtensionContext, ToolResultEvent } from "@earendil-works/pi-coding-agent";
3
+ import { OUTCOME_ENTRY, type Outcome } from "../task-context/outcome-state.ts";
4
+ import { EXTENSION_NAME, type PlanEntry } from "../task-context/types.ts";
5
+
6
+ export type Scenario = "stall-diagnosis" | "scope-review" | "commitment-followup";
7
+ type Branch = ReturnType<ExtensionContext["sessionManager"]["getBranch"]>;
8
+ export const ENTRY = "pi-better-harness:supervisor-review";
9
+ export const digest = (text: string) => createHash("sha256").update(text).digest("hex");
10
+
11
+ /** Keep the fingerprint local. File contents and raw tool output never enter a model prompt here. */
12
+ export function readFingerprint(event: ToolResultEvent) {
13
+ if (event.isError || !["read", "grep", "find", "ls"].includes(event.toolName)) return;
14
+ const hash = createHash("sha256");
15
+ hash.update(JSON.stringify(event.input));
16
+ for (const block of event.content) {
17
+ if (block.type !== "text" || block.text.length > 64_000) return;
18
+ hash.update(JSON.stringify(block.text));
19
+ }
20
+ return { tool: event.toolName, target: typeof event.input.path === "string" ? event.input.path.slice(-250) : "current workspace", fingerprint: hash.digest("hex") };
21
+ }
22
+ export class RepeatedRead {
23
+ private last?: { fingerprint: string; since: number; count: number };
24
+ reset() { this.last = undefined; }
25
+ record(value: string, now: number, minimumAge: number) {
26
+ if (this.last?.fingerprint !== value) this.last = { fingerprint: value, since: now, count: 0 };
27
+ this.last.count++;
28
+ if (this.last.count >= 3 && now - this.last.since >= minimumAge) return this.last.since;
29
+ }
30
+ }
31
+
32
+ export function scopeEvidence(branch: Branch) {
33
+ const newest = [...branch].reverse();
34
+ const outcomeEntry = newest.find(entry => entry.type === "custom" && entry.customType === OUTCOME_ENTRY);
35
+ const outcome = outcomeEntry?.type === "custom" && (outcomeEntry.data as { outcome?: Outcome })?.outcome;
36
+ if (!outcome || outcome.status !== "active" || typeof outcome.objective !== "string") return;
37
+ const user = newest.find(entry => entry.type === "message" && entry.message.role === "user");
38
+ const content = user?.type === "message" && user.message.role === "user" ? user.message.content : "";
39
+ const lastInstruction = typeof content === "string" ? content : content.filter(x => x.type === "text").map(x => x.text).join("\n");
40
+ const plan = newest.find(entry => entry.type === "custom" && entry.customType === EXTENSION_NAME &&
41
+ ["set", "clear"].includes((entry.data as PlanEntry | undefined)?.kind ?? ""));
42
+ const data = plan?.type === "custom" ? plan.data as PlanEntry : undefined;
43
+ const steps = data?.kind === "set" && Array.isArray(data.plan?.steps) ? data.plan.steps.slice(0, 50).map(s => ({ id: s.id, step: s.step, status: s.status })) : [];
44
+ return {
45
+ outcomeId: outcomeEntry!.id,
46
+ planId: data?.kind === "set" ? data.plan.planId : undefined,
47
+ revision: [outcomeEntry!.id, user?.id, plan?.id].join("/"),
48
+ objective: outcome.objective.slice(0, 2000),
49
+ doneWhen: outcome.doneWhen?.slice(0, 8).map(s => s.slice(0, 400)),
50
+ boundaries: outcome.boundaries?.slice(0, 8).map(s => s.slice(0, 400)),
51
+ lastInstruction: lastInstruction.slice(-2000), steps,
52
+ };
53
+ }