pi-better-goal 0.12.3 → 0.13.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/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,15 @@
|
|
|
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 projectAssignment(meta: object, processStatus: string, observation?: object): AssignmentProjection;
|
|
14
|
+
export function assignmentDiagnostic(assignment: AssignmentProjection): string;
|
|
15
|
+
export const ASSIGNMENT_STATES: string[];
|
|
@@ -0,0 +1,110 @@
|
|
|
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
|
+
const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
|
|
62
|
+
const attempts = new Map([[meta.id, meta]]);
|
|
63
|
+
let current = meta;
|
|
64
|
+
try {
|
|
65
|
+
for (const id of (meta.operations || meta.park ? readdirSync(join(base, "runs")) : [])) {
|
|
66
|
+
try {
|
|
67
|
+
const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
|
|
68
|
+
if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
|
|
69
|
+
&& (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
|
|
70
|
+
} catch { /* A partial unrelated record must not hide a continuation. */ }
|
|
71
|
+
}
|
|
72
|
+
} catch { /* Registry gaps cannot establish a newer attempt. */ }
|
|
73
|
+
// Conversation roots survive explicit follow-ups. Only automatic resume edges
|
|
74
|
+
// join attempts into one assignment; manual continuation starts a new one.
|
|
75
|
+
const lineage = new Map([[meta.id, meta]]);
|
|
76
|
+
let ancestor = meta;
|
|
77
|
+
while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
|
|
78
|
+
ancestor = attempts.get(ancestor.resumedFrom);
|
|
79
|
+
lineage.set(ancestor.id, ancestor);
|
|
80
|
+
}
|
|
81
|
+
let added;
|
|
82
|
+
do {
|
|
83
|
+
added = false;
|
|
84
|
+
for (const candidate of attempts.values()) {
|
|
85
|
+
if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
|
|
86
|
+
lineage.set(candidate.id, candidate);
|
|
87
|
+
added = true;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
} while (added);
|
|
91
|
+
for (const candidate of lineage.values()) {
|
|
92
|
+
if (candidate.startedAt > current.startedAt) current = candidate;
|
|
93
|
+
}
|
|
94
|
+
const status = current.id === meta.id ? processStatus : current.status;
|
|
95
|
+
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
96
|
+
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
97
|
+
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
98
|
+
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
99
|
+
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
100
|
+
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
101
|
+
attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
|
|
102
|
+
? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
|
|
103
|
+
: current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
|
|
104
|
+
: { verified: true, waits: [] });
|
|
105
|
+
return projectAssignment(current, status, observation);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
export function assignmentDiagnostic(assignment) {
|
|
109
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
110
|
+
}
|
package/src/subagents.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { assignmentFor } 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,24 @@ function ensureParentIndex(baseDir: string, directory: string, parentPid: number
|
|
|
125
126
|
export function subagentStatusToItem(
|
|
126
127
|
meta: SubagentRunMeta,
|
|
127
128
|
status: SubagentEffectiveStatus,
|
|
129
|
+
baseDir?: string,
|
|
128
130
|
): BackgroundWorkItem {
|
|
129
|
-
const
|
|
131
|
+
const assignment = assignmentFor(meta, status, { baseDir });
|
|
132
|
+
const active = assignment.state === "running" || assignment.state === "waiting";
|
|
130
133
|
const unhealthy = status === "orphaned";
|
|
131
134
|
const terminal = !active;
|
|
132
135
|
const attention = status === "orphaned" || status === "failed" || status === "killed" || status === "lost" || status === "exited";
|
|
133
136
|
|
|
134
137
|
const item: BackgroundWorkItem = {
|
|
135
138
|
id: meta.id,
|
|
136
|
-
status,
|
|
139
|
+
status: assignment.state,
|
|
137
140
|
active,
|
|
138
141
|
unhealthy,
|
|
139
142
|
terminal,
|
|
140
143
|
attention,
|
|
141
144
|
startedAt: meta.startedAt,
|
|
142
145
|
details: {
|
|
146
|
+
assignment,
|
|
143
147
|
callback: meta.callback !== false,
|
|
144
148
|
batchId: meta.batchId,
|
|
145
149
|
batchName: meta.batchName,
|
|
@@ -167,6 +171,6 @@ export function collectSubagentActivity(
|
|
|
167
171
|
return {
|
|
168
172
|
providerId: "subagents",
|
|
169
173
|
label: "Subagents",
|
|
170
|
-
items: metas.map((meta) => subagentStatusToItem(meta, effectiveSubagentStatus(meta, processExists))),
|
|
174
|
+
items: metas.map((meta) => subagentStatusToItem(meta, effectiveSubagentStatus(meta, processExists), options.baseDir)),
|
|
171
175
|
};
|
|
172
176
|
}
|