pi-better-goal 0.12.3 → 0.13.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/package.json
CHANGED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
|
|
4
|
+
/** Read-only, bounded projection input. Never creates/migrates a database. */
|
|
5
|
+
export function readAssignmentWaits(path, owner) {
|
|
6
|
+
let db;
|
|
7
|
+
try {
|
|
8
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
9
|
+
db = new DatabaseSync(path, { readOnly: true });
|
|
10
|
+
// v4 adds repair accounting; the observed wait/outcome fields are unchanged.
|
|
11
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
|
|
12
|
+
return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
|
|
13
|
+
}
|
|
14
|
+
const rows = db.prepare(`SELECT wait_id, generation, phase, phase_reason,
|
|
15
|
+
acknowledgement_json, cancel_epoch FROM waits
|
|
16
|
+
WHERE owner_kind = 'worker-conversation' AND owner_session_id = ? AND owner_workspace = ?
|
|
17
|
+
${owner.assignmentId ? "AND json_extract(origin_json, '$.assignmentRef') = ?" : `AND (
|
|
18
|
+
EXISTS (SELECT 1 FROM json_each(?) AS attempt
|
|
19
|
+
WHERE attempt.value = json_extract(waits.origin_json, '$.attemptId')
|
|
20
|
+
OR attempt.value = json_extract(waits.park_json, '$.attemptId'))
|
|
21
|
+
OR EXISTS (SELECT 1 FROM resume_claims AS claim, json_each(?) AS attempt
|
|
22
|
+
WHERE claim.wait_id = waits.wait_id AND claim.generation = waits.generation
|
|
23
|
+
AND claim.attempt_id = attempt.value)
|
|
24
|
+
OR EXISTS (SELECT 1 FROM json_each(?) AS ref
|
|
25
|
+
WHERE json_extract(ref.value, '$.waitId') = waits.wait_id
|
|
26
|
+
AND json_extract(ref.value, '$.generation') = waits.generation)
|
|
27
|
+
)`}
|
|
28
|
+
ORDER BY created_at DESC, generation DESC LIMIT 100`).all(owner.sessionId, owner.workspace,
|
|
29
|
+
...(owner.assignmentId ? [owner.assignmentId] : [JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.attemptIds ?? []), JSON.stringify(owner.waitRefs ?? [])]));
|
|
30
|
+
const record = owner.assignmentId ? db.prepare("SELECT record_json FROM assignment_outcomes WHERE assignment_id = ?").get(owner.assignmentId) : null;
|
|
31
|
+
const outcome = record ? JSON.parse(record.record_json) : null;
|
|
32
|
+
if (outcome && (outcome.owner.sessionId !== owner.sessionId || outcome.owner.workspace !== owner.workspace)) throw new Error("Foreign assignment outcome");
|
|
33
|
+
return { verified: true, outcome, waits: rows.map((row) => ({
|
|
34
|
+
waitId: row.wait_id, generation: row.generation, phase: row.phase,
|
|
35
|
+
reason: row.phase_reason, cancelEpoch: row.cancel_epoch,
|
|
36
|
+
acknowledgement: row.acknowledgement_json ? JSON.parse(row.acknowledgement_json) : null,
|
|
37
|
+
})) };
|
|
38
|
+
} catch {
|
|
39
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
40
|
+
} finally {
|
|
41
|
+
db?.close();
|
|
42
|
+
}
|
|
43
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/assignment-projection.d.mts. Do not edit directly.
|
|
2
|
+
export interface AssignmentProjection {
|
|
3
|
+
state: "running" | "waiting" | "completed" | "failed" | "cancelled";
|
|
4
|
+
revision: string;
|
|
5
|
+
reason: string;
|
|
6
|
+
processStatus: string;
|
|
7
|
+
termination: string;
|
|
8
|
+
attemptId: string;
|
|
9
|
+
evidence: string[];
|
|
10
|
+
verified: boolean;
|
|
11
|
+
}
|
|
12
|
+
export function assignmentFor(meta: object, processStatus?: string, options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): AssignmentProjection;
|
|
13
|
+
export function createAssignmentProjector(options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): (meta: object, processStatus?: string) => AssignmentProjection;
|
|
14
|
+
export function projectAssignment(meta: object, processStatus: string, observation?: object): AssignmentProjection;
|
|
15
|
+
export function assignmentDiagnostic(assignment: AssignmentProjection): string;
|
|
16
|
+
export const ASSIGNMENT_STATES: string[];
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
// Generated from packages/pi-better-subagents/assignment-projection.mjs. Do not edit directly.
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
4
|
+
import { homedir, tmpdir } from "node:os";
|
|
5
|
+
import { join } from "node:path";
|
|
6
|
+
import { readAssignmentWaits } from "./shared-assignment-observation.mjs";
|
|
7
|
+
|
|
8
|
+
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
9
|
+
|
|
10
|
+
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
11
|
+
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
12
|
+
const waits = observation.waits;
|
|
13
|
+
const pending = waits.find((wait) => !["consumed", "cancelled"].includes(wait.phase));
|
|
14
|
+
let state;
|
|
15
|
+
let reason;
|
|
16
|
+
if (observation.outcome) {
|
|
17
|
+
state = { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[observation.outcome.outcome];
|
|
18
|
+
reason = observation.outcome.reason;
|
|
19
|
+
} else if (waits[0]?.phase === "cancelled") {
|
|
20
|
+
state = "cancelled";
|
|
21
|
+
reason = waits[0]?.reason || "Assignment explicitly cancelled.";
|
|
22
|
+
} else if (!observation.verified && (meta.operations || meta.park)) {
|
|
23
|
+
state = "waiting";
|
|
24
|
+
reason = observation.reason;
|
|
25
|
+
} else if (pending) {
|
|
26
|
+
state = "waiting";
|
|
27
|
+
reason = pending.reason || (pending.phase === "ready" || pending.phase === "resuming"
|
|
28
|
+
? "Dependency evidence awaits worker interpretation."
|
|
29
|
+
: "Waiting for dependencies and supervised continuation.");
|
|
30
|
+
} else if (meta.status === "killed") {
|
|
31
|
+
state = "cancelled";
|
|
32
|
+
reason = "Assignment explicitly cancelled.";
|
|
33
|
+
} else if (processStatus === "running") {
|
|
34
|
+
state = "running";
|
|
35
|
+
reason = "Worker is advancing the assignment.";
|
|
36
|
+
} else if (meta.status === "failed") {
|
|
37
|
+
state = "failed";
|
|
38
|
+
reason = meta.failureReason || "Worker execution failed; retained evidence is available.";
|
|
39
|
+
} else if (meta.status === "completed" && !String(meta.lifecycleClassification ?? "").startsWith("incomplete") && (!meta.park || waits.some((wait) =>
|
|
40
|
+
wait.acknowledgement?.disposition === "assignment-complete"))) {
|
|
41
|
+
state = "completed";
|
|
42
|
+
reason = "Assigned work and required interpretation are complete.";
|
|
43
|
+
} else {
|
|
44
|
+
state = "waiting";
|
|
45
|
+
reason = meta.park && waits.some((wait) => wait.phase === "consumed")
|
|
46
|
+
? "Dependency interpretation recorded; assignment completion is not yet proven."
|
|
47
|
+
: "Execution outcome is unverified; supervised reconciliation is required.";
|
|
48
|
+
}
|
|
49
|
+
reason = String(reason ?? "Assignment state is unverified.").slice(0, 512);
|
|
50
|
+
const evidence = waits.slice(0, 8).map((wait) => `wait:${wait.waitId}:${wait.generation}`);
|
|
51
|
+
evidence.push(`run:${meta.id}:output.log`, `run:${meta.id}:meta.json`);
|
|
52
|
+
const revision = createHash("sha256").update(JSON.stringify([meta.rootRunId ?? meta.id, meta.id, state, reason, evidence])).digest("hex").slice(0, 16);
|
|
53
|
+
return { state, reason, revision, attemptId: meta.id, processStatus,
|
|
54
|
+
termination: !["running", "orphaned", "lost", "exited"].includes(processStatus)
|
|
55
|
+
&& (typeof meta.exitCode === "number" || meta.signal) ? "attempt exit recorded" : "unproven",
|
|
56
|
+
evidence, verified: observation.verified };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
|
|
60
|
+
export function assignmentFor(meta, processStatus = meta.status, options = {}) {
|
|
61
|
+
return assignmentFromSnapshot(meta, processStatus, options, () => readAttempts(options));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readAttempts(options) {
|
|
65
|
+
const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
|
|
66
|
+
const attempts = [];
|
|
67
|
+
try {
|
|
68
|
+
for (const id of readdirSync(join(base, "runs"))) {
|
|
69
|
+
try {
|
|
70
|
+
const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
|
|
71
|
+
if (candidate && typeof candidate === "object") attempts.push(candidate);
|
|
72
|
+
}
|
|
73
|
+
catch { /* A partial unrelated record must not hide a continuation. */ }
|
|
74
|
+
}
|
|
75
|
+
} catch { /* Registry gaps cannot establish a newer attempt. */ }
|
|
76
|
+
return attempts;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** One synchronous UI refresh shares a snapshot; the next refresh reads disk again. */
|
|
80
|
+
export function createAssignmentProjector(options = {}) {
|
|
81
|
+
let snapshot;
|
|
82
|
+
const readSnapshot = (meta) => {
|
|
83
|
+
if (!snapshot) {
|
|
84
|
+
snapshot = new Map();
|
|
85
|
+
for (const candidate of readAttempts(options)) {
|
|
86
|
+
let workspaces = snapshot.get(candidate.sessionId);
|
|
87
|
+
if (!workspaces) snapshot.set(candidate.sessionId, workspaces = new Map());
|
|
88
|
+
let attempts = workspaces.get(candidate.cwd);
|
|
89
|
+
if (!attempts) workspaces.set(candidate.cwd, attempts = []);
|
|
90
|
+
attempts.push(candidate);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return snapshot.get(meta.sessionId)?.get(meta.cwd) ?? [];
|
|
94
|
+
};
|
|
95
|
+
return (meta, processStatus = meta.status) => assignmentFromSnapshot(meta, processStatus, options,
|
|
96
|
+
() => readSnapshot(meta));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function assignmentFromSnapshot(meta, processStatus, options, readSnapshot) {
|
|
100
|
+
const attempts = new Map([[meta.id, meta]]);
|
|
101
|
+
let current = meta;
|
|
102
|
+
if (meta.operations || meta.park) {
|
|
103
|
+
for (const candidate of readSnapshot()) {
|
|
104
|
+
if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
|
|
105
|
+
&& (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// Conversation roots survive explicit follow-ups. Only automatic resume edges
|
|
109
|
+
// join attempts into one assignment; manual continuation starts a new one.
|
|
110
|
+
const lineage = new Map([[meta.id, meta]]);
|
|
111
|
+
let ancestor = meta;
|
|
112
|
+
while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
|
|
113
|
+
ancestor = attempts.get(ancestor.resumedFrom);
|
|
114
|
+
lineage.set(ancestor.id, ancestor);
|
|
115
|
+
}
|
|
116
|
+
let added;
|
|
117
|
+
do {
|
|
118
|
+
added = false;
|
|
119
|
+
for (const candidate of attempts.values()) {
|
|
120
|
+
if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
|
|
121
|
+
lineage.set(candidate.id, candidate);
|
|
122
|
+
added = true;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} while (added);
|
|
126
|
+
for (const candidate of lineage.values()) {
|
|
127
|
+
if (candidate.startedAt > current.startedAt) current = candidate;
|
|
128
|
+
}
|
|
129
|
+
const status = current.id === meta.id ? processStatus : current.status;
|
|
130
|
+
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
131
|
+
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
132
|
+
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
133
|
+
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
134
|
+
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
135
|
+
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
136
|
+
attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
|
|
137
|
+
? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
|
|
138
|
+
: current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
|
|
139
|
+
: { verified: true, waits: [] });
|
|
140
|
+
return projectAssignment(current, status, observation);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function assignmentDiagnostic(assignment) {
|
|
144
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
145
|
+
}
|
package/src/subagents.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createAssignmentProjector } from "./shared-assignment-projection.mjs";
|
|
1
2
|
import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
3
|
import { tmpdir } from "node:os";
|
|
3
4
|
import { join } from "node:path";
|
|
@@ -125,21 +126,25 @@ function ensureParentIndex(baseDir: string, directory: string, parentPid: number
|
|
|
125
126
|
export function subagentStatusToItem(
|
|
126
127
|
meta: SubagentRunMeta,
|
|
127
128
|
status: SubagentEffectiveStatus,
|
|
129
|
+
baseDir?: string,
|
|
130
|
+
project = createAssignmentProjector({ baseDir }),
|
|
128
131
|
): BackgroundWorkItem {
|
|
129
|
-
const
|
|
132
|
+
const assignment = project(meta, status);
|
|
133
|
+
const active = assignment.state === "running" || assignment.state === "waiting";
|
|
130
134
|
const unhealthy = status === "orphaned";
|
|
131
135
|
const terminal = !active;
|
|
132
136
|
const attention = status === "orphaned" || status === "failed" || status === "killed" || status === "lost" || status === "exited";
|
|
133
137
|
|
|
134
138
|
const item: BackgroundWorkItem = {
|
|
135
139
|
id: meta.id,
|
|
136
|
-
status,
|
|
140
|
+
status: assignment.state,
|
|
137
141
|
active,
|
|
138
142
|
unhealthy,
|
|
139
143
|
terminal,
|
|
140
144
|
attention,
|
|
141
145
|
startedAt: meta.startedAt,
|
|
142
146
|
details: {
|
|
147
|
+
assignment,
|
|
143
148
|
callback: meta.callback !== false,
|
|
144
149
|
batchId: meta.batchId,
|
|
145
150
|
batchName: meta.batchName,
|
|
@@ -163,10 +168,11 @@ export function collectSubagentActivity(
|
|
|
163
168
|
const parentPid = options.parentPid ?? process.pid;
|
|
164
169
|
const processExists = options.processExists ?? defaultProcessExists;
|
|
165
170
|
const metas = readParentSubagentMetas(options.baseDir, parentPid);
|
|
171
|
+
const project = createAssignmentProjector({ baseDir: options.baseDir });
|
|
166
172
|
|
|
167
173
|
return {
|
|
168
174
|
providerId: "subagents",
|
|
169
175
|
label: "Subagents",
|
|
170
|
-
items: metas.map((meta) => subagentStatusToItem(meta, effectiveSubagentStatus(meta, processExists))),
|
|
176
|
+
items: metas.map((meta) => subagentStatusToItem(meta, effectiveSubagentStatus(meta, processExists), options.baseDir, project)),
|
|
171
177
|
};
|
|
172
|
-
}
|
|
178
|
+
}
|