pi-better-goal 0.14.0 → 0.14.2
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
package/src/index.ts
CHANGED
|
@@ -318,6 +318,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
318
318
|
let currentCtx: ExtensionContext | undefined;
|
|
319
319
|
let executionGeneration = 0;
|
|
320
320
|
let operationAdmissionRevision = 0;
|
|
321
|
+
const operationAdmissionScope = {};
|
|
321
322
|
let agentGeneration = -1;
|
|
322
323
|
let turnGeneration = 0;
|
|
323
324
|
let escapeAbortSuppression: { session: number; turn: number; execution: number } | undefined;
|
|
@@ -856,7 +857,11 @@ export default function (pi: ExtensionAPI): void {
|
|
|
856
857
|
if (goal && currentContinuationState(ctx, goal.goalId)?.blocked) { held("Goal continuation requires human resume"); return; }
|
|
857
858
|
if (goal && !boundCommandReady(goal, ctx)) { held("Bound workflow is not ready"); return; }
|
|
858
859
|
const workflow = getWorkflow(ctx);
|
|
859
|
-
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) => {
|
|
860
865
|
if (ctx !== currentCtx || revision !== executionGeneration || preferencesRevision !== operationAdmissionRevision || !operationOwnerMatches(currentCtx, request.owner!)) {
|
|
861
866
|
held("Parent execution changed during resume admission"); return;
|
|
862
867
|
}
|
|
@@ -867,6 +872,9 @@ export default function (pi: ExtensionAPI): void {
|
|
|
867
872
|
held("Goal became held during resume admission"); return;
|
|
868
873
|
}
|
|
869
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
|
+
}
|
|
870
878
|
if (gate.waitUntil && gate.waitUntil > Date.now()) { held("Workflow scheduler is waiting"); return; }
|
|
871
879
|
// An in-process capability lets the dispatcher validate this admission
|
|
872
880
|
// after its last await and immediately before releasing execution.
|
|
@@ -876,6 +884,7 @@ export default function (pi: ExtensionAPI): void {
|
|
|
876
884
|
const active = getGoal(ctx);
|
|
877
885
|
if ((request.owner!.goalId ?? null) !== (active?.goalId ?? null)) return false;
|
|
878
886
|
if (JSON.stringify(getWorkflow(ctx)) !== JSON.stringify(workflow)) return false;
|
|
887
|
+
if (!gate.isCurrent()) return false;
|
|
879
888
|
return !active || (preferences.autoContinue && isPokeable(active)
|
|
880
889
|
&& !currentContinuationState(ctx, active.goalId)?.blocked && boundCommandReady(active, ctx));
|
|
881
890
|
};
|
|
@@ -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,82 @@ 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
|
+
let snapshot = false;
|
|
51
|
+
const statements = new Map();
|
|
52
|
+
return {
|
|
53
|
+
revision() {
|
|
54
|
+
const { statSync } = createRequire(import.meta.url)("node:fs");
|
|
55
|
+
const stat = statSync(path, { bigint: true });
|
|
56
|
+
const next = `${stat.dev}:${stat.ino}`;
|
|
57
|
+
if (identity !== next) {
|
|
58
|
+
if (snapshot) throw new Error("Coordinator identity changed during observation");
|
|
59
|
+
db?.close();
|
|
60
|
+
db = undefined;
|
|
61
|
+
statements.clear();
|
|
62
|
+
identity = next;
|
|
63
|
+
}
|
|
64
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
65
|
+
db ??= new DatabaseSync(path, { readOnly: true });
|
|
66
|
+
return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
|
|
67
|
+
},
|
|
68
|
+
beginSnapshot() {
|
|
69
|
+
this.revision();
|
|
70
|
+
if (snapshot) throw new Error("Coordinator snapshot already open");
|
|
71
|
+
db.exec("BEGIN");
|
|
72
|
+
snapshot = true;
|
|
73
|
+
const release = () => {
|
|
74
|
+
if (!snapshot) return;
|
|
75
|
+
try { db.exec("ROLLBACK"); } finally { snapshot = false; }
|
|
76
|
+
};
|
|
77
|
+
try {
|
|
78
|
+
// Pin the WAL read view before recording its revision; other writers keep advancing.
|
|
79
|
+
db.prepare("SELECT count(*) FROM sqlite_schema").get();
|
|
80
|
+
return { revision: this.revision(), release };
|
|
81
|
+
} catch (error) { release(); throw error; }
|
|
82
|
+
},
|
|
83
|
+
read(owner) {
|
|
84
|
+
try {
|
|
85
|
+
this.revision();
|
|
86
|
+
return readAssignmentWaits(path, owner, { prepare(sql) {
|
|
87
|
+
if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
|
|
88
|
+
return statements.get(sql);
|
|
89
|
+
} });
|
|
90
|
+
} catch {
|
|
91
|
+
return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
conversationRevisions() {
|
|
95
|
+
try {
|
|
96
|
+
this.revision();
|
|
97
|
+
if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
|
|
98
|
+
const hashes = new Map();
|
|
99
|
+
const add = (sessionId, workspace, value) => {
|
|
100
|
+
const key = JSON.stringify([sessionId, workspace]);
|
|
101
|
+
if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
|
|
102
|
+
hashes.get(key).update(JSON.stringify(value));
|
|
103
|
+
};
|
|
104
|
+
// One source pass per changed database revision, instead of one
|
|
105
|
+
// projection/query/log parse for every historical attempt.
|
|
106
|
+
for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
|
|
107
|
+
FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
|
|
108
|
+
FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
|
|
109
|
+
add(row.owner_session_id, row.owner_workspace, row);
|
|
110
|
+
}
|
|
111
|
+
for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
|
|
112
|
+
const record = JSON.parse(row.record_json);
|
|
113
|
+
add(record.owner.sessionId, record.owner.workspace, record);
|
|
114
|
+
}
|
|
115
|
+
return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
|
|
116
|
+
} catch { return undefined; }
|
|
117
|
+
},
|
|
118
|
+
close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
|
|
119
|
+
};
|
|
120
|
+
}
|
|
@@ -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/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. */
|