pi-better-goal 0.14.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.14.0",
3
+ "version": "0.14.1",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
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) : Promise.resolve({ ok: true as const, waitUntil: undefined })).then((gate) => {
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,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
- for (let attempt = 0; attempt < 10; attempt++) {
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 === 9) throw error;
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
  }
@@ -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
- /** Automatic worker admission cannot treat unavailable workflow evidence as permission. */
314
- export async function operationResumeSchedulerGate(
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 located = locateRun(entries, owner);
320
- if ("missing" in located) return { ok: false, reason: `${located.problem}, so the run was not checked` };
321
- const run = await runScheduler(located.script, located.runDir, options.timeoutMs);
322
- if (!run.ok) return { ok: false, reason: `Workflow admission evidence unavailable: ${run.reason}` };
323
- return { ok: true, waitUntil: waitUntil(run.due) };
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. */