pi-better-harness 0.59.0 → 0.59.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.
Files changed (54) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +8 -0
  3. package/extensions/minimal-output/hook.ts +2 -2
  4. package/extensions/native-compaction/index.ts +123 -0
  5. package/extensions/native-compaction/provider.ts +90 -0
  6. package/extensions/provider-context.ts +6 -0
  7. package/extensions/settings/index.ts +3 -1
  8. package/extensions/settings/page.ts +1 -1
  9. package/extensions/supervisor/index.ts +4 -2
  10. package/extensions/task-context/dynamic-workflow-runtime.ts +14 -6
  11. package/extensions/task-context/index.ts +33 -13
  12. package/extensions/task-context/work-ledger-actions.ts +5 -3
  13. package/extensions/task-context/work-ledger.ts +1 -1
  14. package/lib/openai-responses.mjs +5 -0
  15. package/node_modules/pi-better-background-tasks/package.json +1 -1
  16. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.gz +0 -0
  17. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-arm64.json +1 -1
  18. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.gz +0 -0
  19. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/darwin-x64.json +1 -1
  20. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.gz +0 -0
  21. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-arm64.json +1 -1
  22. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.gz +0 -0
  23. package/node_modules/pi-better-background-tasks/runtime-client/artifacts/linux-x64.json +1 -1
  24. package/node_modules/pi-better-background-tasks/runtime-client/src/runtime/work-client.mjs +43 -14
  25. package/node_modules/pi-better-background-tasks/src/observed-waits.ts +3 -2
  26. package/node_modules/pi-better-background-tasks/src/registry.ts +65 -5
  27. package/node_modules/pi-better-background-tasks/src/shared-navigator.ts +2 -2
  28. package/node_modules/pi-better-background-tasks/src/shared-work-client.mjs +43 -14
  29. package/node_modules/pi-better-goal/package.json +1 -1
  30. package/node_modules/pi-better-goal/src/goal-state.ts +4 -0
  31. package/node_modules/pi-better-goal/src/index.ts +35 -29
  32. package/node_modules/pi-better-goal/src/task-context.ts +1 -0
  33. package/node_modules/pi-better-goal/src/types.ts +2 -0
  34. package/node_modules/pi-better-goal/src/workflow-gates.ts +31 -10
  35. package/node_modules/pi-better-goal/src/workflow.ts +18 -5
  36. package/node_modules/pi-better-subagents/child-incidents.ts +1 -1
  37. package/node_modules/pi-better-subagents/cleanup.ts +1 -1
  38. package/node_modules/pi-better-subagents/managed-launch-client.ts +14 -16
  39. package/node_modules/pi-better-subagents/package.json +3 -1
  40. package/node_modules/pi-better-subagents/registry.ts +6 -3
  41. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.gz +0 -0
  42. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-arm64.json +1 -1
  43. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.gz +0 -0
  44. package/node_modules/pi-better-subagents/runtime-client/artifacts/darwin-x64.json +1 -1
  45. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.gz +0 -0
  46. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-arm64.json +1 -1
  47. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.gz +0 -0
  48. package/node_modules/pi-better-subagents/runtime-client/artifacts/linux-x64.json +1 -1
  49. package/node_modules/pi-better-subagents/runtime-client/src/runtime/work-client.mjs +43 -14
  50. package/node_modules/pi-better-subagents/shared-navigator.ts +2 -2
  51. package/node_modules/pi-better-subagents/shared-work-client.mjs +43 -14
  52. package/node_modules/pi-better-subagents/stop.ts +9 -0
  53. package/node_modules/pi-better-subagents/work-observation.ts +7 -1
  54. package/package.json +6 -4
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { connect } from "node:net";
3
4
  import { performance } from "node:perf_hooks";
4
5
  import { setTimeout as delay } from "node:timers/promises";
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
13
14
  return file ? existsSync(file) : Boolean(session.getLeafId?.());
14
15
  }
15
16
 
