pi-better-subagents 0.30.0 → 0.31.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/README.md +13 -0
- package/assignment-outcomes.ts +157 -0
- package/assignment-projection.d.mts +14 -0
- package/assignment-projection.mjs +109 -0
- package/cleanup.ts +12 -0
- package/finalization.ts +2 -0
- package/health-surface.mjs +2 -0
- package/index.ts +134 -14
- package/list.mjs +7 -1
- package/navigator.mjs +23 -10
- package/outage-observations.ts +73 -0
- package/output-payload.ts +25 -6
- package/package.json +3 -1
- package/registry.ts +16 -3
- package/session-store.ts +1 -1
- package/shared-callback-batcher.ts +8 -3
- package/shared-operation-coordinator/assignment-observation.mjs +43 -0
- package/shared-operation-coordinator/index.ts +5 -0
- package/shared-operation-coordinator/src/assignment-outcomes.ts +172 -0
- package/shared-operation-coordinator/src/discovery.ts +128 -0
- package/shared-operation-coordinator/src/errors.ts +2 -0
- package/shared-operation-coordinator/src/operations.ts +88 -6
- package/shared-operation-coordinator/src/outbox.ts +11 -2
- package/shared-operation-coordinator/src/recovery.ts +55 -0
- package/shared-operation-coordinator/src/rows.ts +2 -1
- package/shared-operation-coordinator/src/schema.ts +114 -2
- package/shared-operation-coordinator/src/store.ts +83 -1
- package/shared-operation-coordinator/src/types.ts +46 -1
- package/shared-operation-coordinator/src/waits.ts +47 -5
- package/task-policy.ts +2 -0
- package/tools.ts +24 -7
- package/worker-waits.ts +245 -82
package/README.md
CHANGED
|
@@ -170,6 +170,19 @@ pi remove npm:pi-better-subagents
|
|
|
170
170
|
|
|
171
171
|
## More Detail
|
|
172
172
|
|
|
173
|
+
### Assignment Progress
|
|
174
|
+
|
|
175
|
+
Result tools, lists, navigation and Goal activity share five assignment states:
|
|
176
|
+
Running, Waiting, Completed, Failed and Cancelled. Process status is separate.
|
|
177
|
+
An exited attempt can still be Waiting, and its output remains readable.
|
|
178
|
+
Consuming a dependency wait does not by itself complete the assignment.
|
|
179
|
+
|
|
180
|
+
The projection exposes an opaque semantic `revision`, readable `reason`, attempt
|
|
181
|
+
identity, process status, termination evidence and retained evidence references.
|
|
182
|
+
Compare revisions for equality; unchanged observations keep the same revision.
|
|
183
|
+
Unavailable or unsupported coordinator reads report Waiting with an unverified
|
|
184
|
+
reason. See the [projection contract](../../docs/adr/0022-assignment-progress-projection.md).
|
|
185
|
+
|
|
173
186
|
- Repository: https://github.com/1aboveio/pi-better-harness
|
|
174
187
|
- Detailed notes: https://github.com/1aboveio/pi-better-harness/blob/main/packages/pi-better-subagents/docs/usage.md
|
|
175
188
|
- License: https://github.com/1aboveio/pi-better-harness/blob/main/LICENSE
|
|
@@ -0,0 +1,157 @@
|
|
|
1
|
+
import { homedir } from "node:os";
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { join, relative, isAbsolute } from "node:path";
|
|
4
|
+
import { openSync, closeSync, fstatSync, readSync, realpathSync, constants } from "node:fs";
|
|
5
|
+
import { openStore, type OwnerIdentity, type AssignmentOutcomeRecord } from "./shared-operation-coordinator/index.ts";
|
|
6
|
+
import type { RunMeta } from "./registry.ts";
|
|
7
|
+
import { processStartToken } from "./registry.ts";
|
|
8
|
+
import type { PermissionSnapshot } from "./permission-policy.ts";
|
|
9
|
+
import { credentialFilePaths } from "./shared-sandbox-core.ts";
|
|
10
|
+
|
|
11
|
+
export const ASSIGNMENT_OUTCOMES_VERSION = 1;
|
|
12
|
+
const closedHosts = (globalThis as typeof globalThis & { __assignmentOutcomeClosedHosts?: Set<string> }).__assignmentOutcomeClosedHosts ??= new Set<string>();
|
|
13
|
+
export function createOutcomeHost(): string {
|
|
14
|
+
return `assignment:${process.pid}:${encodeURIComponent(processStartToken(process.pid) ?? "unknown")}:${randomUUID()}`;
|
|
15
|
+
}
|
|
16
|
+
export function closeOutcomeHost(hostId: string): void {
|
|
17
|
+
closedHosts.add(hostId);
|
|
18
|
+
}
|
|
19
|
+
export function claimOutcome(meta: RunMeta, hostId: string): boolean {
|
|
20
|
+
const outcome = readOutcome(meta);
|
|
21
|
+
if (!outcome) return false;
|
|
22
|
+
return withStore((store) => {
|
|
23
|
+
const event = store.listOutbox().find((e) => e.eventId === outcome.eventId);
|
|
24
|
+
if (!event || ["delivered", "acknowledged"].includes(event.state)) return false;
|
|
25
|
+
if (event.dispatchClaim) {
|
|
26
|
+
if (event.dispatchClaim.claimedBy === hostId) return true;
|
|
27
|
+
const [prefix, pidText, token] = event.dispatchClaim.claimedBy.split(":");
|
|
28
|
+
let dead = closedHosts.has(event.dispatchClaim.claimedBy);
|
|
29
|
+
if (prefix === "assignment" && !dead) {
|
|
30
|
+
try { process.kill(Number(pidText), 0); } catch (error) { dead = (error as NodeJS.ErrnoException).code === "ESRCH"; }
|
|
31
|
+
const current = processStartToken(Number(pidText));
|
|
32
|
+
if (current && token !== "unknown" && encodeURIComponent(current) !== token) dead = true;
|
|
33
|
+
}
|
|
34
|
+
if (!dead) return false;
|
|
35
|
+
store.releaseOutbox({ eventId: event.eventId, claimToken: event.dispatchClaim.token, reason: "prior outcome delivery host exited" });
|
|
36
|
+
}
|
|
37
|
+
return store.claimOutbox({ type: "assignment-outcome", eventId: outcome.eventId, recipient: outcome.recipient, claimToken: `outcome_${randomUUID()}`, claimedBy: hostId, limit: 1 }).length === 1;
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
export interface AssignmentBinding { version: 1; assignmentId: string; owner: OwnerIdentity; recipient: OwnerIdentity }
|
|
41
|
+
export function coordinatorPath(): string {
|
|
42
|
+
return join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite");
|
|
43
|
+
}
|
|
44
|
+
function withStore<T>(body: (store: ReturnType<typeof openStore>) => T): T {
|
|
45
|
+
const store = openStore({ path: coordinatorPath() });
|
|
46
|
+
try { return body(store); } finally { store.close(); }
|
|
47
|
+
}
|
|
48
|
+
export function registerAssignmentAttempt(binding: AssignmentBinding, attemptId: string): void {
|
|
49
|
+
if (binding.version !== ASSIGNMENT_OUTCOMES_VERSION) throw new Error("Unsupported assignment outcome capability.");
|
|
50
|
+
withStore((store) => store.registerAssignment({ ...binding, attemptId }));
|
|
51
|
+
}
|
|
52
|
+
/** Called before any completion handoff, including callback:false and inactive parents. */
|
|
53
|
+
export function commitAssignmentTerminal(meta: RunMeta, recoveryFailure = false): AssignmentOutcomeRecord | null {
|
|
54
|
+
const binding = meta.assignment;
|
|
55
|
+
if (!binding) return null;
|
|
56
|
+
return withStore((store) => {
|
|
57
|
+
const existing = store.getAssignmentOutcome(binding.assignmentId);
|
|
58
|
+
if (existing) return existing;
|
|
59
|
+
if (!["failed", "completed", "killed", "lost"].includes(meta.status) || (meta.status === "completed" && meta.park)) return null;
|
|
60
|
+
const waits = store.listWaits({ owner: binding.owner }).filter((w) => w.origin?.assignmentRef === binding.assignmentId);
|
|
61
|
+
// A published automatic attempt's exit belongs to bounded recovery first.
|
|
62
|
+
if (!recoveryFailure && meta.status !== "killed" && meta.operations?.resumeLaunchToken && waits.some((w) => !w.acknowledgement && ["resuming", "ready"].includes(w.phase))) return null;
|
|
63
|
+
// A coherent attempt exit does not establish interpretation or completion.
|
|
64
|
+
if (meta.status === "completed" && waits.some((w) => !w.acknowledgement)) return null;
|
|
65
|
+
return store.recordAssignmentOutcome({ ...binding, revision: 1,
|
|
66
|
+
outcome: meta.status === "completed" ? "succeeded" : meta.status === "killed" ? "cancelled" : "failed",
|
|
67
|
+
reason: meta.failureReason || (meta.status === "completed" ? "Assigned work and required interpretation are complete." : `Assignment ended ${meta.status}; retained attempt evidence is available.`),
|
|
68
|
+
processUncertain: meta.status === "lost" || typeof meta.exitCode !== "number"
|
|
69
|
+
|| waits.some((w) => w.dependencies.some((d) => d.terminalRevision === 0)
|
|
70
|
+
|| store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0),
|
|
71
|
+
evidence: [{ kind: "log", ref: meta.logPath, summary: `Attempt ${meta.id}: ${meta.status}` }],
|
|
72
|
+
waits: waits.map((w) => ({ waitId: w.waitId, generation: w.generation, cancelEpoch: w.cancelEpoch })),
|
|
73
|
+
});
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
export function readOutcome(meta: RunMeta): AssignmentOutcomeRecord | null {
|
|
77
|
+
return meta.assignment ? withStore((store) => store.getAssignmentOutcome(meta.assignment!.assignmentId)) : null;
|
|
78
|
+
}
|
|
79
|
+
export function assignmentRetainsEvidence(meta: RunMeta): boolean {
|
|
80
|
+
if (!meta.assignment) return false;
|
|
81
|
+
return withStore((store) => {
|
|
82
|
+
const outcome = store.getAssignmentOutcome(meta.assignment!.assignmentId);
|
|
83
|
+
if (!outcome) return false;
|
|
84
|
+
if (!outcome.disposition) return true;
|
|
85
|
+
const waits = store.listWaits({ owner: outcome.owner }).filter((w) => w.origin?.assignmentRef === outcome.assignmentId);
|
|
86
|
+
return waits.some((w) => store.listResumeClaims({ waitId: w.waitId, generation: w.generation, state: "published" }).length > 0);
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
export function receiptOutcome(meta: RunMeta, entryId: string): void {
|
|
90
|
+
const record = readOutcome(meta);
|
|
91
|
+
if (record) withStore((store) => store.receiptAssignmentOutcome({ assignmentId: record.assignmentId, recipient: record.recipient, revision: record.revision, entryId }));
|
|
92
|
+
}
|
|
93
|
+
export function outcomeTranscriptReceipt(entries: readonly unknown[], eventId: string): string | null {
|
|
94
|
+
for (const raw of entries) {
|
|
95
|
+
const entry = raw as { id?: string; type?: string; customType?: string; details?: { completionEventIds?: unknown }; message?: { role?: string; customType?: string; details?: { completionEventIds?: unknown } } };
|
|
96
|
+
const message = entry.type === "custom_message" ? entry
|
|
97
|
+
: entry.type === "message" && entry.message?.role === "custom" ? entry.message : null;
|
|
98
|
+
if (message?.customType !== "background-completion-batch") continue;
|
|
99
|
+
const ids = message.details?.completionEventIds;
|
|
100
|
+
if (Array.isArray(ids) && ids.includes(eventId)) return entry.id ?? eventId;
|
|
101
|
+
}
|
|
102
|
+
return null;
|
|
103
|
+
}
|
|
104
|
+
function under(path: string, root: string): boolean {
|
|
105
|
+
const rel = relative(root, path);
|
|
106
|
+
return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
|
|
107
|
+
}
|
|
108
|
+
export function inspectOutcome(meta: RunMeta, input: { recipient: OwnerIdentity; branchIds?: readonly string[]; permissions?: PermissionSnapshot; operationId?: string; revision?: number; disposition?: "consumed" | "dismissed"; note?: string }) {
|
|
109
|
+
if (input.disposition && !Number.isInteger(input.revision)) throw new Error("Outcome disposition requires the exact outcome_revision.");
|
|
110
|
+
if (!meta.assignment) throw new Error("This run has no durable assignment outcome capability.");
|
|
111
|
+
return withStore((store) => {
|
|
112
|
+
const outcome = store.getAssignmentOutcome(meta.assignment!.assignmentId);
|
|
113
|
+
if (!outcome || outcome.recipient.sessionId !== input.recipient.sessionId || outcome.recipient.workspace !== input.recipient.workspace
|
|
114
|
+
|| (outcome.recipient.branchId && outcome.recipient.branchId !== input.recipient.branchId && !input.branchIds?.includes(outcome.recipient.branchId))) throw new Error("Outcome belongs to a different parent session or branch.");
|
|
115
|
+
const policy = input.permissions?.permissions;
|
|
116
|
+
if (meta.operations?.policy.sandbox && !policy) throw new Error("Current mandatory read authority is unavailable.");
|
|
117
|
+
const readable = (path: string): string => {
|
|
118
|
+
const real = realpathSync(path);
|
|
119
|
+
if (credentialFilePaths(homedir()).some((p) => {
|
|
120
|
+
try { return under(real, realpathSync(p)); } catch { return under(real, p); }
|
|
121
|
+
})) throw new Error("Credential evidence access is refused.");
|
|
122
|
+
const access = under(real, realpathSync(input.recipient.workspace)) ? policy?.projectFiles : policy?.outsideProject;
|
|
123
|
+
if (policy?.enabled && access !== "read" && access !== "read-write") throw new Error("Current file read permission refuses this evidence.");
|
|
124
|
+
return real;
|
|
125
|
+
};
|
|
126
|
+
const waits = store.listWaits({ owner: outcome.owner }).filter((w) => w.origin?.assignmentRef === outcome.assignmentId);
|
|
127
|
+
let logs: Array<{ ref: string; text: string }> = [];
|
|
128
|
+
if (input.operationId) {
|
|
129
|
+
if (!waits.some((w) => w.dependencies.some((d) => d.operationId === input.operationId))) throw new Error("Operation is not an assignment dependency.");
|
|
130
|
+
logs = store.listOperationEvidence(input.operationId).filter((e) => e.kind === "log").slice(0, 2).map((e) => {
|
|
131
|
+
if (!isAbsolute(e.ref)) throw new Error("Legacy dependency log has no verified absolute path; inspect its retained summary instead.");
|
|
132
|
+
const fd = openSync(readable(e.ref), constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
133
|
+
try {
|
|
134
|
+
const size = fstatSync(fd).size;
|
|
135
|
+
const bytes = Buffer.alloc(Math.min(size, 4096));
|
|
136
|
+
const count = readSync(fd, bytes, 0, bytes.length, Math.max(0, size - bytes.length));
|
|
137
|
+
return { ref: e.ref, text: bytes.subarray(0, count).toString("utf8") };
|
|
138
|
+
} finally { closeSync(fd); }
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
// Check retained references before recording an inspection, never a worker read.
|
|
142
|
+
const unavailableEvidence: string[] = [];
|
|
143
|
+
for (const pin of [...outcome.evidence, ...store.listEvidencePins({ waitId: outcome.eventId, generation: 1 })]) {
|
|
144
|
+
if ((pin.kind === "log" || pin.kind === "artifact") && isAbsolute(pin.ref)) {
|
|
145
|
+
try { readable(pin.ref); } catch (error) {
|
|
146
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
147
|
+
unavailableEvidence.push(pin.ref);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const request = { assignmentId: outcome.assignmentId, recipient: outcome.recipient, revision: input.revision ?? outcome.revision };
|
|
152
|
+
const record = input.disposition
|
|
153
|
+
? store.consumeAssignmentOutcome({ ...request, disposition: input.disposition, note: input.note ?? "" })
|
|
154
|
+
: store.inspectAssignmentOutcome(request);
|
|
155
|
+
return { outcome: record, unavailableEvidence, dependencies: waits.slice(0, 20).map((w) => ({ waitId: w.waitId, generation: w.generation, phase: w.phase, acknowledgement: w.acknowledgement, dependencies: w.dependencies.slice(0, 20) })), logs };
|
|
156
|
+
});
|
|
157
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export interface AssignmentProjection {
|
|
2
|
+
state: "running" | "waiting" | "completed" | "failed" | "cancelled";
|
|
3
|
+
revision: string;
|
|
4
|
+
reason: string;
|
|
5
|
+
processStatus: string;
|
|
6
|
+
termination: string;
|
|
7
|
+
attemptId: string;
|
|
8
|
+
evidence: string[];
|
|
9
|
+
verified: boolean;
|
|
10
|
+
}
|
|
11
|
+
export function assignmentFor(meta: object, processStatus?: string, options?: { baseDir?: string | undefined; coordinatorPath?: string; observation?: object }): AssignmentProjection;
|
|
12
|
+
export function projectAssignment(meta: object, processStatus: string, observation?: object): AssignmentProjection;
|
|
13
|
+
export function assignmentDiagnostic(assignment: AssignmentProjection): string;
|
|
14
|
+
export const ASSIGNMENT_STATES: string[];
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { readFileSync, readdirSync } from "node:fs";
|
|
3
|
+
import { homedir, tmpdir } from "node:os";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { readAssignmentWaits } from "./shared-operation-coordinator/assignment-observation.mjs";
|
|
6
|
+
|
|
7
|
+
export const ASSIGNMENT_STATES = ["running", "waiting", "completed", "failed", "cancelled"];
|
|
8
|
+
|
|
9
|
+
/** A projection revision is a content-addressed semantic token, not a clock. */
|
|
10
|
+
export function projectAssignment(meta, processStatus, observation = { verified: true, waits: [] }) {
|
|
11
|
+
const waits = observation.waits;
|
|
12
|
+
const pending = waits.find((wait) => !["consumed", "cancelled"].includes(wait.phase));
|
|
13
|
+
let state;
|
|
14
|
+
let reason;
|
|
15
|
+
if (observation.outcome) {
|
|
16
|
+
state = { succeeded: "completed", failed: "failed", cancelled: "cancelled" }[observation.outcome.outcome];
|
|
17
|
+
reason = observation.outcome.reason;
|
|
18
|
+
} else if (waits[0]?.phase === "cancelled") {
|
|
19
|
+
state = "cancelled";
|
|
20
|
+
reason = waits[0]?.reason || "Assignment explicitly cancelled.";
|
|
21
|
+
} else if (!observation.verified && (meta.operations || meta.park)) {
|
|
22
|
+
state = "waiting";
|
|
23
|
+
reason = observation.reason;
|
|
24
|
+
} else if (pending) {
|
|
25
|
+
state = "waiting";
|
|
26
|
+
reason = pending.reason || (pending.phase === "ready" || pending.phase === "resuming"
|
|
27
|
+
? "Dependency evidence awaits worker interpretation."
|
|
28
|
+
: "Waiting for dependencies and supervised continuation.");
|
|
29
|
+
} else if (meta.status === "killed") {
|
|
30
|
+
state = "cancelled";
|
|
31
|
+
reason = "Assignment explicitly cancelled.";
|
|
32
|
+
} else if (processStatus === "running") {
|
|
33
|
+
state = "running";
|
|
34
|
+
reason = "Worker is advancing the assignment.";
|
|
35
|
+
} else if (meta.status === "failed") {
|
|
36
|
+
state = "failed";
|
|
37
|
+
reason = meta.failureReason || "Worker execution failed; retained evidence is available.";
|
|
38
|
+
} else if (meta.status === "completed" && !String(meta.lifecycleClassification ?? "").startsWith("incomplete") && (!meta.park || waits.some((wait) =>
|
|
39
|
+
wait.acknowledgement?.disposition === "assignment-complete"))) {
|
|
40
|
+
state = "completed";
|
|
41
|
+
reason = "Assigned work and required interpretation are complete.";
|
|
42
|
+
} else {
|
|
43
|
+
state = "waiting";
|
|
44
|
+
reason = meta.park && waits.some((wait) => wait.phase === "consumed")
|
|
45
|
+
? "Dependency interpretation recorded; assignment completion is not yet proven."
|
|
46
|
+
: "Execution outcome is unverified; supervised reconciliation is required.";
|
|
47
|
+
}
|
|
48
|
+
reason = String(reason ?? "Assignment state is unverified.").slice(0, 512);
|
|
49
|
+
const evidence = waits.slice(0, 8).map((wait) => `wait:${wait.waitId}:${wait.generation}`);
|
|
50
|
+
evidence.push(`run:${meta.id}:output.log`, `run:${meta.id}:meta.json`);
|
|
51
|
+
const revision = createHash("sha256").update(JSON.stringify([meta.rootRunId ?? meta.id, meta.id, state, reason, evidence])).digest("hex").slice(0, 16);
|
|
52
|
+
return { state, reason, revision, attemptId: meta.id, processStatus,
|
|
53
|
+
termination: !["running", "orphaned", "lost", "exited"].includes(processStatus)
|
|
54
|
+
&& (typeof meta.exitCode === "number" || meta.signal) ? "attempt exit recorded" : "unproven",
|
|
55
|
+
evidence, verified: observation.verified };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** All consumers use the same lineage and authoritative wait read. Park caches are hints only. */
|
|
59
|
+
export function assignmentFor(meta, processStatus = meta.status, options = {}) {
|
|
60
|
+
const base = options.baseDir ?? join(tmpdir(), "pi-better-subagents");
|
|
61
|
+
const attempts = new Map([[meta.id, meta]]);
|
|
62
|
+
let current = meta;
|
|
63
|
+
try {
|
|
64
|
+
for (const id of (meta.operations || meta.park ? readdirSync(join(base, "runs")) : [])) {
|
|
65
|
+
try {
|
|
66
|
+
const candidate = JSON.parse(readFileSync(join(base, "runs", id, "meta.json"), "utf8"));
|
|
67
|
+
if (candidate.sessionId === meta.sessionId && candidate.cwd === meta.cwd
|
|
68
|
+
&& (!meta.assignment || candidate.assignment?.assignmentId === meta.assignment.assignmentId)) attempts.set(candidate.id, candidate);
|
|
69
|
+
} catch { /* A partial unrelated record must not hide a continuation. */ }
|
|
70
|
+
}
|
|
71
|
+
} catch { /* Registry gaps cannot establish a newer attempt. */ }
|
|
72
|
+
// Conversation roots survive explicit follow-ups. Only automatic resume edges
|
|
73
|
+
// join attempts into one assignment; manual continuation starts a new one.
|
|
74
|
+
const lineage = new Map([[meta.id, meta]]);
|
|
75
|
+
let ancestor = meta;
|
|
76
|
+
while (ancestor.operations?.resumeLaunchToken && attempts.has(ancestor.resumedFrom) && !lineage.has(ancestor.resumedFrom)) {
|
|
77
|
+
ancestor = attempts.get(ancestor.resumedFrom);
|
|
78
|
+
lineage.set(ancestor.id, ancestor);
|
|
79
|
+
}
|
|
80
|
+
let added;
|
|
81
|
+
do {
|
|
82
|
+
added = false;
|
|
83
|
+
for (const candidate of attempts.values()) {
|
|
84
|
+
if (candidate.operations?.resumeLaunchToken && lineage.has(candidate.resumedFrom) && !lineage.has(candidate.id)) {
|
|
85
|
+
lineage.set(candidate.id, candidate);
|
|
86
|
+
added = true;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
} while (added);
|
|
90
|
+
for (const candidate of lineage.values()) {
|
|
91
|
+
if (candidate.startedAt > current.startedAt) current = candidate;
|
|
92
|
+
}
|
|
93
|
+
const status = current.id === meta.id ? processStatus : current.status;
|
|
94
|
+
const sessionId = current.operations?.conversationId ?? current.sessionId;
|
|
95
|
+
const observation = options.observation ?? (sessionId && (current.assignment || current.operations || current.park)
|
|
96
|
+
? readAssignmentWaits(options.coordinatorPath ?? join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "operation-coordinator.sqlite"),
|
|
97
|
+
{ sessionId, workspace: current.operations?.workspace ?? current.cwd,
|
|
98
|
+
...(current.assignment ? { assignmentId: current.assignment.assignmentId } : {}),
|
|
99
|
+
attemptIds: [...lineage.keys()], waitRefs: [...lineage.values()].flatMap((attempt) =>
|
|
100
|
+
attempt.park?.waitId && Number.isSafeInteger(attempt.park.generation)
|
|
101
|
+
? [{ waitId: attempt.park.waitId, generation: attempt.park.generation }] : []) })
|
|
102
|
+
: current.park ? { verified: false, waits: [], reason: "Coordinator identity is unavailable; assignment state is unverified." }
|
|
103
|
+
: { verified: true, waits: [] });
|
|
104
|
+
return projectAssignment(current, status, observation);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function assignmentDiagnostic(assignment) {
|
|
108
|
+
return `Assignment ${assignment.state} r${assignment.revision}: ${assignment.reason} Process ${assignment.processStatus}; termination ${assignment.termination}. Evidence: ${assignment.evidence.join(", ")}`;
|
|
109
|
+
}
|
package/cleanup.ts
CHANGED
|
@@ -40,6 +40,11 @@ import {
|
|
|
40
40
|
} from "./continuation.ts";
|
|
41
41
|
import { processExists } from "./spawn.ts";
|
|
42
42
|
import { archiveCompletedAttempt, archivePublicationPending, listArchivedAttempts } from "./session-store.ts";
|
|
43
|
+
import { assignmentRetainsEvidence } from "./assignment-outcomes.ts";
|
|
44
|
+
|
|
45
|
+
function outcomeProtected(meta: RunMeta): boolean {
|
|
46
|
+
try { return assignmentRetainsEvidence(meta); } catch { return true; }
|
|
47
|
+
}
|
|
43
48
|
|
|
44
49
|
export const DEFAULT_CLEANUP_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
|
|
45
50
|
|
|
@@ -327,6 +332,11 @@ function planCleanupOccupancy(
|
|
|
327
332
|
): CleanupOccupancy {
|
|
328
333
|
const runIds = new Set<string>(protect?.runIds ?? []);
|
|
329
334
|
const paths = [...(protect?.paths ?? [])];
|
|
335
|
+
for (const meta of metas) {
|
|
336
|
+
if (outcomeProtected(meta)) {
|
|
337
|
+
runIds.add(meta.id);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
330
340
|
|
|
331
341
|
// A protected path may be the shared workspace or something inside it. The
|
|
332
342
|
// run whose removal would delete it is protected instead, because
|
|
@@ -569,6 +579,7 @@ function ageSweepEligible(
|
|
|
569
579
|
scope: CleanupScope,
|
|
570
580
|
): boolean {
|
|
571
581
|
if (!TERMINAL_CLEANUP_STATUSES.has(meta.status)) return false;
|
|
582
|
+
if (outcomeProtected(meta)) return false;
|
|
572
583
|
if (retained.has(meta.sessionId)) return false;
|
|
573
584
|
// The run directory still holds the only copy of this conversation's recipe.
|
|
574
585
|
if (scope.archivePending.has(meta.id)) return false;
|
|
@@ -986,6 +997,7 @@ function removeSizeCappedRun(
|
|
|
986
997
|
if (!conversationQuiescentUnderLock(meta.sessionId, runIds)) return "retained";
|
|
987
998
|
const fresh = readMeta(id) ?? meta;
|
|
988
999
|
if (!TERMINAL_CLEANUP_STATUSES.has(fresh.status)) return "retained";
|
|
1000
|
+
if (outcomeProtected(fresh)) return "retained";
|
|
989
1001
|
if (scope.occupancy.runIds.has(fresh.id)) return "retained";
|
|
990
1002
|
if (removeMetaArtifacts(fresh, { keepWorkspace: scope.persistent.has(fresh.sessionId) })) return "removed";
|
|
991
1003
|
errors.push(`${runDir(id)}: could not remove run artifacts`);
|
package/finalization.ts
CHANGED
|
@@ -8,6 +8,7 @@
|
|
|
8
8
|
import { buildCompletionDelivery } from "./completion.ts";
|
|
9
9
|
import { collectRunFailures, failurePath } from "./failures.ts";
|
|
10
10
|
import { observeFailures } from "./shared-failure-observations.ts";
|
|
11
|
+
import { commitAssignmentTerminal } from "./assignment-outcomes.ts";
|
|
11
12
|
import {
|
|
12
13
|
classifyChildExit,
|
|
13
14
|
type ChildExitOutcome,
|
|
@@ -114,6 +115,7 @@ export function finalizeRun(
|
|
|
114
115
|
}
|
|
115
116
|
}
|
|
116
117
|
writeMeta(meta);
|
|
118
|
+
commitAssignmentTerminal(meta);
|
|
117
119
|
if (!parked && park.record) {
|
|
118
120
|
// A park disposition existed but could not be proven on exit. Hold it in
|
|
119
121
|
// both durable copies (park.json + metadata) so nothing resumes it; the
|