pi-better-goal 0.13.3 → 0.14.1
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/README.md +10 -3
- package/package.json +1 -1
- package/src/index.ts +56 -12
- package/src/preferences.ts +6 -3
- package/src/settings-page.ts +2 -1
- package/src/shared-assignment-observation.mjs +63 -3
- package/src/shared-assignment-projection.mjs +12 -4
- package/src/shared-harness-settings.ts +4 -2
- package/src/task-context.ts +25 -3
- package/src/workflow-gates.ts +77 -11
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Use `pi-better-goal` when a Pi session should keep an explicit objective visible
|
|
|
13
13
|
## Core Features
|
|
14
14
|
|
|
15
15
|
- `/goal` runtime for starting, pausing, resuming, completing, and clearing the current objective.
|
|
16
|
-
- `/goal settings` opens an interactive settings page in the TUI. Select a row with Up/Down and toggle with Space/Enter; changes save immediately, and Escape closes the page.
|
|
16
|
+
- `/goal settings` opens an interactive settings page in the TUI. Select a row with Up/Down and toggle with Space/Enter; changes save immediately, and Escape closes the page. Automatic continuation, conversational resume, and **Pause on Esc** default to `on`. **Auto-start Goal** defaults to `off` and is also available directly on the `/harness-settings` main page. Automatic continuation controls idle and background-drain wakes; conversational resume controls the agent's Escape-pause resume tool; Pause on Esc controls whether editor Escape pauses the active goal. Goal kickoff, `/goal resume`, and `alt+g` remain available with these controls off. For scripts or non-interactive sessions, use `/goal settings auto-continue on|off`, `/goal settings conversational-resume on|off`, `/goal settings pause-on-escape on|off`, or `/goal settings auto-start-from-outcome on|off`; bare `/goal settings` prints the saved values outside the TUI.
|
|
17
17
|
- `escape` pauses the active goal by default, and it stays paused while you talk to the agent. With **Pause on Esc** off, observed editor Escape leaves the goal active while preserving native streaming interruption and menu/dialog cancellation. Automatic continuation remains independent. Hosts without terminal/focus inspection and unknown custom editors retain generic abort-to-pause behavior because they cannot identify Escape reliably. With conversational resume enabled, say "go" (the agent then calls `goal_resume`), or use `/goal resume` or `alt+g`. `/goal pause` resumes only through `/goal resume` or `alt+g`. Paused goals are never poked. On a macOS terminal without Option-as-Meta, `alt+g` types `©`; use `/goal resume` there.
|
|
18
18
|
- Background work that finishes while an `ask_user_question` is pending is handed to the agent right after the answer.
|
|
19
19
|
- A compact goal widget that does not replace Pi's footer.
|
|
@@ -28,13 +28,20 @@ When `pi-better-harness` is installed, its optional **Outcome & Todo** runtime o
|
|
|
28
28
|
|
|
29
29
|
`/goal` does not install, enable, or configure Outcome & Todo. Install Harness and enable **Outcome & Todo** in `/harness-settings` if you want that shared outcome and checklist. Without Harness, this package keeps its standalone prompts and behavior unchanged. The stored Goal objective remains the raw original trigger (for example, a bound command invocation) so `/goal resume` can re-enter the work; it is not the authoritative business outcome when Harness owns one.
|
|
30
30
|
|
|
31
|
+
With **Auto-start Goal** enabled, a successful explicit `update_todo` outcome save can create and bind a Goal. The outcome must be active, unbound, have a nonempty objective and at least one nonempty `doneWhen` acceptance criterion. All criteria must contain text. Slash-shaped command invocations do not qualify; invoke those commands explicitly. Outcome & Todo hooks must also be enabled. The existing outcome, boundaries and Todo stay intact. No kickoff message is queued for the already-running tool turn; subsequent idle/background continuation obeys its existing setting and gates.
|
|
32
|
+
|
|
33
|
+
Existing active, paused or budget-limited Goals are never replaced or resumed. Refinements of a bound outcome do not create another Goal. A new unbound task can start after the previous Goal completes. Session restore, branch navigation and enabling the preference do not replay saved outcomes; the next explicit qualifying save is the trigger. Completing a checklist or outcome does not complete the Goal.
|
|
34
|
+
|
|
35
|
+
When a workflow already owns the session, the new Goal binds its registered coordinator without invoking it again. Its scheduler and completion checks continue to apply. An unavailable or invalid workflow coordinator prevents automatic creation.
|
|
36
|
+
|
|
31
37
|
## Settings Storage
|
|
32
38
|
|
|
33
39
|
Goal preferences are saved only in Pi's global `~/.pi/agent/settings.json` under
|
|
34
40
|
`piBetterHarness.goal` (or `$PI_CODING_AGENT_DIR/settings.json` when overridden).
|
|
35
41
|
The payload retains `version: 1` and the boolean `autoContinue`,
|
|
36
|
-
`conversationalResume`, and `
|
|
37
|
-
|
|
42
|
+
`conversationalResume`, `pauseOnEscape`, and `autoStartFromOutcome` fields. The
|
|
43
|
+
first three default to `true`; `autoStartFromOutcome` defaults to `false`.
|
|
44
|
+
Updates preserve other Pi settings and other `piBetterHarness` keys.
|
|
38
45
|
|
|
39
46
|
On first read, an existing `extensions/pi-better-goal-preferences.json` in the
|
|
40
47
|
agent directory is validated and migrated when the global Goal key is absent.
|
package/package.json
CHANGED
package/src/index.ts
CHANGED
|
@@ -45,7 +45,7 @@ import { collectSubagentActivity } from "./subagents.js";
|
|
|
45
45
|
import { currentWorkflowOwner, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
|
|
46
46
|
import { completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
|
|
47
47
|
import { workflowRehydrateMessage, WORKFLOW_REHYDRATE_MESSAGE_TYPE } from "./rehydrate.js";
|
|
48
|
-
import { requestTaskContext } from "./task-context.js";
|
|
48
|
+
import { canStartGoalFromOutcome, OUTCOME_ACCEPTED_EVENT, requestTaskContext, type OutcomeAcceptedEvent } from "./task-context.js";
|
|
49
49
|
import {
|
|
50
50
|
EVENT_ACTIVITY,
|
|
51
51
|
EVENT_READY,
|
|
@@ -125,10 +125,10 @@ const GOAL_ACTIONS: readonly AutocompleteItem[] = [
|
|
|
125
125
|
{ value: "resume", label: "resume", description: "Resume the paused goal" },
|
|
126
126
|
{ value: "clear", label: "clear", description: "Remove the current goal" },
|
|
127
127
|
{ value: "complete", label: "complete", description: "Mark the current goal complete" },
|
|
128
|
-
{ value: "settings", label: "settings", description: "Inspect or persist goal continuation,
|
|
128
|
+
{ value: "settings", label: "settings", description: "Inspect or persist goal continuation, resume, Escape pause, and Outcome auto-start controls" },
|
|
129
129
|
];
|
|
130
130
|
|
|
131
|
-
const GOAL_SETTINGS = ["auto-continue", "conversational-resume", "pause-on-escape"] as const;
|
|
131
|
+
const GOAL_SETTINGS = ["auto-continue", "conversational-resume", "pause-on-escape", "auto-start-from-outcome"] as const;
|
|
132
132
|
|
|
133
133
|
export function goalArgumentCompletions(argumentPrefix: string): AutocompleteItem[] | null {
|
|
134
134
|
const prefix = argumentPrefix.trimStart().toLowerCase();
|
|
@@ -244,7 +244,7 @@ function formatGoal(
|
|
|
244
244
|
goal: GoalSnapshot | null,
|
|
245
245
|
continuation: ReturnType<typeof currentContinuationState> = null,
|
|
246
246
|
stall = observeGoalStall(goal, continuation),
|
|
247
|
-
preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true },
|
|
247
|
+
preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true, autoStartFromOutcome: false },
|
|
248
248
|
permissions?: PermissionHold | null,
|
|
249
249
|
): string {
|
|
250
250
|
const settings = formatPreferences(preferences);
|
|
@@ -285,6 +285,7 @@ function formatPreferences(preferences: GoalPreferences): string {
|
|
|
285
285
|
`Automatic continuation setting: ${preferences.autoContinue ? "on" : "off"}${WAKE_DISABLED ? " (disabled by environment)" : ""}`,
|
|
286
286
|
`Conversational resume setting: ${preferences.conversationalResume ? "on" : "off"}`,
|
|
287
287
|
`Pause on Esc setting: ${preferences.pauseOnEscape ? "on" : "off"}`,
|
|
288
|
+
`Auto-start Goal setting: ${preferences.autoStartFromOutcome ? "on" : "off"}`,
|
|
288
289
|
].join("\n");
|
|
289
290
|
}
|
|
290
291
|
|
|
@@ -317,6 +318,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
317
318
|
let currentCtx: ExtensionContext | undefined;
|
|
318
319
|
let executionGeneration = 0;
|
|
319
320
|
let operationAdmissionRevision = 0;
|
|
321
|
+
const operationAdmissionScope = {};
|
|
320
322
|
let agentGeneration = -1;
|
|
321
323
|
let turnGeneration = 0;
|
|
322
324
|
let escapeAbortSuppression: { session: number; turn: number; execution: number } | undefined;
|
|
@@ -341,7 +343,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
341
343
|
let terminalInputIsEditor: (() => boolean) | undefined;
|
|
342
344
|
let uiPromptDepth = 0;
|
|
343
345
|
let lastAgentEvidence: ContinuationEvidence | null = null;
|
|
344
|
-
let preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true };
|
|
346
|
+
let preferences: GoalPreferences = { autoContinue: true, conversationalResume: true, pauseOnEscape: true, autoStartFromOutcome: false };
|
|
345
347
|
/** Background items active when each pending blocking question started, keyed by tool call id. */
|
|
346
348
|
const pendingQuestions = new Map<string, Map<string, BackgroundWorkItem>>();
|
|
347
349
|
|
|
@@ -396,7 +398,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
396
398
|
ctx.ui.notify(message, type);
|
|
397
399
|
};
|
|
398
400
|
|
|
399
|
-
const setGoal = (goal: GoalSnapshot, ctx: ExtensionContext, source: GoalEntrySource): void => {
|
|
401
|
+
const setGoal = (goal: GoalSnapshot, ctx: ExtensionContext, source: GoalEntrySource, bindOutcome = false): void => {
|
|
400
402
|
executionGeneration += 1;
|
|
401
403
|
lastAgentEvidence = null;
|
|
402
404
|
const previous = getGoal(ctx);
|
|
@@ -405,7 +407,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
405
407
|
// Bridge lifecycle after the raw Goal entry is durable. Harness may own the
|
|
406
408
|
// structured outcome, but Goal still owns its trigger, clocks, pauses, and wakes.
|
|
407
409
|
if (!previous || previous.goalId !== goal.goalId) {
|
|
408
|
-
requestTaskContext(pi, "start", goal);
|
|
410
|
+
requestTaskContext(pi, bindOutcome ? "bind" : "start", goal);
|
|
409
411
|
} else if (goal.status === "complete") {
|
|
410
412
|
requestTaskContext(pi, "complete", goal);
|
|
411
413
|
} else if (goal.status === "paused" || goal.status === "budgetLimited") {
|
|
@@ -855,7 +857,11 @@ export default function (pi: ExtensionAPI): void {
|
|
|
855
857
|
if (goal && currentContinuationState(ctx, goal.goalId)?.blocked) { held("Goal continuation requires human resume"); return; }
|
|
856
858
|
if (goal && !boundCommandReady(goal, ctx)) { held("Bound workflow is not ready"); return; }
|
|
857
859
|
const workflow = getWorkflow(ctx);
|
|
858
|
-
void (workflow ? operationResumeSchedulerGate(ctx.sessionManager.getBranch(), workflow
|
|
860
|
+
void (workflow ? operationResumeSchedulerGate(ctx.sessionManager.getBranch(), workflow, {
|
|
861
|
+
scope: operationAdmissionScope,
|
|
862
|
+
revision: JSON.stringify([request.owner.sessionId, request.owner.workspace, request.owner.branchId, goal?.goalId, revision, preferencesRevision]),
|
|
863
|
+
getEntries: () => ctx.sessionManager.getBranch(),
|
|
864
|
+
}) : Promise.resolve({ ok: true as const, waitUntil: undefined, isCurrent: () => true })).then((gate) => {
|
|
859
865
|
if (ctx !== currentCtx || revision !== executionGeneration || preferencesRevision !== operationAdmissionRevision || !operationOwnerMatches(currentCtx, request.owner!)) {
|
|
860
866
|
held("Parent execution changed during resume admission"); return;
|
|
861
867
|
}
|
|
@@ -866,6 +872,9 @@ export default function (pi: ExtensionAPI): void {
|
|
|
866
872
|
held("Goal became held during resume admission"); return;
|
|
867
873
|
}
|
|
868
874
|
if (!gate.ok) { held(gate.reason); return; }
|
|
875
|
+
if (JSON.stringify(getWorkflow(ctx)) !== JSON.stringify(workflow) || !gate.isCurrent()) {
|
|
876
|
+
held("Bound workflow changed during resume admission"); return;
|
|
877
|
+
}
|
|
869
878
|
if (gate.waitUntil && gate.waitUntil > Date.now()) { held("Workflow scheduler is waiting"); return; }
|
|
870
879
|
// An in-process capability lets the dispatcher validate this admission
|
|
871
880
|
// after its last await and immediately before releasing execution.
|
|
@@ -875,6 +884,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
875
884
|
const active = getGoal(ctx);
|
|
876
885
|
if ((request.owner!.goalId ?? null) !== (active?.goalId ?? null)) return false;
|
|
877
886
|
if (JSON.stringify(getWorkflow(ctx)) !== JSON.stringify(workflow)) return false;
|
|
887
|
+
if (!gate.isCurrent()) return false;
|
|
878
888
|
return !active || (preferences.autoContinue && isPokeable(active)
|
|
879
889
|
&& !currentContinuationState(ctx, active.goalId)?.blocked && boundCommandReady(active, ctx));
|
|
880
890
|
};
|
|
@@ -897,6 +907,24 @@ export default function (pi: ExtensionAPI): void {
|
|
|
897
907
|
if (latestSnapshot) collectIfPossible();
|
|
898
908
|
});
|
|
899
909
|
|
|
910
|
+
const unsubscribeOutcomeAccepted = pi.events.on(OUTCOME_ACCEPTED_EVENT, (value: unknown) => {
|
|
911
|
+
const ctx = currentCtx;
|
|
912
|
+
const event = value as Partial<OutcomeAcceptedEvent> | null;
|
|
913
|
+
if (!preferences.autoStartFromOutcome || !ctx || !event ||
|
|
914
|
+
typeof event.sessionId !== "string" || event.sessionId !== ctx.sessionManager.getSessionId() ||
|
|
915
|
+
!canStartGoalFromOutcome(event.outcome)) return;
|
|
916
|
+
const current = getGoal(ctx);
|
|
917
|
+
if (current && current.status !== "complete") return;
|
|
918
|
+
const objective = event.outcome.objective.trim();
|
|
919
|
+
if (validateObjective(objective)) return;
|
|
920
|
+
const owner = getWorkflow(ctx);
|
|
921
|
+
if (owner && !workflowAvailable(owner)) return;
|
|
922
|
+
const command = owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null;
|
|
923
|
+
const goal = createGoalSnapshot(objective, null, undefined, command ?? undefined);
|
|
924
|
+
setGoal(goal, ctx, "runtime", true);
|
|
925
|
+
resetContinuationState(goal);
|
|
926
|
+
});
|
|
927
|
+
|
|
900
928
|
const changePreference = async (ctx: ExtensionCommandContext, key: keyof GoalPreferences, enabled: boolean): Promise<void> => {
|
|
901
929
|
const previous = preferences;
|
|
902
930
|
preferences = writeGoalPreference(key, enabled);
|
|
@@ -923,7 +951,20 @@ export default function (pi: ExtensionAPI): void {
|
|
|
923
951
|
}
|
|
924
952
|
};
|
|
925
953
|
const contribution = { id: "goal", label: "Goal", command: "/goal settings", open: openSettings };
|
|
926
|
-
const
|
|
954
|
+
const autoStartControl = {
|
|
955
|
+
id: "goal-auto-start",
|
|
956
|
+
label: "Auto-start Goal",
|
|
957
|
+
values: ["Off", "On"],
|
|
958
|
+
get: () => preferences.autoStartFromOutcome ? "On" : "Off",
|
|
959
|
+
async change(value: string, ctx: ExtensionCommandContext) {
|
|
960
|
+
if (value !== "On" && value !== "Off") throw new Error("Invalid Auto-start Goal mode.");
|
|
961
|
+
await changePreference(ctx, "autoStartFromOutcome", value === "On");
|
|
962
|
+
},
|
|
963
|
+
};
|
|
964
|
+
const registerSettings = () => {
|
|
965
|
+
pi.events.emit("harness-settings:register", contribution);
|
|
966
|
+
pi.events.emit("harness-settings:register", autoStartControl);
|
|
967
|
+
};
|
|
927
968
|
const unsubscribeSettingsRequest = pi.events.on("harness-settings:request", registerSettings);
|
|
928
969
|
registerSettings();
|
|
929
970
|
|
|
@@ -943,13 +984,14 @@ export default function (pi: ExtensionAPI): void {
|
|
|
943
984
|
const [, setting, mode, ...extra] = trimmed.split(/\s+/);
|
|
944
985
|
if (setting !== undefined && (!GOAL_SETTINGS.includes(setting as typeof GOAL_SETTINGS[number]) ||
|
|
945
986
|
(mode !== "on" && mode !== "off") || extra.length > 0)) {
|
|
946
|
-
notifyGoal(ctx, "Usage: /goal settings [auto-continue|conversational-resume|pause-on-escape on|off]", "warning");
|
|
987
|
+
notifyGoal(ctx, "Usage: /goal settings [auto-continue|conversational-resume|pause-on-escape|auto-start-from-outcome on|off]", "warning");
|
|
947
988
|
return;
|
|
948
989
|
}
|
|
949
990
|
if (setting !== undefined) {
|
|
950
991
|
try {
|
|
951
992
|
const key = setting === "auto-continue" ? "autoContinue"
|
|
952
|
-
: setting === "conversational-resume" ? "conversationalResume"
|
|
993
|
+
: setting === "conversational-resume" ? "conversationalResume"
|
|
994
|
+
: setting === "pause-on-escape" ? "pauseOnEscape" : "autoStartFromOutcome";
|
|
953
995
|
await changePreference(ctx, key, mode === "on");
|
|
954
996
|
} catch (error) {
|
|
955
997
|
notifyGoal(ctx, error instanceof Error ? error.message : String(error), "error");
|
|
@@ -1232,6 +1274,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
1232
1274
|
try {
|
|
1233
1275
|
preferences = readGoalPreferences();
|
|
1234
1276
|
} catch (error) {
|
|
1277
|
+
preferences = { ...preferences, autoStartFromOutcome: false };
|
|
1235
1278
|
notifyGoal(ctx, error instanceof Error ? error.message : String(error), "error");
|
|
1236
1279
|
}
|
|
1237
1280
|
const restoredGoal = getGoal(ctx);
|
|
@@ -1559,6 +1602,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
1559
1602
|
pi.on("session_shutdown", async (_event, ctx) => {
|
|
1560
1603
|
if (typeof unsubscribeSettingsRequest === "function") unsubscribeSettingsRequest();
|
|
1561
1604
|
if (typeof unsubscribeOperationAdmission === "function") unsubscribeOperationAdmission();
|
|
1605
|
+
if (typeof unsubscribeOutcomeAccepted === "function") unsubscribeOutcomeAccepted();
|
|
1562
1606
|
|
|
1563
1607
|
executionGeneration += 1;
|
|
1564
1608
|
sessionGeneration += 1;
|
|
@@ -1580,4 +1624,4 @@ export default function (pi: ExtensionAPI): void {
|
|
|
1580
1624
|
// Best-effort cleanup.
|
|
1581
1625
|
}
|
|
1582
1626
|
});
|
|
1583
|
-
}
|
|
1627
|
+
}
|
package/src/preferences.ts
CHANGED
|
@@ -11,6 +11,7 @@ export interface GoalPreferences {
|
|
|
11
11
|
autoContinue: boolean;
|
|
12
12
|
conversationalResume: boolean;
|
|
13
13
|
pauseOnEscape: boolean;
|
|
14
|
+
autoStartFromOutcome: boolean;
|
|
14
15
|
}
|
|
15
16
|
|
|
16
17
|
export interface GoalPreferenceSeams extends HarnessSettingsSeams {}
|
|
@@ -39,19 +40,21 @@ export function readGoalPreferences(seams: GoalPreferenceSeams = {}): GoalPrefer
|
|
|
39
40
|
|
|
40
41
|
function parseGoalPreferences(parsed: unknown, path: string): GoalPreferences {
|
|
41
42
|
if (parsed === undefined) {
|
|
42
|
-
return { autoContinue: true, conversationalResume: true, pauseOnEscape: true };
|
|
43
|
+
return { autoContinue: true, conversationalResume: true, pauseOnEscape: true, autoStartFromOutcome: false };
|
|
43
44
|
}
|
|
44
45
|
const value = parsed as Partial<GoalPreferences> & { version?: unknown } | null;
|
|
45
46
|
if (value?.version !== 1 ||
|
|
46
47
|
(value.autoContinue !== undefined && typeof value.autoContinue !== "boolean") ||
|
|
47
48
|
(value.conversationalResume !== undefined && typeof value.conversationalResume !== "boolean") ||
|
|
48
|
-
(value.pauseOnEscape !== undefined && typeof value.pauseOnEscape !== "boolean")
|
|
49
|
-
|
|
49
|
+
(value.pauseOnEscape !== undefined && typeof value.pauseOnEscape !== "boolean") ||
|
|
50
|
+
(value.autoStartFromOutcome !== undefined && typeof value.autoStartFromOutcome !== "boolean")) {
|
|
51
|
+
throw new Error(`Goal preferences at ${path} must contain version 1 and boolean autoContinue/conversationalResume/pauseOnEscape/autoStartFromOutcome settings.`);
|
|
50
52
|
}
|
|
51
53
|
return {
|
|
52
54
|
autoContinue: value.autoContinue ?? true,
|
|
53
55
|
conversationalResume: value.conversationalResume ?? true,
|
|
54
56
|
pauseOnEscape: value.pauseOnEscape ?? true,
|
|
57
|
+
autoStartFromOutcome: value.autoStartFromOutcome ?? false,
|
|
55
58
|
};
|
|
56
59
|
}
|
|
57
60
|
|
package/src/settings-page.ts
CHANGED
|
@@ -6,6 +6,7 @@ const rows: { key: keyof GoalPreferences; label: string }[] = [
|
|
|
6
6
|
{ key: "autoContinue", label: "Automatic continuation" },
|
|
7
7
|
{ key: "conversationalResume", label: "Conversational resume" },
|
|
8
8
|
{ key: "pauseOnEscape", label: "Pause on Esc" },
|
|
9
|
+
{ key: "autoStartFromOutcome", label: "Auto-start Goal" },
|
|
9
10
|
];
|
|
10
11
|
|
|
11
12
|
export function createGoalSettingsPage(
|
|
@@ -65,4 +66,4 @@ export function createGoalSettingsPage(
|
|
|
65
66
|
return lines.map((line) => truncateToWidth(line, w, ""));
|
|
66
67
|
},
|
|
67
68
|
};
|
|
68
|
-
}
|
|
69
|
+
}
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
// Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
|
|
2
2
|
import { createRequire } from "node:module";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
3
4
|
|
|
4
5
|
/** Read-only, bounded projection input. Never creates/migrates a database. */
|
|
5
|
-
export function readAssignmentWaits(path, owner) {
|
|
6
|
+
export function readAssignmentWaits(path, owner, connection) {
|
|
6
7
|
let db;
|
|
7
8
|
try {
|
|
8
9
|
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
9
|
-
db = new DatabaseSync(path, { readOnly: true });
|
|
10
|
+
db = connection ?? new DatabaseSync(path, { readOnly: true });
|
|
10
11
|
// v4 adds repair accounting; the observed wait/outcome fields are unchanged.
|
|
11
12
|
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
|
|
12
13
|
return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
|
|
@@ -38,6 +39,65 @@ export function readAssignmentWaits(path, owner) {
|
|
|
38
39
|
} catch {
|
|
39
40
|
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
40
41
|
} finally {
|
|
41
|
-
db?.close();
|
|
42
|
+
if (!connection) db?.close();
|
|
42
43
|
}
|
|
43
44
|
}
|
|
45
|
+
|
|
46
|
+
/** A root read model owns this connection; ordinary observers remain one-shot. */
|
|
47
|
+
export function createAssignmentReader(path) {
|
|
48
|
+
let db;
|
|
49
|
+
let identity;
|
|
50
|
+
const statements = new Map();
|
|
51
|
+
return {
|
|
52
|
+
revision() {
|
|
53
|
+
const { statSync } = createRequire(import.meta.url)("node:fs");
|
|
54
|
+
const stat = statSync(path, { bigint: true });
|
|
55
|
+
const next = `${stat.dev}:${stat.ino}`;
|
|
56
|
+
if (identity !== next) {
|
|
57
|
+
db?.close();
|
|
58
|
+
db = undefined;
|
|
59
|
+
statements.clear();
|
|
60
|
+
identity = next;
|
|
61
|
+
}
|
|
62
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
63
|
+
db ??= new DatabaseSync(path, { readOnly: true });
|
|
64
|
+
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
65
|
+
},
|
|
66
|
+
read(owner) {
|
|
67
|
+
try {
|
|
68
|
+
this.revision();
|
|
69
|
+
return readAssignmentWaits(path, owner, { prepare(sql) {
|
|
70
|
+
if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
|
|
71
|
+
return statements.get(sql);
|
|
72
|
+
} });
|
|
73
|
+
} catch {
|
|
74
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
75
|
+
}
|
|
76
|
+
},
|
|
77
|
+
conversationRevisions() {
|
|
78
|
+
try {
|
|
79
|
+
this.revision();
|
|
80
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
|
|
81
|
+
const hashes = new Map();
|
|
82
|
+
const add = (sessionId, workspace, value) => {
|
|
83
|
+
const key = JSON.stringify([sessionId, workspace]);
|
|
84
|
+
if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
|
|
85
|
+
hashes.get(key).update(JSON.stringify(value));
|
|
86
|
+
};
|
|
87
|
+
// One source pass per changed database revision, instead of one
|
|
88
|
+
// projection/query/log parse for every historical attempt.
|
|
89
|
+
for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
|
|
90
|
+
FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
|
|
91
|
+
FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
|
|
92
|
+
add(row.owner_session_id, row.owner_workspace, row);
|
|
93
|
+
}
|
|
94
|
+
for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
|
|
95
|
+
const record = JSON.parse(row.record_json);
|
|
96
|
+
add(record.owner.sessionId, record.owner.workspace, record);
|
|
97
|
+
}
|
|
98
|
+
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
99
|
+
} catch { return undefined; }
|
|
100
|
+
},
|
|
101
|
+
close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
102
|
+
};
|
|
103
|
+
}
|
|
@@ -1,11 +1,18 @@
|
|
|
1
1
|
// Generated from packages/pi-better-subagents/assignment-projection.mjs. Do not edit directly.
|
|
2
2
|
import { createHash } from "node:crypto";
|
|
3
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
3
4
|
import { readFileSync, readdirSync, statSync } from "node:fs";
|
|
4
5
|
import { homedir, tmpdir } from "node:os";
|
|
5
6
|
import { join } from "node:path";
|
|
6
7
|
import { readAssignmentWaits } from "./shared-assignment-observation.mjs";
|
|
7
8
|
|
|
8
9
|
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
10
|
+
const observations = new AsyncLocalStorage();
|
|
11
|
+
|
|
12
|
+
/** Bind an immutable observation to one read call, never to a supervision loop. */
|
|
13
|
+
export function withAssignmentObservations(rows, read) {
|
|
14
|
+
return observations.run(new Map(rows.map(row => [row.meta.id, row.assignment])), read);
|
|
15
|
+
}
|
|
9
16
|
|
|
10
17
|
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
11
18
|
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
@@ -177,6 +184,7 @@ export function createAssignmentProjector(options = {}) {
|
|
|
177
184
|
let prepared;
|
|
178
185
|
const snapshots = new Map();
|
|
179
186
|
const readSnapshot = (meta) => {
|
|
187
|
+
if (options.attempts) return options.attempts;
|
|
180
188
|
const key = conversationKey(meta.sessionId, meta.cwd);
|
|
181
189
|
if (!snapshots.has(key)) {
|
|
182
190
|
prepared ??= prepareAttemptIndex(options);
|
|
@@ -184,7 +192,7 @@ export function createAssignmentProjector(options = {}) {
|
|
|
184
192
|
}
|
|
185
193
|
return snapshots.get(key);
|
|
186
194
|
};
|
|
187
|
-
return (meta, processStatus = meta.status) => assignmentFromSnapshot(meta, processStatus, options,
|
|
195
|
+
return (meta, processStatus = meta.status) => observations.getStore()?.get(meta.id) ?? assignmentFromSnapshot(meta, processStatus, options,
|
|
188
196
|
() => readSnapshot(meta));
|
|
189
197
|
}
|
|
190
198
|
|
|
@@ -221,7 +229,7 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
|
221
229
|
const status = current.id === meta.id ? processStatus : current.status;
|
|
222
230
|
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
223
231
|
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
224
|
-
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
232
|
+
? (options.observe ?? ((owner) => readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"), owner)))(
|
|
225
233
|
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
226
234
|
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
227
235
|
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
@@ -232,6 +240,6 @@ function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
|
232
240
|
return projectAssignment(current, status, observation);
|
|
233
241
|
}
|
|
234
242
|
|
|
235
|
-
export function assignmentDiagnostic(assignment) {
|
|
236
|
-
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
243
|
+
export function assignmentDiagnostic(assignment, options = {}) {
|
|
244
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}.${options.includeEvidence === false ? "" : ` Evidence: ${assignment.evidence.join(", ")}`}`;
|
|
237
245
|
}
|
|
@@ -34,10 +34,12 @@ function section(settings: Record<string, unknown>): Record<string, unknown> {
|
|
|
34
34
|
}
|
|
35
35
|
|
|
36
36
|
function acquire(path: string): () => void {
|
|
37
|
-
|
|
37
|
+
// A live writer can be briefly descheduled; allow contention without stealing its lock.
|
|
38
|
+
const maxAttempts = 100;
|
|
39
|
+
for (let attempt = 0; attempt < maxAttempts; attempt++) {
|
|
38
40
|
try { return lockfile.lockSync(path, { realpath: false }); }
|
|
39
41
|
catch (error) {
|
|
40
|
-
if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt ===
|
|
42
|
+
if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === maxAttempts - 1) throw error;
|
|
41
43
|
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
|
|
42
44
|
}
|
|
43
45
|
}
|
package/src/task-context.ts
CHANGED
|
@@ -4,7 +4,29 @@ import type { GoalSnapshot } from "./types.js";
|
|
|
4
4
|
/** Synchronous request bus shared with an installed `pi-better-harness` runtime. */
|
|
5
5
|
export const TASK_CONTEXT_EVENT = "pi-better-harness:task-context";
|
|
6
6
|
|
|
7
|
-
export type TaskContextAction = "inspect" | "start" | "pause" | "resume" | "complete";
|
|
7
|
+
export type TaskContextAction = "inspect" | "start" | "bind" | "pause" | "resume" | "complete";
|
|
8
|
+
|
|
9
|
+
export const OUTCOME_ACCEPTED_EVENT = "pi-better-harness:outcome-accepted";
|
|
10
|
+
|
|
11
|
+
export interface OutcomeAcceptedEvent {
|
|
12
|
+
sessionId: string;
|
|
13
|
+
outcome: {
|
|
14
|
+
objective: string;
|
|
15
|
+
doneWhen?: readonly string[];
|
|
16
|
+
status: string;
|
|
17
|
+
goalId?: string;
|
|
18
|
+
};
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** Only explicit, actionable outcomes qualify; prose and restored state do not. */
|
|
22
|
+
export function canStartGoalFromOutcome(value: unknown): value is OutcomeAcceptedEvent["outcome"] {
|
|
23
|
+
if (!value || typeof value !== "object") return false;
|
|
24
|
+
const outcome = value as Partial<OutcomeAcceptedEvent["outcome"]>;
|
|
25
|
+
return outcome.status === "active" && outcome.goalId === undefined &&
|
|
26
|
+
typeof outcome.objective === "string" && !!outcome.objective.trim() && !outcome.objective.trim().startsWith("/") &&
|
|
27
|
+
Array.isArray(outcome.doneWhen) && outcome.doneWhen.length > 0 &&
|
|
28
|
+
outcome.doneWhen.every(item => typeof item === "string" && !!item.trim());
|
|
29
|
+
}
|
|
8
30
|
|
|
9
31
|
/**
|
|
10
32
|
* Mutable request. A present Harness runtime sets `enabled` to a boolean even
|
|
@@ -16,7 +38,7 @@ export interface TaskContextRequest {
|
|
|
16
38
|
goalId?: string;
|
|
17
39
|
/** Current widget width on a visual ownership inspection. */
|
|
18
40
|
width?: number;
|
|
19
|
-
/** The raw original goal trigger; only start requests carry it. */
|
|
41
|
+
/** The raw original goal trigger; only start/bind requests carry it. */
|
|
20
42
|
objective?: string;
|
|
21
43
|
/** Hooks authority: a present Harness runtime sets this even when Outcome & Todo is off. */
|
|
22
44
|
enabled?: boolean;
|
|
@@ -43,7 +65,7 @@ export function requestTaskContext(
|
|
|
43
65
|
if (width !== undefined) request.width = width;
|
|
44
66
|
if (goal) {
|
|
45
67
|
request.goalId = goal.goalId;
|
|
46
|
-
if (action === "start") request.objective = goal.objective;
|
|
68
|
+
if (action === "start" || action === "bind") request.objective = goal.objective;
|
|
47
69
|
}
|
|
48
70
|
pi.events.emit(TASK_CONTEXT_EVENT, request);
|
|
49
71
|
return request;
|
package/src/workflow-gates.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { execFile } from "node:child_process";
|
|
2
|
-
import { cpSync, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
|
|
2
|
+
import { cpSync, existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from "node:fs";
|
|
3
3
|
import { tmpdir } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
5
|
|
|
@@ -157,6 +157,7 @@ async function settlementScheduler(script: string, runDir: string, timeoutMs?: n
|
|
|
157
157
|
interface PlannedRun {
|
|
158
158
|
runDir: string;
|
|
159
159
|
script: string;
|
|
160
|
+
planPath: string;
|
|
160
161
|
}
|
|
161
162
|
|
|
162
163
|
/** The run a gate would check, or what it could not locate, so each gate decides how to report it. */
|
|
@@ -167,7 +168,7 @@ function locateRun(entries: Iterable<EntryLike>, owner: WorkflowOwner): RunLocat
|
|
|
167
168
|
if (!script) return { missing: "scheduler", problem: `${owner.name} ships no scheduler` };
|
|
168
169
|
const plan = boundPlanPath(entries, owner);
|
|
169
170
|
if (!plan) return { missing: "plan", problem: `no task plan is bound for ${owner.name} yet` };
|
|
170
|
-
return { runDir: dirname(plan), script };
|
|
171
|
+
return { runDir: dirname(plan), script, planPath: plan };
|
|
171
172
|
}
|
|
172
173
|
|
|
173
174
|
function unchecked(warning: string): GateVerdict {
|
|
@@ -308,19 +309,84 @@ export function waitUntil(due: readonly SchedulerAction[]): number | undefined {
|
|
|
308
309
|
return times.length > 0 ? Math.min(...times) : undefined;
|
|
309
310
|
}
|
|
310
311
|
|
|
311
|
-
export type OperationResumeSchedulerGate = { ok: true; waitUntil: number | undefined } | { ok: false; reason: string };
|
|
312
|
+
export type OperationResumeSchedulerGate = { ok: true; waitUntil: number | undefined; isCurrent: () => boolean } | { ok: false; reason: string };
|
|
312
313
|
|
|
313
|
-
|
|
314
|
-
|
|
314
|
+
const admissionChecks = new WeakMap<object, Map<string, Promise<OperationResumeSchedulerGate>>>();
|
|
315
|
+
|
|
316
|
+
function admissionBinding(entries: Iterable<EntryLike>): string {
|
|
317
|
+
return JSON.stringify(Array.from(entries).filter((entry) => entry.type === "custom"
|
|
318
|
+
&& (entry.customType === WORKFLOW_ENTRY || entry.customType === WORKFLOW_PLAN_ENTRY)));
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Check scheduler inputs without walking the workers' workspaces. */
|
|
322
|
+
function admissionInputs({ script, runDir }: PlannedRun): string {
|
|
323
|
+
const metadata = (path: string): string => {
|
|
324
|
+
try {
|
|
325
|
+
const stat = statSync(path, { bigint: true });
|
|
326
|
+
return `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}`;
|
|
327
|
+
} catch (error) {
|
|
328
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return "missing";
|
|
329
|
+
throw error;
|
|
330
|
+
}
|
|
331
|
+
};
|
|
332
|
+
const inputs = [script, ...["task-plan.json", "issue-tree.json", "next-actions-seen.json"].map((name) => join(runDir, name))];
|
|
333
|
+
for (const name of ["reviews", "results"]) {
|
|
334
|
+
const dir = join(runDir, name);
|
|
335
|
+
inputs.push(dir);
|
|
336
|
+
try {
|
|
337
|
+
for (const file of readdirSync(dir).filter((file) => file.endsWith(".json")).sort()) inputs.push(join(dir, file));
|
|
338
|
+
} catch (error) {
|
|
339
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
return JSON.stringify(inputs.map((path) => [path, metadata(path)]));
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Share pending evidence in one authority scope; a settled result is never cached.
|
|
347
|
+
* The caller owns the scope and supplies its session/execution revision and live branch reader.
|
|
348
|
+
*/
|
|
349
|
+
export function operationResumeSchedulerGate(
|
|
315
350
|
entries: Iterable<EntryLike>,
|
|
316
351
|
owner: WorkflowOwner,
|
|
317
|
-
options: { timeoutMs?: number } = {},
|
|
352
|
+
options: { timeoutMs?: number; scope?: object; revision?: string; getEntries?: () => Iterable<EntryLike> } = {},
|
|
318
353
|
): Promise<OperationResumeSchedulerGate> {
|
|
319
|
-
const
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
354
|
+
const branch = Array.from(entries);
|
|
355
|
+
const located = locateRun(branch, owner);
|
|
356
|
+
if ("missing" in located) return Promise.resolve({ ok: false, reason: `${located.problem}, so the run was not checked` });
|
|
357
|
+
const scope = options.scope ?? owner;
|
|
358
|
+
let checks = admissionChecks.get(scope);
|
|
359
|
+
if (!checks) { checks = new Map(); admissionChecks.set(scope, checks); }
|
|
360
|
+
const binding = admissionBinding(branch);
|
|
361
|
+
const key = JSON.stringify([owner, located, binding, options.timeoutMs ?? SCHEDULER_TIMEOUT_MS, options.revision]);
|
|
362
|
+
const pending = checks.get(key);
|
|
363
|
+
if (pending) return pending;
|
|
364
|
+
const check = (async (): Promise<OperationResumeSchedulerGate> => {
|
|
365
|
+
try {
|
|
366
|
+
const inputs = admissionInputs(located);
|
|
367
|
+
const isCurrent = (): boolean => {
|
|
368
|
+
try {
|
|
369
|
+
const currentBranch = Array.from(options.getEntries?.() ?? (Array.isArray(entries) ? entries : branch));
|
|
370
|
+
const current = locateRun(currentBranch, owner);
|
|
371
|
+
return !("missing" in current) && current.script === located.script && current.runDir === located.runDir
|
|
372
|
+
&& current.planPath === located.planPath
|
|
373
|
+
&& admissionBinding(currentBranch) === binding
|
|
374
|
+
&& admissionInputs(located) === inputs;
|
|
375
|
+
} catch { return false; }
|
|
376
|
+
};
|
|
377
|
+
const run = await runScheduler(located.script, located.runDir, options.timeoutMs);
|
|
378
|
+
if (!run.ok) return { ok: false, reason: `Workflow admission evidence unavailable: ${run.reason}` };
|
|
379
|
+
if (!isCurrent()) return { ok: false, reason: "Workflow admission inputs changed during the scheduler check" };
|
|
380
|
+
return { ok: true, waitUntil: waitUntil(run.due), isCurrent };
|
|
381
|
+
} catch (error) {
|
|
382
|
+
return { ok: false, reason: `Workflow admission evidence unavailable: ${String(error).slice(0, DETAIL_LIMIT)}` };
|
|
383
|
+
}
|
|
384
|
+
})().finally(() => {
|
|
385
|
+
checks.delete(key);
|
|
386
|
+
if (checks.size === 0) admissionChecks.delete(scope);
|
|
387
|
+
});
|
|
388
|
+
checks.set(key, check);
|
|
389
|
+
return check;
|
|
324
390
|
}
|
|
325
391
|
|
|
326
392
|
/** When the bound run next wants a continuation, or undefined when it is not only waiting. */
|