17
+ function unknownLaunchReceipt(cause) {
18
+ return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
19
+ }
20
+
16
21
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
17
22
  export class WorkClient {
23
+ lastSubscriptionTrace;
18
24
  socket;
19
25
  snapshot;
20
26
  pending = new Map();
@@ -29,6 +35,7 @@ export class WorkClient {
29
35
  recoveryAgain = false;
30
36
  recoveryDelay = 100;
31
37
  scopeGeneration = 0;
38
+ snapshotGeneration = 0;
32
39
 
33
40
  constructor(socketPath, agentDir, requiredCapabilities = []) {
34
41
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
@@ -44,7 +51,10 @@ export class WorkClient {
44
51
  if (message.type === "event") {
45
52
  if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
46
53
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
47
- else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
54
+ else if (message.event.type === "runtime_snapshot") {
55
+ const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
56
+ this.accept(message.event.snapshot, message.event.previousSeq, generation);
57
+ }
48
58
  } else {
49
59
  const request = this.pending.get(message.id);
50
60
  if (!request) continue;
@@ -64,10 +74,28 @@ export class WorkClient {
64
74
  request(type, params = {}) {
65
75
  if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
66
76
  if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
67
- const id = `work-${++this.sequence}`;
77
+ const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
78
+ if (trace) this.lastSubscriptionTrace = trace;
79
+ const id = trace?.id ?? `work-${++this.sequence}`;
68
80
  return new Promise((resolve, reject) => {
69
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
70
- this.pending.set(id, { resolve, reject, timer });
81
+ const rejectPending = type === "runtime_launch_subagent" ? error => reject(unknownLaunchReceipt(error)) : reject;
82
+ const timer = setTimeout(() => {
83
+ this.pending.delete(id);
84
+ if (trace) trace.timedOutAt = Date.now();
85
+ rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
86
+ }, 5000);
87
+ this.pending.set(id, { resolve: value => {
88
+ if (trace) trace.receivedAt = Date.now();
89
+ // Apply subscription receipts in wire order, including events in the same socket chunk.
90
+ try {
91
+ if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
92
+ this.accept(value, undefined, params.subscriptionGeneration);
93
+ resolve(value);
94
+ } catch (error) { reject(error); }
95
+ }, reject: error => {
96
+ if (trace) trace.receivedAt = Date.now();
97
+ reject(error);
98
+ }, rejectPending, timer });
71
99
  this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
72
100
  });
73
101
  }
@@ -78,17 +106,20 @@ export class WorkClient {
78
106
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
79
107
  this.notify();
80
108
  }
81
- accept(snapshot, previousSeq) {
82
- if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
109
+ accept(snapshot, previousSeq, generation = this.scopeGeneration) {
110
+ if (this.closed || generation !== this.scopeGeneration) return;
111
+ const sameSubscription = this.snapshotGeneration === generation;
112
+ if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
83
113
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
84
114
  this.degrade("instance-changed: resync required");
85
115
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
86
- } else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
116
+ } else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
87
117
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
88
118
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
89
119
  }
90
120
  // Global seq may skip unrelated changes; only a missing subscription
91
121
  // predecessor indicates loss. The received snapshot is still complete.
122
+ this.snapshotGeneration = generation;
92
123
  this.snapshot = Object.freeze(snapshot); this.notify();
93
124
  }
94
125
  scheduleRecovery(delay = 0) {
@@ -123,18 +154,16 @@ export class WorkClient {
123
154
  }
124
155
  async subscribe(scope) {
125
156
  await this.ready;
126
- this.scopeGeneration++;
157
+ const generation = ++this.scopeGeneration;
127
158
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
128
159
  this.recoveryAgain = false; this.recoveryDelay = 100;
129
160
  this.scope = scope;
130
- const snapshot = await this.request("runtime_subscribe", { scope });
131
- this.accept(snapshot); return snapshot;
161
+ return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
132
162
  }
133
163
  async resync() {
134
164
  const generation = this.scopeGeneration;
135
- const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
136
- if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
137
- return snapshot;
165
+ return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
166
+ sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
138
167
  }
139
168
  async get(scope) {
140
169
  await this.ready;
@@ -151,7 +180,7 @@ export class WorkClient {
151
180
  this.closed = true;
152
181
  this.scopeGeneration++;
153
182
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
154
- for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
183
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
155
184
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
156
185
  for (const listener of this.catalogListeners) listener({ status: "revoked" });
157
186
  }
@@ -77,7 +77,7 @@ import {
77
77
  type SupervisorStartOptions,
78
78
  type SupervisorTaskStatus,
79
79
  } from "./supervisor/index.js";
80
- import { processGroupExitVerified } from "./supervisor/identity.js";
80
+ import { processGroupExitVerified, verifyProcessIdentity } from "./supervisor/identity.js";
81
81
  import { readStopRequest, writeTextAtomic } from "./supervisor/store.js";
82
82
  import { ciObserverArgv, ciRunFromArgv, validCiRun } from "./ci-observation.js";
83
83
  import type { BackgroundTaskCallbackOrigin, CommandSpec, Condition, TaskSandboxProvenance } from "./types.js";
@@ -1355,7 +1355,8 @@ export class ObservedWaitHost {
1355
1355
  store.verifyAssignmentCleanup(candidate.operationId, launchToken, candidate.terminalRevision);
1356
1356
  return;
1357
1357
  }
1358
- if (!pgid) return;
1358
+ if (!pgid || (process.platform === "win32" &&
1359
+ verifyProcessIdentity(inspection.command?.pid, inspection.command?.pidStartTime) !== "verified")) return;
1359
1360
  }
1360
1361
  if (!this.localCancels.has(taskId)) {
1361
1362
  this.localCancels.add(taskId);
@@ -286,9 +286,68 @@ export function recentMetaDeadline(origin: BackgroundTaskCallbackOrigin): number
286
286
  return recentEntries(origin).map(entry => entry.observedAt + RECENT_MS);
287
287
  }
288
288
 
289
+ /** Read each task once, even when its active and recent pointers overlap. */
290
+ export function observeOriginActivity(origin: BackgroundTaskCallbackOrigin, retained: string[] = [], exactId?: string) {
291
+ let active: string[];
292
+ let recent: Array<{ id: string; observedAt: number }>;
293
+ if (exactId !== undefined) {
294
+ if (!/^[A-Za-z0-9_-]+$/.test(exactId)) throw new Error("Invalid Background task ID");
295
+ registryIo.indexRevisionChecks += 2;
296
+ const marker = statSync(join(recentPath(origin), exactId), { throwIfNoEntry: false });
297
+ recent = marker && marker.mtimeMs + RECENT_MS > Date.now() ? [{ id: exactId, observedAt: marker.mtimeMs }] : [];
298
+ active = statSync(join(originActiveIndexDir(origin), exactId), { throwIfNoEntry: false }) ? [exactId] : [];
299
+ } else {
300
+ registryIo.indexDirectoryReads++;
301
+ try { active = readdirSync(originActiveIndexDir(origin)).filter(id => id !== ".initialized"); }
302
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; active = []; }
303
+ recent = recentEntries(origin);
304
+ }
305
+ const deadlines = recent.map(entry => entry.observedAt + RECENT_MS);
306
+ const recentIds = new Set(recent.map(entry => entry.id));
307
+ const activeIds = new Set(active);
308
+ const retainedIds = new Set(retained);
309
+ const rows: BackgroundTaskMeta[] = [];
310
+ for (const id of new Set([...active, ...recentIds, ...retained])) {
311
+ const record = inspectMeta(id);
312
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${id}: ${record.error}`);
313
+ const meta = record.meta;
314
+ if (!meta || !belongsToOrigin(meta, origin) || meta.dismissedAt !== undefined) continue;
315
+ const wasRetained = retainedIds.has(id) && meta.status !== "running" && (!meta.endedAt || meta.endedAt + RECENT_MS > Date.now());
316
+ if (wasRetained && meta.endedAt) deadlines.push(meta.endedAt + RECENT_MS);
317
+ if (wasRetained || recentIds.has(id) || (activeIds.has(id) && meta.callbackOrigin && meta.status === "running")) rows.push(meta);
318
+ }
319
+ return { rows, deadline: deadlines.length ? Math.min(...deadlines) : null };
320
+ }
321
+
289
322
  /** Exact cooperative source identity; no metadata or historical enumeration. */
290
323
  export function observationRevisionForOrigin(origin: BackgroundTaskCallbackOrigin): string {
291
- return [originActiveIndexDir(origin), recentPath(origin)].map(indexDirectorySignature).join(";");
324
+ return observedIndexRevision(originKey(origin));
325
+ }
326
+
327
+ const absentOrigin = "missing;missing";
328
+ function observedIndexRevision(key: string): string {
329
+ const root = baseDir();
330
+ return [join(root, "by-origin-active", key), join(root, "by-origin-recent", key)]
331
+ .map(path => indexDirectorySignature(path, true)).join(";");
332
+ }
333
+
334
+ /** A missing origin directory cannot appear without changing its parent. Existing directories
335
+ * still need exact checks because writes to their children do not change the parent's stamp. */
336
+ export function beginOriginIndexScan(previous?: { roots: string; missing: Set<string> }) {
337
+ const roots = observedIndexRevision("");
338
+ const missing = new Set<string>();
339
+ const revisions = new Map<string, string>();
340
+ function revision(origin: BackgroundTaskCallbackOrigin): string {
341
+ if (roots === absentOrigin) return absentOrigin;
342
+ const key = originKey(origin);
343
+ const cached = revisions.get(key);
344
+ if (cached !== undefined) return cached;
345
+ const stamp = previous?.roots === roots && previous.missing.has(key) ? absentOrigin : observedIndexRevision(key);
346
+ if (stamp === absentOrigin) missing.add(key);
347
+ revisions.set(key, stamp);
348
+ return stamp;
349
+ }
350
+ return { state: { roots, missing }, revision };
292
351
  }
293
352
 
294
353
  /** Bounded cooperative writes, including results written before the first reader. */
@@ -441,12 +500,13 @@ function removeIndexEntry(directory: string, id: string): void {
441
500
  }
442
501
  }
443
502
 
444
- function indexDirectorySignature(directory: string): string {
503
+ function indexDirectorySignature(directory: string, verifyAbsence = false): string {
445
504
  registryIo.indexRevisionChecks += 1;
446
505
  try {
447
- const stat = statSync(directory);
448
- return `${stat.dev}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}`;
449
- } catch {
506
+ const stat = statSync(directory, { bigint: true });
507
+ return [stat.dev, stat.ino, stat.mtimeNs, stat.ctimeNs].join(":");
508
+ } catch (error) {
509
+ if (verifyAbsence && (error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
450
510
  return "missing";
451
511
  }
452
512
  }
@@ -1539,7 +1539,7 @@ function neighbourCloseTarget(
1539
1539
 
1540
1540
  function buildTranscriptDetailLines(
1541
1541
  detail: BackgroundWorkDetail,
1542
- transcriptLines: string[],
1542
+ transcriptLines: readonly string[],
1543
1543
  width: number,
1544
1544
  truncate: (s: string, width: number) => string,
1545
1545
  fg: (color: string, value: string) => string,
@@ -1599,7 +1599,7 @@ function detailOverlayOptions() {
1599
1599
  };
1600
1600
  }
1601
1601
 
1602
- function renderEditorLines(width: number): string[] {
1602
+ function renderEditorLines(width: number): readonly string[] {
1603
1603
  try {
1604
1604
  const lines = state().editorComponent?.render(width);
1605
1605
  if (lines?.length) return lines;
@@ -1,4 +1,5 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { connect } from "node:net";
3
4
  import { performance } from "node:perf_hooks";
4
5
  import { setTimeout as delay } from "node:timers/promises";
@@ -13,8 +14,13 @@ export function shouldRestoreWorkObservation(event, session) {
13
14
  return file ? existsSync(file) : Boolean(session.getLeafId?.());
14
15
  }
15
16
 
17
+ function unknownLaunchReceipt(cause) {
18
+ return Object.assign(new Error(`Launch receipt unavailable: ${cause.message}`, { cause }), { code: "LAUNCH_OUTCOME_UNKNOWN" });
19
+ }
20
+
16
21
  /** SDK-free observation stream. Cached snapshots are the only synchronous read API. */
17
22
  export class WorkClient {
23
+ lastSubscriptionTrace;
18
24
  socket;
19
25
  snapshot;
20
26
  pending = new Map();
@@ -29,6 +35,7 @@ export class WorkClient {
29
35
  recoveryAgain = false;
30
36
  recoveryDelay = 100;
31
37
  scopeGeneration = 0;
38
+ snapshotGeneration = 0;
32
39
 
33
40
  constructor(socketPath, agentDir, requiredCapabilities = []) {
34
41
  this.socket = typeof socketPath === "string" ? connect(socketPath) : socketPath;
@@ -44,7 +51,10 @@ export class WorkClient {
44
51
  if (message.type === "event") {
45
52
  if (message.event.type === "runtime_catalog_snapshot") { for (const listener of this.catalogListeners) listener(message.event.snapshot); continue; }
46
53
  if (message.event.type === "resync_required") { this.degrade(message.event.reason); this.scheduleRecovery(); }
47
- else if (message.event.type === "runtime_snapshot") this.accept(message.event.snapshot, message.event.previousSeq);
54
+ else if (message.event.type === "runtime_snapshot") {
55
+ const generation = message.event.subscriptionGeneration ?? this.snapshotGeneration;
56
+ this.accept(message.event.snapshot, message.event.previousSeq, generation);
57
+ }
48
58
  } else {
49
59
  const request = this.pending.get(message.id);
50
60
  if (!request) continue;
@@ -64,10 +74,28 @@ export class WorkClient {
64
74
  request(type, params = {}) {
65
75
  if (this.closed) return Promise.reject(new Error("runtime-unavailable: disconnected; resync required"));
66
76
  if (this.pending.size >= 32) return Promise.reject(new Error("runtime-unhealthy: too many in-flight queries"));
67
- const id = `work-${++this.sequence}`;
77
+ const trace = type === "runtime_subscribe" ? { id: `sub-${randomUUID()}`, sentAt: Date.now() } : undefined;
78
+ if (trace) this.lastSubscriptionTrace = trace;
79
+ const id = trace?.id ?? `work-${++this.sequence}`;
68
80
  return new Promise((resolve, reject) => {
69
- const timer = setTimeout(() => { this.pending.delete(id); reject(new Error(`runtime-unhealthy: ${type} timed out`)); }, 5000);
70
- this.pending.set(id, { resolve, reject, timer });
81
+ const rejectPending = type === "runtime_launch_subagent" ? error => reject(unknownLaunchReceipt(error)) : reject;
82
+ const timer = setTimeout(() => {
83
+ this.pending.delete(id);
84
+ if (trace) trace.timedOutAt = Date.now();
85
+ rejectPending(new Error(`runtime-unhealthy: ${type} timed out${trace ? ` (${trace.id})` : ""}`));
86
+ }, 5000);
87
+ this.pending.set(id, { resolve: value => {
88
+ if (trace) trace.receivedAt = Date.now();
89
+ // Apply subscription receipts in wire order, including events in the same socket chunk.
90
+ try {
91
+ if (type === "runtime_subscribe" && Number.isSafeInteger(params.subscriptionGeneration))
92
+ this.accept(value, undefined, params.subscriptionGeneration);
93
+ resolve(value);
94
+ } catch (error) { reject(error); }
95
+ }, reject: error => {
96
+ if (trace) trace.receivedAt = Date.now();
97
+ reject(error);
98
+ }, rejectPending, timer });
71
99
  this.socket.write(JSON.stringify({ id, type, ...params }) + "\n");
72
100
  });
73
101
  }
@@ -78,17 +106,20 @@ export class WorkClient {
78
106
  this.snapshot = { ...this.snapshot, status: "degraded", reason, rows: this.snapshot?.rows ?? [] };
79
107
  this.notify();
80
108
  }
81
- accept(snapshot, previousSeq) {
82
- if (this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
109
+ accept(snapshot, previousSeq, generation = this.scopeGeneration) {
110
+ if (this.closed || generation !== this.scopeGeneration) return;
111
+ const sameSubscription = this.snapshotGeneration === generation;
112
+ if (sameSubscription && this.snapshot?.instanceId === snapshot.instanceId && snapshot.seq < this.snapshot.seq) return;
83
113
  if (this.snapshot?.instanceId && this.snapshot.instanceId !== snapshot.instanceId) {
84
114
  this.degrade("instance-changed: resync required");
85
115
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "instance-changed" };
86
- } else if (this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
116
+ } else if (sameSubscription && this.snapshot?.seq !== undefined && Number.isSafeInteger(previousSeq) && previousSeq > this.snapshot.seq) {
87
117
  this.degrade("sequence-gap: replacing with a full authoritative snapshot");
88
118
  snapshot = { ...snapshot, resyncRequired: true, resyncReason: "sequence-gap" };
89
119
  }
90
120
  // Global seq may skip unrelated changes; only a missing subscription
91
121
  // predecessor indicates loss. The received snapshot is still complete.
122
+ this.snapshotGeneration = generation;
92
123
  this.snapshot = Object.freeze(snapshot); this.notify();
93
124
  }
94
125
  scheduleRecovery(delay = 0) {
@@ -123,18 +154,16 @@ export class WorkClient {
123
154
  }
124
155
  async subscribe(scope) {
125
156
  await this.ready;
126
- this.scopeGeneration++;
157
+ const generation = ++this.scopeGeneration;
127
158
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
128
159
  this.recoveryAgain = false; this.recoveryDelay = 100;
129
160
  this.scope = scope;
130
- const snapshot = await this.request("runtime_subscribe", { scope });
131
- this.accept(snapshot); return snapshot;
161
+ return this.request("runtime_subscribe", { scope, subscriptionGeneration: generation });
132
162
  }
133
163
  async resync() {
134
164
  const generation = this.scopeGeneration;
135
- const snapshot = await this.request("runtime_subscribe", { scope: this.scope, sinceSeq: this.snapshot?.seq, instanceId: this.snapshot?.instanceId });
136
- if (!this.closed && generation === this.scopeGeneration) this.accept(snapshot);
137
- return snapshot;
165
+ return this.request("runtime_subscribe", { scope: this.scope, subscriptionGeneration: generation,
166
+ sinceSeq: this.snapshotGeneration === generation ? this.snapshot?.seq : undefined, instanceId: this.snapshot?.instanceId });
138
167
  }
139
168
  async get(scope) {
140
169
  await this.ready;
@@ -151,7 +180,7 @@ export class WorkClient {
151
180
  this.closed = true;
152
181
  this.scopeGeneration++;
153
182
  clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined;
154
- for (const request of this.pending.values()) { clearTimeout(request.timer); request.reject(error); }
183
+ for (const request of this.pending.values()) { clearTimeout(request.timer); request.rejectPending(error); }
155
184
  this.pending.clear(); this.socket.destroy(); this.degrade(String(error));
156
185
  for (const listener of this.catalogListeners) listener({ status: "revoked" });
157
186
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.18.0",
3
+ "version": "0.18.1",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -16,6 +16,7 @@ interface GoalLike {
16
16
  goalId: string;
17
17
  objective: string;
18
18
  command?: unknown;
19
+ workflowBinding?: { name?: unknown; path?: unknown } | null;
19
20
  status: GoalStatus;
20
21
  pauseReason?: unknown;
21
22
  tokenBudget?: number | null;
@@ -133,6 +134,9 @@ function normalizeGoal(goal: GoalLike): GoalSnapshot {
133
134
  goalId: goal.goalId,
134
135
  objective: goal.objective,
135
136
  ...(isCommandBinding(goal.command) ? { command: goal.command } : {}),
137
+ ...(goal.workflowBinding === null ? { workflowBinding: null } :
138
+ typeof goal.workflowBinding?.name === "string" && typeof goal.workflowBinding.path === "string"
139
+ ? { workflowBinding: { name: goal.workflowBinding.name, path: goal.workflowBinding.path } } : {}),
136
140
  status: goal.status,
137
141
  ...(pauseReason ? { pauseReason } : {}),
138
142
  tokenBudget: typeof goal.tokenBudget === "number" ? goal.tokenBudget : null,
@@ -43,8 +43,8 @@ import {
43
43
  import { createRenderScheduler } from "./shared-render-scheduler.js";
44
44
  import { initializeNavigatorPanels, setNavigatorPanel } from "./shared-navigator-panels.js";
45
45
  import { collectSubagentActivity } from "./subagents.js";
46
- import { currentWorkflowOwner, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
47
- import { completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
46
+ import { currentWorkflowOwner, restoredWorkflowMatches, ISSUE_WORKFLOW_SKILLS, skillCommandName, workflowEntry, workflowOwnerFromSkill, WORKFLOW_ENTRY_TYPE } from "./workflow.js";
47
+ import { boundPlanEntry, WORKFLOW_PLAN_ENTRY, completionGate, pauseGate, schedulerWaitUntil, operationResumeSchedulerGate } from "./workflow-gates.js";
48
48
  import { workflowRehydrateMessage, WORKFLOW_REHYDRATE_MESSAGE_TYPE } from "./rehydrate.js";
49
49
  import { canStartGoalFromOutcome, GOAL_PANEL_START_EVENT, type GoalPanelStartRequest, OUTCOME_ACCEPTED_EVENT, requestTaskContext, type OutcomeAcceptedEvent } from "./task-context.js";
50
50
  import {
@@ -398,8 +398,9 @@ export default function (pi: ExtensionAPI): void {
398
398
  return false;
399
399
  }
400
400
  };
401
- const recordWorkflow = (owner: ReturnType<typeof currentWorkflowOwner>, resumePlan = false): void => {
402
- pi.appendEntry(WORKFLOW_ENTRY_TYPE, { ...workflowEntry(owner), ...(resumePlan && { resumePlan }) });
401
+ const recordWorkflow = (owner: ReturnType<typeof currentWorkflowOwner>, plan?: ReturnType<typeof boundPlanEntry>): void => {
402
+ pi.appendEntry(WORKFLOW_ENTRY_TYPE, workflowEntry(owner));
403
+ if (plan) pi.appendEntry(WORKFLOW_PLAN_ENTRY, plan);
403
404
  pi.events.emit("pi-better-workflow:changed", owner);
404
405
  };
405
406
 
@@ -529,15 +530,13 @@ export default function (pi: ExtensionAPI): void {
529
530
  ? workflowOwnerFromSkill(goal.command.name.slice("skill:".length), goal.command.path, registeredSkillPath)
530
531
  : null;
531
532
 
532
- /**
533
- * The session's workflow owner when an active goal is bound to it through its skill command, else
534
- * null. Only these goals are gated by the workflow's scheduler.
535
- */
536
533
  const boundWorkflow = (goal: GoalSnapshot, ctx: ExtensionContext): NonNullable<ReturnType<typeof currentWorkflowOwner>> | null => {
537
534
  const owner = getWorkflow(ctx);
538
- if (!owner || goal.status !== "active" || goal.command?.source !== "skill") return null;
535
+ if (!owner || goal.command?.source !== "skill") return null;
539
536
  try {
540
537
  const bound = goalWorkflowOwner(goal);
538
+ if (goal.workflowBinding !== undefined &&
539
+ (goal.workflowBinding?.name !== bound?.name || goal.workflowBinding?.path !== bound?.path)) return null;
541
540
  return bound?.name === owner.name && bound.path === owner.path ? owner : null;
542
541
  } catch {
543
542
  return null;
@@ -698,6 +697,7 @@ export default function (pi: ExtensionAPI): void {
698
697
  const owner = command?.source === "skill"
699
698
  ? workflowOwnerFromSkill(command.name.slice("skill:".length), command.path, registeredSkillPath)
700
699
  : null;
700
+ if (command?.source === "skill") goal.workflowBinding = owner ? { name: owner.name, path: owner.path } : null;
701
701
  if (getWorkflow(ctx)) recordWorkflow(null);
702
702
  setGoal(goal, ctx, source);
703
703
  if (command) {
@@ -1037,7 +1037,7 @@ export default function (pi: ExtensionAPI): void {
1037
1037
  const invalid = validateObjective(objective);
1038
1038
  if (invalid) return invalid;
1039
1039
  const owner = getWorkflow(ctx);
1040
- if (owner && !workflowAvailable(owner)) return `Restore /skill:${owner.name} before continuing its Todo.`;
1040
+ if (!previous && owner && !workflowAvailable(owner)) return `Restore /skill:${owner.name} before continuing its Todo.`;
1041
1041
  if (previous) {
1042
1042
  const blocker = resumeBlocker(previous, ctx);
1043
1043
  if (blocker) return blocker;
@@ -1045,17 +1045,19 @@ export default function (pi: ExtensionAPI): void {
1045
1045
  if (objective.startsWith("/") && (!previous?.command || previous.objective.trim() !== objective)) {
1046
1046
  return "Reinvoke the original command to continue this Goal.";
1047
1047
  }
1048
- const command = previous?.command ?? (owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null);
1048
+ const command = previous ? previous.command : owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null;
1049
1049
  const goal = createGoalSnapshot(objective, null, undefined, command ?? undefined);
1050
1050
  const restoredOwner = previous?.command ? goalWorkflowOwner(goal) : null;
1051
- const completedOwner = previous?.command?.source === "skill"
1052
- ? currentWorkflowOwner(ctx.sessionManager.getBranch(), previous.goalId) : null;
1053
- if ((completedOwner && (restoredOwner?.name !== completedOwner.name || restoredOwner.path !== completedOwner.path)) ||
1054
- (handoffOwner && restoredOwner?.name !== handoffOwner) ||
1055
- (restoredOwner && owner && (restoredOwner.name !== owner.name || restoredOwner.path !== owner.path))) {
1051
+ if (previous?.command?.source === "skill" && !restoredWorkflowMatches(previous, ctx.sessionManager.getBranch(), restoredOwner)) {
1056
1052
  return "Reinvoke the original workflow to continue its Todo.";
1057
1053
  }
1058
- return { goal, restore: owner ? null : restoredOwner };
1054
+ if (handoffOwner && restoredOwner?.name !== handoffOwner) return "Reinvoke the original workflow to continue its Todo.";
1055
+ if (command?.source === "skill") {
1056
+ const binding = previous ? restoredOwner : owner;
1057
+ goal.workflowBinding = binding ? { name: binding.name, path: binding.path } : null;
1058
+ }
1059
+ const plan = restoredOwner && previous ? boundPlanEntry(ctx.sessionManager.getBranch(), restoredOwner, previous.goalId) : undefined;
1060
+ return { goal, restore: restoredOwner, plan };
1059
1061
  };
1060
1062
 
1061
1063
  const unsubscribeOutcomeAccepted = pi.events.on(OUTCOME_ACCEPTED_EVENT, (value: unknown) => {
@@ -1070,8 +1072,8 @@ export default function (pi: ExtensionAPI): void {
1070
1072
  if (!canStartGoalFromOutcome(event.outcome, reopenedGoal)) return;
1071
1073
  const prepared = prepareSavedGoal(ctx, event.outcome.objective.trim(), reopenedGoal);
1072
1074
  if (typeof prepared === "string") return;
1075
+ if (prepared.restore) recordWorkflow(prepared.restore, prepared.plan);
1073
1076
  setGoal(prepared.goal, ctx, "runtime", "bind");
1074
- if (prepared.restore) recordWorkflow(prepared.restore, true);
1075
1077
  resetContinuationState(prepared.goal);
1076
1078
  });
1077
1079
 
@@ -1118,8 +1120,8 @@ export default function (pi: ExtensionAPI): void {
1118
1120
  const prepared = prepareSavedGoal(ctx, savedGoal.objective, previous, handoffOwner);
1119
1121
  if (typeof prepared === "string") { warn(prepared); return; }
1120
1122
  const { goal } = prepared;
1123
+ if (prepared.restore) recordWorkflow(prepared.restore, prepared.plan);
1121
1124
  setGoal(action === "pause" ? goalWithStatus(goal, "paused") : goal, ctx, "command", "adopt");
1122
- if (prepared.restore) recordWorkflow(prepared.restore, true);
1123
1125
  if (action === "resume") queueGoalContinuation(goal, ctx);
1124
1126
  } else if (action === "resume") {
1125
1127
  if (!current) { warn("No saved Goal or unfinished Todo to resume."); return; }
@@ -1240,8 +1242,9 @@ export default function (pi: ExtensionAPI): void {
1240
1242
  notifyGoal(ctx, "No goal is set.", "warning");
1241
1243
  return;
1242
1244
  }
1245
+ const releaseOwner = current.status !== "complete" ? boundWorkflow(current, ctx) : null;
1243
1246
  setGoal(goalWithStatus(current, "complete"), ctx, "command");
1244
- if (getWorkflow(ctx)) recordWorkflow(null);
1247
+ if (releaseOwner) recordWorkflow(null);
1245
1248
  notifyGoal(ctx, "Goal marked complete.");
1246
1249
  return;
1247
1250
  }
@@ -1314,7 +1317,8 @@ export default function (pi: ExtensionAPI): void {
1314
1317
  details: { ok: true, goal: current },
1315
1318
  };
1316
1319
  }
1317
- const gated = boundWorkflow(current, ctx);
1320
+ const releaseOwner = boundWorkflow(current, ctx);
1321
+ const gated = current.status === "active" ? releaseOwner : null;
1318
1322
  const verdict = gated ? await completionGate(ctx.sessionManager.getBranch(), gated) : null;
1319
1323
  if (verdict && !verdict.allow) {
1320
1324
  return {
@@ -1326,13 +1330,15 @@ export default function (pi: ExtensionAPI): void {
1326
1330
  if (latest?.goalId !== current.goalId || latest.status !== current.status) {
1327
1331
  return { content: [{ type: "text", text: "Goal changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1328
1332
  }
1329
- if (gated) {
1330
- const owner = getWorkflow(ctx);
1331
- if (owner?.name !== gated.name || owner.path !== gated.path) {
1332
- return { content: [{ type: "text", text: "Workflow changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1333
- }
1333
+ const activeOwner = boundWorkflow(latest, ctx);
1334
+ if (releaseOwner?.name !== activeOwner?.name || releaseOwner?.path !== activeOwner?.path) {
1335
+ return { content: [{ type: "text", text: "Workflow changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1336
+ }
1337
+ const audit = requestTaskContext(pi, "audit", current);
1338
+ if (audit.enabled && !audit.auditHandled) {
1339
+ return { content: [{ type: "text", text: "Harness did not confirm the Todo audit. Update Harness before completing this Goal." }],
1340
+ details: { ok: false, goal: current } };
1334
1341
  }
1335
- const audit = requestTaskContext(pi, { action: "audit", workflowOwnsPlan: !!gated }, current);
1336
1342
  const criteria = audit.doneWhen?.length ? audit.doneWhen : audit.objective ? [audit.objective] : [];
1337
1343
  const evidence = [...input.evidence ?? [], ...audit.evidence ?? []];
1338
1344
  const missing = criteria.filter(criterion => !evidence.some(item => item.criterion === criterion && item.result.trim()));
@@ -1347,7 +1353,7 @@ export default function (pi: ExtensionAPI): void {
1347
1353
  }
1348
1354
  const goal = goalWithStatus(latest, "complete");
1349
1355
  setGoal(goal, ctx, "tool");
1350
- if (gated) recordWorkflow(null);
1356
+ if (releaseOwner) recordWorkflow(null);
1351
1357
  const warning = verdict?.allow ? verdict.warning : undefined;
1352
1358
  return {
1353
1359
  content: [{ type: "text", text: warning ? `Goal marked complete. ${warning}` : "Goal marked complete." }],
@@ -1431,7 +1437,7 @@ export default function (pi: ExtensionAPI): void {
1431
1437
  const owner = getWorkflow(ctx);
1432
1438
  if (!owner) return { content: [{ type: "text", text: "No workflow owns this session." }], details: { released: false } };
1433
1439
  const goal = getGoal(ctx);
1434
- const gated = goal ? boundWorkflow(goal, ctx) : null;
1440
+ const gated = goal?.status === "active" ? boundWorkflow(goal, ctx) : null;
1435
1441
  const verdict = gated ? await pauseGate(ctx.sessionManager.getBranch(), gated) : null;
1436
1442
  if (verdict && !verdict.allow) {
1437
1443
  return { content: [{ type: "text", text: verdict.message }], details: { released: false, goalPaused: false } };
@@ -44,6 +44,7 @@ export function canStartGoalFromOutcome(value: unknown, reopenedGoal?: Pick<Goal
44
44
  */
45
45
  export interface TaskContextRequest {
46
46
  action: TaskContextAction;
47
+ auditHandled?: boolean;
47
48
  savedGoal?: { objective: string; status: string; goalId?: string; reopenedGoalId?: string };
48
49
  handoffOwner?: string;
49
50
  manual?: boolean;
@@ -102,6 +102,8 @@ export interface GoalSnapshot {
102
102
  goalId: string;
103
103
  objective: string;
104
104
  command?: GoalCommandBinding;
105
+ /** Canonical coordinator of a skill at creation; older Goals predate this field. */
106
+ workflowBinding?: { name: string; path: string } | null;
105
107
  status: GoalStatus;
106
108
  /** Present only while `status` is "paused". */
107
109
  pauseReason?: GoalPauseReason;