pi-better-goal 0.14.3 → 0.16.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 CHANGED
@@ -12,6 +12,24 @@ Use `pi-better-goal` when a Pi session should keep an explicit objective visible
12
12
 
13
13
  ## Core Features
14
14
 
15
+ ### Activity Provider Contract
16
+
17
+ New providers register `activityVersion: 1`, `getActivity(ctx)`, and
18
+ `onActivityChanged(notify, ctx)`. Each snapshot supplies `nextDeadline` as an
19
+ absolute millisecond timestamp or `null`. Notifications observe the captured
20
+ workspace, session, and branch; they do not authorize a model turn. Goal owns
21
+ continuation admission and transcript writes. Callbacks from replaced execution
22
+ generations are ignored. Deadline timers are cancelled while the Goal is held,
23
+ paused, complete, or foreground-busy, and recalculated on re-entry.
24
+
25
+ Unversioned providers retain legacy compatibility: at most one scheduled
26
+ collection every 2,000 ms per provider while observation is needed. This cost is
27
+ reported as `compatibilityIntervalMs` in its activity snapshot. Notifying
28
+ providers are cached between events and deadlines, even when legacy providers
29
+ need a compatibility check. A v1 provider without notifications is refused; it
30
+ never falls back to a global scanner. Elapsed-clock rendering reads only session
31
+ memory and does not collect activity.
32
+
15
33
  - `/goal` runtime for starting, pausing, resuming, completing, and clearing the current objective.
16
34
  - `/goal settings` opens an interactive settings page in the TUI. Select a row with Up/Down and toggle with Space/Enter; changes save immediately, and Escape closes the page. Automatic continuation, conversational resume, and **Pause on Esc** default to `on`. **Auto-start Goal** defaults to `off` and is also available directly on the `/harness-settings` main page. Automatic continuation controls idle and background-drain wakes; conversational resume controls the agent's Escape-pause resume tool; Pause on Esc controls whether editor Escape pauses the active goal. Goal kickoff, `/goal resume`, and `alt+g` remain available with these controls off. For scripts or non-interactive sessions, use `/goal settings auto-continue on|off`, `/goal settings conversational-resume on|off`, `/goal settings pause-on-escape on|off`, or `/goal settings auto-start-from-outcome on|off`; bare `/goal settings` prints the saved values outside the TUI.
17
35
  - `escape` pauses the active goal by default, and it stays paused while you talk to the agent. With **Pause on Esc** off, observed editor Escape leaves the goal active while preserving native streaming interruption and menu/dialog cancellation. Automatic continuation remains independent. Hosts without terminal/focus inspection and unknown custom editors retain generic abort-to-pause behavior because they cannot identify Escape reliably. With conversational resume enabled, say "go" (the agent then calls `goal_resume`), or use `/goal resume` or `alt+g`. `/goal pause` resumes only through `/goal resume` or `alt+g`. Paused goals are never poked. On a macOS terminal without Option-as-Meta, `alt+g` types `©`; use `/goal resume` there.
@@ -32,6 +50,10 @@ With **Auto-start Goal** enabled, a successful explicit `update_todo` outcome sa
32
50
 
33
51
  Existing active, paused or budget-limited Goals are never replaced or resumed. Refinements of a bound outcome do not create another Goal. A new unbound task can start after the previous Goal completes. Session restore, branch navigation and enabling the preference do not replay saved outcomes; the next explicit qualifying save is the trigger. Completing a checklist or outcome does not complete the Goal.
34
52
 
53
+ For an active Goal with a bound Outcome, the agent completes both through `update_goal`. It supplies an `evidence` array with one `{criterion, result}` per `doneWhen` entry, using the Outcome objective if no criteria were recorded. Each result should identify the observed result and its source. Open Todo steps and open items on an associated work ledger block completion. These checks also apply after a workflow scheduler reports `finish`. The user can still complete a Goal manually with `/goal complete`.
54
+
55
+ Explicitly setting the same bound Outcome back to `active` after Goal completion starts a fresh Goal for its remaining work, including when Auto-start Goal is off. The new Goal preserves the Todo. Restoring an older session that saved active work against an already completed Goal leaves that work active and unbound. Running `/goal <exact Outcome objective>` binds it again with its Todo intact.
56
+
35
57
  When a workflow already owns the session, the new Goal binds its registered coordinator without invoking it again. Its scheduler and completion checks continue to apply. An unavailable or invalid workflow coordinator prevents automatic creation.
36
58
 
37
59
  ## Settings Storage
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-better-goal",
3
- "version": "0.14.3",
3
+ "version": "0.16.0",
4
4
  "description": "Pi extension for goal tracking with background-aware continuation.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/activity.ts CHANGED
@@ -19,6 +19,10 @@ export interface BackgroundDrainPlan {
19
19
  wakeSignature: string | null;
20
20
  }
21
21
 
22
+ export function hasUnverifiedActivity(snapshot: ActivitySnapshot): boolean {
23
+ return snapshot.coverage === "unverified" || snapshot.providers.some(provider => provider.coverage === "unverified");
24
+ }
25
+
22
26
  export function activeItems(snapshot: ActivitySnapshot): BackgroundWorkItem[] {
23
27
  return snapshot.providers.flatMap((provider) => provider.items.filter((item) => item.active));
24
28
  }
@@ -50,6 +54,10 @@ export function planBackgroundDrainWake(
50
54
  return { nextTracker: null, wakeSignature: null };
51
55
  }
52
56
 
57
+ if (hasUnverifiedActivity(snapshot)) {
58
+ return { nextTracker: tracker?.goalId === goal.goalId ? tracker : null, wakeSignature: null };
59
+ }
60
+
53
61
  const active = activeSignature(snapshot);
54
62
  if (active) {
55
63
  return {
@@ -69,6 +77,7 @@ export function planBackgroundDrainWake(
69
77
  }
70
78
 
71
79
  export function summarizeActiveBackground(snapshot: ActivitySnapshot): string {
80
+ if (hasUnverifiedActivity(snapshot)) return "Background activity is unverified.";
72
81
  const active = activeItems(snapshot);
73
82
  if (active.length === 0) {
74
83
  return "No active background work.";
@@ -95,7 +104,10 @@ export async function collectActivitySnapshot(
95
104
  const snapshot = await provider.getActivity(ctx);
96
105
  const normalized: BackgroundProviderSnapshot = {
97
106
  providerId: snapshot.providerId || provider.id,
107
+ coverage: snapshot.coverage ?? "verified",
98
108
  items: snapshot.items,
109
+ ...(snapshot.nextDeadline !== undefined ? { nextDeadline: snapshot.nextDeadline } : {}),
110
+ ...(!provider.onActivityChanged ? { compatibilityIntervalMs: 2_000 } : {}),
99
111
  };
100
112
  const label = snapshot.label ?? provider.label;
101
113
  if (label !== undefined) {
@@ -105,6 +117,7 @@ export async function collectActivitySnapshot(
105
117
  } catch (error) {
106
118
  const failedSnapshot: BackgroundProviderSnapshot = {
107
119
  providerId: provider.id,
120
+ coverage: "unverified",
108
121
  items: [
109
122
  {
110
123
  id: `${provider.id}:provider-error`,
@@ -138,14 +151,16 @@ export async function collectActivitySnapshot(
138
151
  0,
139
152
  );
140
153
 
154
+ const coverage = providerSnapshots.some(provider => provider.coverage === "unverified") ? "unverified" : "verified";
141
155
  const category: ActivityCategory = foregroundRunning
142
156
  ? "foreground-running"
143
- : activeBackgroundCount > 0
157
+ : coverage === "unverified" ? "unverified" : activeBackgroundCount > 0
144
158
  ? "background-running"
145
159
  : "idle-waiting";
146
160
 
147
161
  return {
148
162
  version: 1,
163
+ coverage,
149
164
  category,
150
165
  foregroundRunning,
151
166
  backgroundRunning: activeBackgroundCount > 0,
@@ -0,0 +1,118 @@
1
+ import { createRequire } from "node:module";
2
+
3
+ /** Rebuildable observation state, never an execution or delivery credential. */
4
+ export class AssignmentInbox {
5
+ constructor(path, connectionOrOptions, options = {}) {
6
+ const connection = typeof connectionOrOptions?.prepare === "function" ? connectionOrOptions : undefined;
7
+ if (!connection) options = connectionOrOptions ?? options;
8
+ this.entityPrefix = options.entityPrefix;
9
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
10
+ this.shared = Boolean(connection);
11
+ this.db = connection ?? new DatabaseSync(path);
12
+ this.alias = this.entityPrefix === "background:" ? "background_inbox" : "assignment_inbox";
13
+ this.prefix = connection ? `${this.alias}.` : "";
14
+ let attached = false;
15
+ try {
16
+ // Share the query owner's handle; only the attached derived file is durable.
17
+ if (connection) {
18
+ connection.prepare(`ATTACH DATABASE ? AS ${this.alias}`).run(path);
19
+ attached = true;
20
+ }
21
+ // A second observer may open while the first holds a derived write
22
+ // transaction. Existing schema/diagnostics require no write reservation.
23
+ const tables = this.db.prepare(`SELECT count(*) AS n FROM ${this.prefix}sqlite_master
24
+ WHERE type='table' AND name IN ('position','pending','applied_scopes','diagnostics')`).get().n;
25
+ if (tables === 4 && this.db.prepare(`SELECT 1 FROM ${this.prefix}diagnostics LIMIT 1`).get()) return;
26
+ this.db.exec(`CREATE TABLE IF NOT EXISTS ${this.prefix}position (
27
+ singleton INTEGER PRIMARY KEY CHECK(singleton=1), generation TEXT NOT NULL,
28
+ received INTEGER NOT NULL, applied INTEGER NOT NULL);
29
+ CREATE TABLE IF NOT EXISTS ${this.prefix}pending (
30
+ scope TEXT PRIMARY KEY, seq INTEGER NOT NULL, first_seq INTEGER NOT NULL, since INTEGER NOT NULL);
31
+ CREATE TABLE IF NOT EXISTS ${this.prefix}applied_scopes (scope TEXT PRIMARY KEY, seq INTEGER NOT NULL);
32
+ CREATE TABLE IF NOT EXISTS ${this.prefix}diagnostics (repairs INTEGER NOT NULL);`);
33
+ // Reopening an initialized inbox must not reserve every attached file
34
+ // merely to execute an INSERT whose SELECT would produce no rows.
35
+ if (!this.db.prepare(`SELECT 1 FROM ${this.prefix}diagnostics LIMIT 1`).get()) {
36
+ this.db.exec(`INSERT INTO ${this.prefix}diagnostics SELECT 0 WHERE NOT EXISTS (SELECT 1 FROM ${this.prefix}diagnostics)`);
37
+ }
38
+ } catch (error) {
39
+ // A failed constructor cannot transfer its alias to a caller.
40
+ // Never detach an earlier participant or close a borrowed owner.
41
+ try {
42
+ if (attached) this.db.exec(`DETACH DATABASE ${this.alias}`);
43
+ else if (!connection) this.db.close();
44
+ } catch (cleanup) { throw new AggregateError([error, cleanup], "Assignment inbox initialization and owned cleanup failed"); }
45
+ throw error;
46
+ }
47
+ }
48
+
49
+ receive(source, identity) {
50
+ const version = source.prepare("SELECT value FROM schema_meta WHERE key='schema_version'").get()?.value;
51
+ if (!["1", "2", "3", "4"].includes(version)) throw new Error("Unsupported assignment source schema");
52
+ const token = source.prepare("SELECT generation FROM assignment_change_source WHERE singleton=1").get()?.generation;
53
+ if (!token) throw new Error("Assignment change journal unavailable");
54
+ const generation = `${identity}:${version}:${token}`;
55
+ const bounds = source.prepare("SELECT min(seq) AS first, max(seq) AS last FROM assignment_changes").get();
56
+ const last = Number(bounds.last ?? 0);
57
+ const position = this.db.prepare(`SELECT * FROM ${this.prefix}position WHERE singleton=1`).get();
58
+ const reset = !position || position.generation !== generation || position.received > last
59
+ || (bounds.first !== null && position.received < Number(bounds.first) - 1);
60
+ const after = reset ? last : position.received;
61
+ const changes = reset ? [] : source.prepare("SELECT * FROM assignment_changes WHERE seq>? ORDER BY seq LIMIT 128").all(after);
62
+ this.more = !reset && Number(changes.at(-1)?.seq ?? after) < last;
63
+ if (!reset && !changes.length) return this.batch(generation);
64
+ this.db.exec(this.shared ? `SAVEPOINT ${this.alias}_receive` : "BEGIN IMMEDIATE");
65
+ try {
66
+ if (reset) {
67
+ this.db.exec(`DELETE FROM ${this.prefix}pending; DELETE FROM ${this.prefix}applied_scopes; UPDATE ${this.prefix}diagnostics SET repairs=repairs+1`);
68
+ this.db.prepare(`INSERT INTO ${this.prefix}pending VALUES('*', ?, 0, ?)`).run(last, Date.now());
69
+ this.db.prepare(`INSERT OR REPLACE INTO ${this.prefix}position VALUES(1, ?, ?, 0)`).run(generation, last);
70
+ }
71
+ const insert = this.db.prepare(`INSERT INTO ${this.prefix}pending VALUES(?, ?, ?, ?)
72
+ ON CONFLICT(scope) DO UPDATE SET seq=excluded.seq`);
73
+ for (const change of changes) {
74
+ const background = change.entity.startsWith('background:');
75
+ if (this.entityPrefix ? !change.entity.startsWith(this.entityPrefix) : background) continue;
76
+ insert.run(JSON.stringify([change.session_id, change.workspace, change.assignment_id]), change.seq, change.seq, Date.now());
77
+ }
78
+ // The obligations above and received position commit together.
79
+ if (changes.length) this.db.prepare(`UPDATE ${this.prefix}position SET received=? WHERE singleton=1`).run(changes.at(-1).seq);
80
+ this.db.exec(this.shared ? `RELEASE ${this.alias}_receive` : "COMMIT");
81
+ } catch (error) { this.db.exec(this.shared ? `ROLLBACK TO ${this.alias}_receive; RELEASE ${this.alias}_receive` : "ROLLBACK"); throw error; }
82
+ return this.batch(generation);
83
+ }
84
+
85
+ batch(generation) {
86
+ const batch = new Map(this.db.prepare(`SELECT scope, seq FROM ${this.prefix}pending ORDER BY first_seq, scope LIMIT 128`).all().map(row => [row.scope, String(row.seq)]));
87
+ Object.defineProperty(batch, "generation", { value: generation });
88
+ return batch;
89
+ }
90
+
91
+ acknowledge(batch, baselineComplete) {
92
+ const position = this.db.prepare(`SELECT * FROM ${this.prefix}position WHERE singleton=1`).get();
93
+ if (batch.generation && batch.generation !== position?.generation) return;
94
+ if (batch.size && ![...batch.keys()].some(scope => scope !== "*" || baselineComplete)) return;
95
+ if (!batch.size && (!position || position.applied === position.received)) return;
96
+ this.db.exec(this.shared ? `SAVEPOINT ${this.alias}_ack` : "BEGIN IMMEDIATE");
97
+ try {
98
+ const remove = this.db.prepare(`DELETE FROM ${this.prefix}pending WHERE scope=? AND seq=?`);
99
+ const applied = this.db.prepare(`INSERT INTO ${this.prefix}applied_scopes VALUES(?,?) ON CONFLICT(scope) DO UPDATE SET seq=max(seq,excluded.seq)`);
100
+ for (const [scope, seq] of batch) if (scope !== "*" || baselineComplete) {
101
+ if (remove.run(scope, Number(seq)).changes) applied.run(scope, Number(seq));
102
+ }
103
+ // A later entity completing cannot advance past any earlier obligation.
104
+ this.db.exec(`UPDATE ${this.prefix}position SET applied=max(0,min(received,
105
+ COALESCE((SELECT min(first_seq)-1 FROM ${this.prefix}pending), received))) WHERE singleton=1`);
106
+ this.db.exec(this.shared ? `RELEASE ${this.alias}_ack` : "COMMIT");
107
+ } catch (error) { this.db.exec(this.shared ? `ROLLBACK TO ${this.alias}_ack; RELEASE ${this.alias}_ack` : "ROLLBACK"); throw error; }
108
+ }
109
+ get metrics() {
110
+ const pending = this.db.prepare(`SELECT count(*) AS pending, min(since) AS oldestPendingAt FROM ${this.prefix}pending`).get();
111
+ return { ...this.db.prepare(`SELECT * FROM ${this.prefix}position`).get(),
112
+ more: Boolean(this.more),
113
+ affected: this.db.prepare(`SELECT scope, seq, first_seq, since FROM ${this.prefix}pending ORDER BY first_seq, scope LIMIT 128`).all(),
114
+ ...pending, oldestPendingAgeMs: pending.oldestPendingAt === null ? 0 : Math.max(0, Date.now() - Number(pending.oldestPendingAt)),
115
+ ...this.db.prepare(`SELECT repairs FROM ${this.prefix}diagnostics`).get() };
116
+ }
117
+ close() { if (this.shared) this.db.exec(`DETACH DATABASE ${this.alias}`); else this.db.close(); }
118
+ }
package/src/index.ts CHANGED
@@ -10,6 +10,7 @@ import { OPERATION_RESUME_ADMISSION, operationOwnerMatches, type OperationResume
10
10
 
11
11
  import {
12
12
  collectActivitySnapshot,
13
+ hasUnverifiedActivity,
13
14
  planBackgroundDrainWake,
14
15
  summarizeActiveBackground,
15
16
  terminalAttentionSignature,
@@ -56,6 +57,7 @@ import {
56
57
  type ActivitySnapshot,
57
58
  type BackgroundActivityProvider,
58
59
  type BackgroundWorkItem,
60
+ type BackgroundProviderSnapshot,
59
61
  type GoalSnapshot,
60
62
  } from "./types.js";
61
63
 
@@ -203,6 +205,7 @@ export function finishedSinceQuestion(
203
205
  activeAtStart: ReadonlyMap<string, BackgroundWorkItem>,
204
206
  snapshot: ActivitySnapshot,
205
207
  ): BackgroundWorkItem[] {
208
+ if (hasUnverifiedActivity(snapshot)) return [];
206
209
  const stillActive = activeItemsByKey(snapshot);
207
210
  const current = new Map<string, BackgroundWorkItem>();
208
211
  for (const provider of snapshot.providers) {
@@ -309,6 +312,12 @@ export default function (pi: ExtensionAPI): void {
309
312
  initializeNavigatorPanels(pi);
310
313
  const providers = new Map<string, BackgroundActivityProvider>();
311
314
  const providerUnsubscribers = new Map<string, () => void>();
315
+ const providerCache = new Map<string, BackgroundProviderSnapshot>();
316
+ const providerCacheSequences = new Map<string, number>();
317
+ const dirtyProviders = new Set<string>();
318
+ const providerBindings = new Map<string, number>();
319
+ const compatibilityReadAt = new Map<string, number>();
320
+ let providerDeadline: ReturnType<typeof setTimeout> | undefined;
312
321
  providers.set("subagents", {
313
322
  id: "subagents",
314
323
  label: "Subagents",
@@ -622,7 +631,7 @@ export default function (pi: ExtensionAPI): void {
622
631
  if (!auditIsCurrent() || !isPokeable(goal)) return;
623
632
  if (!boundCommandReady(goal, ctx)) return;
624
633
  const snapshot = await publishSnapshot(ctx);
625
- if (!snapshot || !auditIsCurrent() || snapshot.foregroundRunning || snapshot.backgroundRunning) return;
634
+ if (!snapshot || !auditIsCurrent() || snapshot.foregroundRunning || snapshot.backgroundRunning || hasUnverifiedActivity(snapshot)) return;
626
635
 
627
636
  continuationQueuedFor = goal.goalId;
628
637
  const content = kind === "background-drained"
@@ -668,14 +677,54 @@ export default function (pi: ExtensionAPI): void {
668
677
  return goal;
669
678
  };
670
679
 
671
- const publishSnapshot = async (ctx: ExtensionContext): Promise<ActivitySnapshot | null> => {
680
+ const publishSnapshot = async (
681
+ ctx: ExtensionContext, explicit = true,
682
+ readMode: "cached" | "connect" = getGoal(ctx) || getWorkflow(ctx) ? "connect" : "cached",
683
+ ): Promise<ActivitySnapshot | null> => {
684
+ const cachedOnly = readMode === "cached";
685
+ bindProviderSubscriptions();
672
686
  const execution = executionGeneration;
673
687
  const sequence = ++snapshotSequence;
674
- const snapshot = await collectActivitySnapshot(ctx, providers.values(), foregroundRunning);
688
+ const snapshot = await collectActivitySnapshot(ctx, [...providers.values()].map(provider => ({
689
+ ...provider,
690
+ getActivity: async () => {
691
+ const cached = providerCache.get(provider.id);
692
+ if (cached && !provider.onActivityChanged && !explicit && Date.now() < (compatibilityReadAt.get(provider.id) ?? 0)) return cached;
693
+ if (cached && provider.onActivityChanged && !dirtyProviders.has(provider.id) &&
694
+ !(typeof cached.nextDeadline === "number" && cached.nextDeadline <= Date.now())) return cached;
695
+ dirtyProviders.delete(provider.id);
696
+ let value: BackgroundProviderSnapshot;
697
+ try {
698
+ value = await provider.getActivity(ctx, { cachedOnly });
699
+ if (provider.activityVersion === 1 && value.nextDeadline !== null &&
700
+ (typeof value.nextDeadline !== "number" || !Number.isFinite(value.nextDeadline))) {
701
+ throw new Error(`${provider.id}: activity v1 requires an explicit nextDeadline`);
702
+ }
703
+ } catch (error) {
704
+ // A failed fresh read must not resurrect an older verified cache.
705
+ if (execution === executionGeneration && providers.get(provider.id) === provider &&
706
+ sequence >= (providerCacheSequences.get(provider.id) ?? 0)) {
707
+ providerCacheSequences.set(provider.id, sequence);
708
+ providerCache.delete(provider.id);
709
+ }
710
+ throw error;
711
+ }
712
+ // Explicit inspections may finish before an older notification read.
713
+ if (execution === executionGeneration && providers.get(provider.id) === provider &&
714
+ sequence >= (providerCacheSequences.get(provider.id) ?? 0)) {
715
+ providerCacheSequences.set(provider.id, sequence);
716
+ if (cachedOnly && value.coverage === "unverified") providerCache.delete(provider.id);
717
+ else providerCache.set(provider.id, value);
718
+ if (!provider.onActivityChanged) compatibilityReadAt.set(provider.id, Date.now() + POLL_INTERVAL_MS);
719
+ }
720
+ return value;
721
+ },
722
+ })), foregroundRunning);
675
723
  if (execution !== executionGeneration) return null;
676
724
  if (sequence < lastAppliedSnapshotSequence) return latestSnapshot;
677
725
  lastAppliedSnapshotSequence = sequence;
678
726
  latestSnapshot = snapshot;
727
+ armProviderDeadline();
679
728
 
680
729
  const goal = currentGoalSnapshot(ctx);
681
730
  const wakePlan = planBackgroundDrainWake(backgroundDrainTracker, goal, snapshot);
@@ -688,7 +737,7 @@ export default function (pi: ExtensionAPI): void {
688
737
  scheduleIdleContinuation(goal, ctx, "background-drained", snapshot);
689
738
  }
690
739
 
691
- if (snapshot.foregroundRunning || snapshot.backgroundRunning) {
740
+ if (snapshot.foregroundRunning || snapshot.backgroundRunning || hasUnverifiedActivity(snapshot)) {
692
741
  clearIdleContinuation();
693
742
  }
694
743
 
@@ -732,7 +781,7 @@ export default function (pi: ExtensionAPI): void {
732
781
  }
733
782
  collecting = true;
734
783
  const session = sessionGeneration;
735
- void publishSnapshot(ctx).finally(() => {
784
+ void publishSnapshot(ctx, false).finally(() => {
736
785
  if (session !== sessionGeneration) return;
737
786
  collecting = false;
738
787
  if (collectionPending) {
@@ -761,15 +810,49 @@ export default function (pi: ExtensionAPI): void {
761
810
  };
762
811
 
763
812
  const syncPollingState = (): void => {
813
+ bindProviderSubscriptions();
814
+ armProviderDeadline();
764
815
  const ctx = currentCtx;
765
816
  const goal = ctx ? currentGoalSnapshot(ctx) : null;
766
- if (ctx && (isPokeable(goal) || latestSnapshot?.backgroundRunning === true)) {
817
+ if (ctx && [...providers.values()].some(provider => !provider.onActivityChanged) &&
818
+ (isPokeable(goal) || latestSnapshot?.backgroundRunning === true)) {
767
819
  startPolling();
768
820
  } else {
769
821
  stopPolling();
770
822
  }
771
823
  };
772
824
 
825
+ function armProviderDeadline(): void {
826
+ if (providerDeadline) clearTimeout(providerDeadline);
827
+ providerDeadline = undefined;
828
+ if (!currentCtx) return;
829
+ const goal = getGoal(currentCtx);
830
+ if (isForegroundBusy(currentCtx) || (goal && (!isPokeable(goal) || currentContinuationState(currentCtx, goal.goalId)?.blocked))) return;
831
+ const deadlines = [...providerCache.values()].map(value => value.nextDeadline)
832
+ .filter((value): value is number => typeof value === "number" && value > Date.now());
833
+ if (!deadlines.length) return;
834
+ const execution = executionGeneration;
835
+ providerDeadline = setTimeout(() => {
836
+ providerDeadline = undefined;
837
+ if (execution === executionGeneration) collectIfPossible();
838
+ }, Math.min(MAX_TIMER_DELAY_MS, Math.max(1, Math.min(...deadlines) - Date.now())));
839
+ providerDeadline.unref?.();
840
+ }
841
+
842
+ function bindProviderSubscriptions(): void {
843
+ for (const provider of providers.values()) {
844
+ if (!provider.onActivityChanged || providerBindings.get(provider.id) === executionGeneration) continue;
845
+ providerUnsubscribers.get(provider.id)?.();
846
+ const execution = executionGeneration;
847
+ providerBindings.set(provider.id, execution);
848
+ providerUnsubscribers.set(provider.id, provider.onActivityChanged(() => {
849
+ if (!currentCtx || execution !== executionGeneration || providers.get(provider.id) !== provider) return;
850
+ dirtyProviders.add(provider.id);
851
+ collectIfPossible();
852
+ }, currentCtx));
853
+ }
854
+ }
855
+
773
856
  const installGoalWidget = (ctx: ExtensionContext): void => {
774
857
  if (!ctx.hasUI) {
775
858
  return;
@@ -857,6 +940,7 @@ export default function (pi: ExtensionAPI): void {
857
940
  if (goal && currentContinuationState(ctx, goal.goalId)?.blocked) { held("Goal continuation requires human resume"); return; }
858
941
  if (goal && !boundCommandReady(goal, ctx)) { held("Bound workflow is not ready"); return; }
859
942
  const workflow = getWorkflow(ctx);
943
+ if (workflow) request.pending?.();
860
944
  void (workflow ? operationResumeSchedulerGate(ctx.sessionManager.getBranch(), workflow, {
861
945
  scope: operationAdmissionScope,
862
946
  revision: JSON.stringify([request.owner.sessionId, request.owner.workspace, request.owner.branchId, goal?.goalId, revision, preferencesRevision]),
@@ -898,30 +982,40 @@ export default function (pi: ExtensionAPI): void {
898
982
  return;
899
983
  }
900
984
  const accepted = candidate as BackgroundActivityProvider;
985
+ if (accepted.activityVersion !== undefined && accepted.activityVersion !== 1) return;
986
+ if (accepted.activityVersion === 1 && typeof accepted.onActivityChanged !== "function") return;
901
987
  providerUnsubscribers.get(accepted.id)?.();
902
988
  providerUnsubscribers.delete(accepted.id);
903
989
  providers.set(accepted.id, accepted);
904
- if (typeof accepted.onActivityChanged === "function") {
905
- providerUnsubscribers.set(accepted.id, accepted.onActivityChanged(collectIfPossible));
906
- }
990
+ providerCache.delete(accepted.id);
991
+ providerCacheSequences.set(accepted.id, ++snapshotSequence);
992
+ dirtyProviders.add(accepted.id);
993
+ providerBindings.delete(accepted.id);
994
+ bindProviderSubscriptions();
907
995
  if (latestSnapshot) collectIfPossible();
908
996
  });
909
997
 
910
998
  const unsubscribeOutcomeAccepted = pi.events.on(OUTCOME_ACCEPTED_EVENT, (value: unknown) => {
911
999
  const ctx = currentCtx;
912
1000
  const event = value as Partial<OutcomeAcceptedEvent> | null;
913
- if (!preferences.autoStartFromOutcome || !ctx || !event ||
914
- typeof event.sessionId !== "string" || event.sessionId !== ctx.sessionManager.getSessionId() ||
915
- !canStartGoalFromOutcome(event.outcome)) return;
1001
+ if (!ctx || !event ||
1002
+ typeof event.sessionId !== "string" || event.sessionId !== ctx.sessionManager.getSessionId()) return;
916
1003
  const current = getGoal(ctx);
917
1004
  if (current && current.status !== "complete") return;
1005
+ const reopenedGoal = current?.status === "complete" && current.goalId === event.reopenedGoalId ? current : undefined;
1006
+ if ((!reopenedGoal && !preferences.autoStartFromOutcome) || !canStartGoalFromOutcome(event.outcome, reopenedGoal)) return;
918
1007
  const objective = event.outcome.objective.trim();
919
1008
  if (validateObjective(objective)) return;
920
1009
  const owner = getWorkflow(ctx);
921
1010
  if (owner && !workflowAvailable(owner)) return;
922
- const command = owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null;
1011
+ const retainedCommand = objective.startsWith("/") ? reopenedGoal?.command : undefined;
1012
+ const command = retainedCommand ?? (owner ? resolveGoalCommand(pi, `/skill:${owner.name}`) : null);
923
1013
  const goal = createGoalSnapshot(objective, null, undefined, command ?? undefined);
924
1014
  setGoal(goal, ctx, "runtime", true);
1015
+ if (retainedCommand) {
1016
+ const retainedOwner = goalWorkflowOwner(goal);
1017
+ if (retainedOwner && (owner?.name !== retainedOwner.name || owner?.path !== retainedOwner.path)) recordWorkflow(retainedOwner);
1018
+ }
925
1019
  resetContinuationState(goal);
926
1020
  });
927
1021
 
@@ -934,7 +1028,7 @@ export default function (pi: ExtensionAPI): void {
934
1028
  if (!previous.autoContinue && preferences.autoContinue) {
935
1029
  const snapshot = await publishSnapshot(ctx);
936
1030
  const goal = getGoal(ctx);
937
- if (snapshot && isPokeable(goal) && !isForegroundBusy(ctx) && !snapshot.backgroundRunning) {
1031
+ if (snapshot && isPokeable(goal) && !isForegroundBusy(ctx) && !snapshot.backgroundRunning && !hasUnverifiedActivity(snapshot)) {
938
1032
  scheduleIdleContinuation(goal, ctx, "continuation", snapshot);
939
1033
  }
940
1034
  }
@@ -1092,13 +1186,17 @@ export default function (pi: ExtensionAPI): void {
1092
1186
  pi.registerTool({
1093
1187
  name: "update_goal",
1094
1188
  label: "Update Goal",
1095
- description: "Mark the current pi-better-goal objective complete after a completion audit.",
1189
+ description: "Mark the Goal complete after verifying the requested outcome. For each recorded doneWhen criterion, supply its exact text and observed result in evidence. If a bound Outcome has no criteria, use its objective. A scheduler finish alone only confirms that workflow actions have settled.",
1096
1190
  promptSnippet: "Mark the current Codex-style goal complete after verification.",
1097
1191
  parameters: Type.Object({
1192
+ evidence: Type.Optional(Type.Array(Type.Object({
1193
+ criterion: Type.String(),
1194
+ result: Type.String({ description: "Observed result and its source, such as a test run, deployment receipt, or issue state." }),
1195
+ }))),
1098
1196
  status: Type.String({ description: "Only 'complete' is accepted." }),
1099
1197
  }),
1100
1198
  async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
1101
- const input = params as { status: string };
1199
+ const input = params as { status: string; evidence?: Array<{ criterion: string; result: string }> };
1102
1200
  if (input.status !== "complete") {
1103
1201
  return {
1104
1202
  content: [{ type: "text", text: "Only status:'complete' is accepted." }],
@@ -1126,7 +1224,23 @@ export default function (pi: ExtensionAPI): void {
1126
1224
  details: { ok: false, goal: current, due: verdict.due },
1127
1225
  };
1128
1226
  }
1129
- const goal = goalWithStatus(current, "complete");
1227
+ const latest = getGoal(ctx);
1228
+ if (latest?.goalId !== current.goalId || latest.status !== current.status) {
1229
+ return { content: [{ type: "text", text: "Goal changed during the completion check. Read the current Goal." }], details: { ok: false, goal: latest } };
1230
+ }
1231
+ const audit = requestTaskContext(pi, "audit", current);
1232
+ const criteria = audit.doneWhen?.length ? audit.doneWhen : audit.objective ? [audit.objective] : [];
1233
+ const missing = criteria.filter(criterion => !input.evidence?.some(item => item.criterion === criterion && item.result.trim()));
1234
+ if (audit.ledgerBlocker || audit.openSteps?.length || missing.length) {
1235
+ const message = [
1236
+ "Verify the requested outcome before completing the Goal.",
1237
+ ...(audit.ledgerBlocker ? [audit.ledgerBlocker] : []),
1238
+ ...(audit.openSteps ?? []).map(step => `Open Todo: ${step}`),
1239
+ ...missing.map(criterion => `Missing evidence: ${criterion}`),
1240
+ ].join("\n");
1241
+ return { content: [{ type: "text", text: message }], details: { ok: false, goal: current, missing, openSteps: audit.openSteps } };
1242
+ }
1243
+ const goal = goalWithStatus(latest, "complete");
1130
1244
  setGoal(goal, ctx, "tool");
1131
1245
  if (getWorkflow(ctx)) recordWorkflow(null);
1132
1246
  const warning = verdict?.allow ? verdict.warning : undefined;
@@ -1185,7 +1299,7 @@ export default function (pi: ExtensionAPI): void {
1185
1299
  description: "Show foreground/background activity known to pi-better-goal",
1186
1300
  handler: async (_args, ctx) => {
1187
1301
  currentCtx = ctx;
1188
- const snapshot = await publishSnapshot(ctx);
1302
+ const snapshot = await publishSnapshot(ctx, true, "connect");
1189
1303
  if (!snapshot) return;
1190
1304
  ctx.ui.notify(formatSnapshot(snapshot), "info");
1191
1305
  },
@@ -1243,7 +1357,7 @@ export default function (pi: ExtensionAPI): void {
1243
1357
  parameters: Type.Object({}),
1244
1358
  async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
1245
1359
  currentCtx = ctx;
1246
- const snapshot = await publishSnapshot(ctx);
1360
+ const snapshot = await publishSnapshot(ctx, true, "connect");
1247
1361
  if (!snapshot) {
1248
1362
  return { content: [{ type: "text", text: "Activity changed during collection; inspect again." }], details: { stale: true } };
1249
1363
  }
@@ -1268,6 +1382,8 @@ export default function (pi: ExtensionAPI): void {
1268
1382
  lastAgentEvidence = null;
1269
1383
  collecting = false;
1270
1384
  collectionPending = false;
1385
+ providerCache.clear();
1386
+ dirtyProviders.clear();
1271
1387
  currentCtx = ctx;
1272
1388
  foregroundRunning = !ctx.isIdle();
1273
1389
  agentLoopActive = false;
@@ -1302,15 +1418,34 @@ export default function (pi: ExtensionAPI): void {
1302
1418
  return undefined;
1303
1419
  });
1304
1420
  }
1305
- const snapshot = await publishSnapshot(ctx);
1421
+ const snapshot = await publishSnapshot(ctx, true, "cached");
1306
1422
  if (!snapshot) return;
1307
1423
  syncPollingState();
1308
- if (restoredGoal?.status === "active" && restoredGoal.command && boundCommandReady(restoredGoal, ctx) && !foregroundRunning && !snapshot.backgroundRunning) {
1309
- scheduleIdleContinuation(restoredGoal, ctx, "continuation");
1424
+ if (restoredGoal?.status === "active") {
1425
+ const resumeIfIdle = (activity: ActivitySnapshot | null) => {
1426
+ if (activity && restoredGoal.command && boundCommandReady(restoredGoal, ctx) && !foregroundRunning &&
1427
+ !activity.backgroundRunning && !hasUnverifiedActivity(activity)) {
1428
+ scheduleIdleContinuation(restoredGoal, ctx, "continuation");
1429
+ }
1430
+ };
1431
+ if (hasUnverifiedActivity(snapshot)) {
1432
+ // A restored Goal still needs verified work evidence. Let Pi finish binding while it arrives.
1433
+ void publishSnapshot(ctx, true, "connect").then(resumeIfIdle);
1434
+ } else resumeIfIdle(snapshot);
1310
1435
  }
1311
1436
  });
1312
1437
 
1313
1438
  pi.on("ui_prompt_start", () => { uiPromptDepth += 1; });
1439
+ pi.on("session_tree", async (_event, ctx) => {
1440
+ executionGeneration += 1;
1441
+ clearIdleContinuation();
1442
+ backgroundDrainTracker = null;
1443
+ continuationQueuedFor = null;
1444
+ providerCache.clear();
1445
+ currentCtx = ctx;
1446
+ await publishSnapshot(ctx);
1447
+ syncPollingState();
1448
+ });
1314
1449
  pi.on("ui_prompt_end", () => { uiPromptDepth = Math.max(0, uiPromptDepth - 1); });
1315
1450
 
1316
1451
  pi.on("input", async (event, ctx) => {
@@ -1396,7 +1531,7 @@ export default function (pi: ExtensionAPI): void {
1396
1531
  `${pausedInstruction}\n` + "While the goal is paused, this overrides the workflow instructions below: do not advance the workflow until the goal is resumed.\n\n",
1397
1532
  `Active workflow: ${owner.name} (${owner.path}). Its task plan owns planning and the parent is a coordinator, not a product-code implementer. Follow the workflow instructions below, including on resumed turns:\n\n${instructions}`,
1398
1533
  isPokeable(goal) && (harnessPresent
1399
- ? "Complete the goal only after the workflow completion audit."
1534
+ ? "Complete the goal only after the workflow completion audit and verification of every accepted Outcome criterion."
1400
1535
  : `Active objective: ${goal.objective}. Complete it only after the workflow completion audit.`),
1401
1536
  questionInstruction && questionInstruction.trim(),
1402
1537
  heldInstruction,
@@ -1404,7 +1539,9 @@ export default function (pi: ExtensionAPI): void {
1404
1539
  }
1405
1540
 
1406
1541
  if (!isPokeable(goal)) return;
1407
- const backgroundInstruction = snapshot.backgroundRunning
1542
+ const backgroundInstruction = hasUnverifiedActivity(snapshot)
1543
+ ? " Background activity is unverified. Do not infer completion or drained work from missing activity; inspect a verified observation before completing the goal."
1544
+ : snapshot.backgroundRunning
1408
1545
  ? ` The goal still has delegated background work running (${summarizeActiveBackground(snapshot)}). Foreground idleness alone is not goal completion; keep any structured plan current and do not mark verification, the plan, or the goal complete until every relevant delegated task reaches a terminal state and its result or failure has been inspected and integrated.`
1409
1546
  : "";
1410
1547
  if (harnessPresent) {
@@ -1523,7 +1660,7 @@ export default function (pi: ExtensionAPI): void {
1523
1660
  const snapshot = await publishSnapshot(ctx);
1524
1661
  if (!snapshot) return;
1525
1662
  const goal = getGoal(ctx);
1526
- if (!isPokeable(goal) || snapshot.backgroundRunning) {
1663
+ if (!isPokeable(goal) || snapshot.backgroundRunning || hasUnverifiedActivity(snapshot)) {
1527
1664
  return;
1528
1665
  }
1529
1666
  // A run the scheduler says is only waiting (a retry is due at a known time) is not stuck: wake at
@@ -1564,6 +1701,7 @@ export default function (pi: ExtensionAPI): void {
1564
1701
  updatedAt: Math.floor(now / 1000),
1565
1702
  });
1566
1703
  if (blocked) {
1704
+ syncPollingState();
1567
1705
  refreshGoalWidget?.();
1568
1706
  if (ctx.hasUI) {
1569
1707
  ctx.ui.notify(
@@ -1612,6 +1750,11 @@ export default function (pi: ExtensionAPI): void {
1612
1750
  terminalInputIsEditor = undefined;
1613
1751
  uiPromptDepth = 0;
1614
1752
  stopPolling();
1753
+ if (providerDeadline) clearTimeout(providerDeadline);
1754
+ providerDeadline = undefined;
1755
+ for (const off of providerUnsubscribers.values()) off();
1756
+ providerUnsubscribers.clear();
1757
+ providerCache.clear();
1615
1758
  foregroundRunning = false;
1616
1759
  pendingQuestions.clear();
1617
1760
  clearIdleContinuation();
@@ -3,7 +3,7 @@ import type {ExtensionContext} from '@earendil-works/pi-coding-agent';
3
3
  export const OPERATION_RESUME_ADMISSION='pi-better-goal:operation-resume-admission';
4
4
  export interface OperationResumeOwner {sessionId:string;workspace:string;branchId?:string|null;goalId?:string|null}
5
5
  export interface OperationResumeGate {allowed:boolean;reason?:string;revision:number;isCurrent?:()=>boolean}
6
- export interface OperationResumeRequest {version:1;owner:OperationResumeOwner;reply:(gate:OperationResumeGate)=>void}
6
+ export interface OperationResumeRequest {version:1;owner:OperationResumeOwner;pending?:()=>void;reply:(gate:OperationResumeGate)=>void}
7
7
 
8
8
  /** A recorded branch anchor remains valid on descendants, not on an abandoned fork. */
9
9
  export function operationOwnerMatches(ctx:ExtensionContext|undefined,owner:OperationResumeOwner):boolean {
@@ -1,6 +1,16 @@
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
+ import { AssignmentInbox } from "./assignment-inbox.mjs";
4
+ import { pathToFileURL } from "node:url";
5
+
6
+ // Only first-party source SQL passes this facade; quoted values stay untouched.
7
+ const sourceTables = new Set(["schema_meta", "sqlite_master", "sqlite_schema", "assignment_change_source", "assignment_changes",
8
+ "waits", "wait_dependencies", "resume_claims", "operations", "coordinator_state", "assignment_outcomes",
9
+ "subagent_launch_intents", "background_input_versions", "background_parent_callbacks", "assignments", "assignment_bindings", "assignment_attempts"]);
10
+ function sourceSQL(sql) {
11
+ if (/^PRAGMA\s+data_version\s*$/i.test(sql)) return "PRAGMA coordinator_source.data_version";
12
+ return sql.replace(/'(?:''|[^'])*'|\b[A-Za-z_][A-Za-z_0-9]*\b/g, token => sourceTables.has(token) ? `coordinator_source.${token}` : token);
13
+ }
4
14
 
5
15
  /** Read-only, bounded projection input. Never creates/migrates a database. */
6
16
  export function readAssignmentWaits(path, owner, connection) {
@@ -44,42 +54,63 @@ export function readAssignmentWaits(path, owner, connection) {
44
54
  }
45
55
 
46
56
  /** A root read model owns this connection; ordinary observers remain one-shot. */
47
- export function createAssignmentReader(path) {
57
+ export function createAssignmentReader(path, inboxPath = ":memory:", derivedConnection, options = {}) {
58
+ const inbox = new AssignmentInbox(inboxPath, derivedConnection);
48
59
  let db;
49
60
  let identity;
50
61
  let snapshot = false;
62
+ const composed = options.composed === true;
63
+ const owner = derivedConnection;
64
+ const dropSource = () => {
65
+ if (composed) { if (db) owner.exec("DETACH DATABASE coordinator_source"); }
66
+ else db?.close();
67
+ db = undefined; statements.clear();
68
+ };
51
69
  const statements = new Map();
52
- return {
70
+ const reader = {
53
71
  revision() {
54
72
  const { statSync } = createRequire(import.meta.url)("node:fs");
55
73
  const stat = statSync(path, { bigint: true });
56
74
  const next = `${stat.dev}:${stat.ino}`;
57
75
  if (identity !== next) {
58
76
  if (snapshot) throw new Error("Coordinator identity changed during observation");
59
- db?.close();
60
- db = undefined;
61
- statements.clear();
77
+ dropSource();
62
78
  identity = next;
63
79
  }
64
80
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
65
- db ??= new DatabaseSync(path, { readOnly: true });
81
+ if (!db) {
82
+ if (composed) {
83
+ const uri = pathToFileURL(path); uri.searchParams.set("mode", "ro");
84
+ owner.prepare("ATTACH DATABASE ? AS coordinator_source").run(uri.href);
85
+ db = { prepare: sql => owner.prepare(sourceSQL(sql)), get observationActive() { return snapshot; }, beginSnapshot: () => reader.beginSnapshot() };
86
+ } else db = new DatabaseSync(path, { readOnly: true });
87
+ }
66
88
  return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
67
89
  },
68
90
  connection(refresh = true) { if (refresh) this.revision(); return db; },
91
+ changes() { this.revision(); return inbox.receive(db, identity); },
92
+ acknowledgeChanges(batch, complete) { inbox.acknowledge(batch, complete); },
93
+ get changeMetrics() { return inbox.metrics; },
94
+ get snapshotActive() { return snapshot; },
69
95
 
70
96
  beginSnapshot() {
71
97
  this.revision();
72
98
  if (snapshot) throw new Error("Coordinator snapshot already open");
73
- db.exec("BEGIN");
99
+ const transaction = composed ? owner : db;
100
+ transaction.exec("BEGIN");
74
101
  snapshot = true;
75
102
  const release = () => {
76
103
  if (!snapshot) return;
77
- try { db.exec("ROLLBACK"); } finally { snapshot = false; }
104
+ try { transaction.exec("ROLLBACK"); } finally { snapshot = false; }
78
105
  };
79
106
  try {
80
107
  // Pin the WAL read view before recording its revision; other writers keep advancing.
81
108
  db.prepare("SELECT count(*) FROM sqlite_schema").get();
82
- return { revision: this.revision(), release };
109
+ return { revision: this.revision(), release, commit: () => {
110
+ if (!snapshot) return;
111
+ transaction.exec("COMMIT");
112
+ snapshot = false;
113
+ } };
83
114
  } catch (error) { release(); throw error; }
84
115
  },
85
116
 
@@ -94,30 +125,6 @@ export function createAssignmentReader(path) {
94
125
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
95
126
  }
96
127
  },
97
- conversationRevisions() {
98
- try {
99
- this.revision();
100
- if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
101
- const hashes = new Map();
102
- const add = (sessionId, workspace, value) => {
103
- const key = JSON.stringify([sessionId, workspace]);
104
- if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
105
- hashes.get(key).update(JSON.stringify(value));
106
- };
107
- // One source pass per changed database revision, instead of one
108
- // projection/query/log parse for every historical attempt.
109
- for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
110
- FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
111
- FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
112
- add(row.owner_session_id, row.owner_workspace, row);
113
- }
114
- for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
115
- const record = JSON.parse(row.record_json);
116
- add(record.owner.sessionId, record.owner.workspace, record);
117
- }
118
- return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
119
- } catch { return undefined; }
120
- },
121
128
  upgradeObligations() {
122
129
  try { this.revision(); } catch (error) {
123
130
  if (error.code === "ENOENT") return [];
@@ -144,7 +151,8 @@ export function createAssignmentReader(path) {
144
151
  return [...obligations, ...reasons];
145
152
  },
146
153
 
147
- close() { if (snapshot) { db.exec("ROLLBACK"); snapshot = false; } db?.close(); db = undefined; statements.clear(); identity = undefined; },
154
+ close() { if (snapshot) { (composed ? owner : db).exec("ROLLBACK"); snapshot = false; } dropSource(); identity = undefined; inbox.close(); },
148
155
 
149
156
  };
157
+ return reader;
150
158
  }
@@ -9,7 +9,8 @@ export const NAVIGATOR_ENTRY_TYPE = "pi-better-harness-navigator-panels";
9
9
  export const NAVIGATOR_STICKY_SETTING_ID = "navigator-sticky";
10
10
  type MouseEvent = { type: string; button: string; x: number; y: number; width: number; shift?: boolean; alt?: boolean; ctrl?: boolean };
11
11
  type PanelComponent = Component & { dispose?(): void; handleMouse?(event: MouseEvent): { handled: true; render: boolean } | undefined };
12
- export type NavigatorPanelFactory = (tui: TUI, theme: Theme) => PanelComponent;
12
+ export type NavigatorPanelLayout = { availableRows(): number };
13
+ export type NavigatorPanelFactory = (tui: TUI, theme: Theme, layout: NavigatorPanelLayout) => PanelComponent;
13
14
  type Panel = { factory: NavigatorPanelFactory; component?: PanelComponent | undefined };
14
15
  type Preference = { version: 1; sticky: boolean };
15
16
  type Owner = { pi: ExtensionAPI; stop?: (() => void) | undefined };
@@ -23,6 +24,8 @@ type State = {
23
24
  mounted: boolean;
24
25
  tui?: TUI | undefined;
25
26
  theme?: Theme | undefined;
27
+ host?: Component | undefined;
28
+ availableRows?: number | undefined;
26
29
  anchor?: string | undefined;
27
30
  pendingAnchor: boolean;
28
31
  generation: number;
@@ -61,14 +64,30 @@ function orderedPanels(s: State): Panel[] {
61
64
  }
62
65
  function buildPanels(s: State): void {
63
66
  if (!s.tui || !s.theme) return;
64
- for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme);
67
+ for (const panel of orderedPanels(s)) panel.component ??= panel.factory(s.tui, s.theme, { availableRows: () => s.availableRows ?? Infinity });
68
+ }
69
+ // Count the editor, footer and other siblings following the host in regular mode.
70
+ // Never render ancestors here: they contain this host and would recurse.
71
+ function rowsAfter(root: object, target: Component, width: number): number | undefined {
72
+ if (root === target) return 0;
73
+ const children = (root as Component & { children?: Component[] }).children;
74
+ if (!children) return undefined;
75
+ for (let i = children.length - 1; i >= 0; i--) {
76
+ const after = rowsAfter(children[i]!, target, width);
77
+ if (after !== undefined) return after + children.slice(i + 1).reduce((sum, child) => sum + child.render(width).length, 0);
78
+ }
79
+ return undefined;
65
80
  }
66
81
  function renderPanels(s: State, width: number): string[] {
67
82
  buildPanels(s);
68
83
  const lines: string[] = [];
69
84
  s.ranges = [];
85
+ const after = s.sticky && s.tui && s.host ? rowsAfter(s.tui, s.host, width) : undefined;
86
+ const height = s.tui?.terminal?.rows;
87
+ const budget = after !== undefined && height ? Math.max(0, height - after) : Infinity;
70
88
  for (const panel of orderedPanels(s)) {
71
89
  if (!panel.component) continue;
90
+ s.availableRows = Math.max(0, budget - lines.length);
72
91
  const rendered = panel.component.render(width);
73
92
  s.ranges.push({ start: lines.length, end: lines.length + rendered.length, component: panel.component });
74
93
  lines.push(...rendered);
@@ -115,6 +134,7 @@ function clearHost(s: State): void {
115
134
  disposePanels(s);
116
135
  s.mounted = false;
117
136
  s.tui = undefined;
137
+ s.host = undefined;
118
138
  s.theme = undefined;
119
139
  }
120
140
  function adoptContext(s: State, ctx: ExtensionContext): void {
@@ -134,7 +154,7 @@ function mountHost(s: State): void {
134
154
  s.tui = tui;
135
155
  s.theme = theme;
136
156
  buildPanels(s);
137
- return {
157
+ const host: PanelComponent = {
138
158
  render(width: number) {
139
159
  const lines = renderPanels(s, width);
140
160
  if (s.sticky) return lines;
@@ -147,6 +167,8 @@ function mountHost(s: State): void {
147
167
  },
148
168
  dispose() { disposePanels(s); s.mounted = false; },
149
169
  };
170
+ s.host = host;
171
+ return host;
150
172
  }, { placement: "aboveEditor" });
151
173
  }
152
174
  function changeSticky(value: string, ctx: ExtensionContext): void {
@@ -247,4 +269,4 @@ export function __resetNavigatorPanelsForTests(): void {
247
269
  s.anchor = undefined;
248
270
  s.sticky = true;
249
271
  s.control = undefined;
250
- }
272
+ }
@@ -4,12 +4,13 @@ import type { GoalSnapshot } from "./types.js";
4
4
  /** Synchronous request bus shared with an installed `pi-better-harness` runtime. */
5
5
  export const TASK_CONTEXT_EVENT = "pi-better-harness:task-context";
6
6
 
7
- export type TaskContextAction = "inspect" | "start" | "bind" | "pause" | "resume" | "complete";
7
+ export type TaskContextAction = "inspect" | "audit" | "start" | "bind" | "pause" | "resume" | "complete";
8
8
 
9
9
  export const OUTCOME_ACCEPTED_EVENT = "pi-better-harness:outcome-accepted";
10
10
 
11
11
  export interface OutcomeAcceptedEvent {
12
12
  sessionId: string;
13
+ reopenedGoalId?: string;
13
14
  outcome: {
14
15
  objective: string;
15
16
  doneWhen?: readonly string[];
@@ -19,13 +20,15 @@ export interface OutcomeAcceptedEvent {
19
20
  }
20
21
 
21
22
  /** Only explicit, actionable outcomes qualify; prose and restored state do not. */
22
- export function canStartGoalFromOutcome(value: unknown): value is OutcomeAcceptedEvent["outcome"] {
23
+ export function canStartGoalFromOutcome(value: unknown, reopenedGoal?: Pick<GoalSnapshot, "objective" | "command">): value is OutcomeAcceptedEvent["outcome"] {
23
24
  if (!value || typeof value !== "object") return false;
24
25
  const outcome = value as Partial<OutcomeAcceptedEvent["outcome"]>;
26
+ const objective = typeof outcome.objective === "string" ? outcome.objective.trim() : "";
27
+ const retainsCommand = reopenedGoal?.command && reopenedGoal.objective.trim() === objective;
25
28
  return outcome.status === "active" && outcome.goalId === undefined &&
26
- typeof outcome.objective === "string" && !!outcome.objective.trim() && !outcome.objective.trim().startsWith("/") &&
27
- Array.isArray(outcome.doneWhen) && outcome.doneWhen.length > 0 &&
28
- outcome.doneWhen.every(item => typeof item === "string" && !!item.trim());
29
+ !!objective && (!objective.startsWith("/") || !!retainsCommand) &&
30
+ (reopenedGoal !== undefined || (Array.isArray(outcome.doneWhen) && outcome.doneWhen.length > 0 &&
31
+ outcome.doneWhen.every(item => typeof item === "string" && !!item.trim())));
29
32
  }
30
33
 
31
34
  /**
@@ -35,10 +38,13 @@ export function canStartGoalFromOutcome(value: unknown): value is OutcomeAccepte
35
38
  */
36
39
  export interface TaskContextRequest {
37
40
  action: TaskContextAction;
41
+ doneWhen?: readonly string[];
42
+ openSteps?: readonly string[];
43
+ ledgerBlocker?: string;
38
44
  goalId?: string;
39
45
  /** Current widget width on a visual ownership inspection. */
40
46
  width?: number;
41
- /** The raw original goal trigger; only start/bind requests carry it. */
47
+ /** The raw original goal trigger; returned as the refined objective on audit. */
42
48
  objective?: string;
43
49
  /** Hooks authority: a present Harness runtime sets this even when Outcome & Todo is off. */
44
50
  enabled?: boolean;
package/src/types.ts CHANGED
@@ -12,6 +12,7 @@ export const EVENT_TERMINAL_ATTENTION = "pi-better-goal:terminal-attention";
12
12
  export type ActivityCategory =
13
13
  | "foreground-running"
14
14
  | "background-running"
15
+ | "unverified"
15
16
  | "idle-waiting"
16
17
  | "complete";
17
18
 
@@ -40,19 +41,29 @@ export interface BackgroundWorkItem {
40
41
 
41
42
  export interface BackgroundProviderSnapshot {
42
43
  providerId: string;
44
+ /** Omitted by legacy providers; unverified observations cannot prove drain. */
45
+ coverage?: "verified" | "unverified";
43
46
  label?: string;
44
47
  items: BackgroundWorkItem[];
48
+ /** Absolute milliseconds; null means no time-dependent change is owed. */
49
+ nextDeadline?: number | null;
50
+ /** Legacy providers cost at most one collection per compatibility interval. */
51
+ compatibilityIntervalMs?: number;
45
52
  }
46
53
 
47
54
  export interface BackgroundActivityProvider {
48
55
  id: string;
56
+ /** v1 requires notifications and an explicit nextDeadline (including null). */
57
+ activityVersion?: 1;
49
58
  label?: string;
50
- getActivity(ctx: ExtensionContext): BackgroundProviderSnapshot | Promise<BackgroundProviderSnapshot>;
51
- onActivityChanged?(notify: () => void): () => void;
59
+ /** Passive foreground updates can use existing subscriptions without opening a connection. */
60
+ getActivity(ctx: ExtensionContext, options?: { cachedOnly?: boolean }): BackgroundProviderSnapshot | Promise<BackgroundProviderSnapshot>;
61
+ onActivityChanged?(notify: () => void, ctx?: ExtensionContext): () => void;
52
62
  }
53
63
 
54
64
  export interface ActivitySnapshot {
55
65
  version: 1;
66
+ coverage?: "verified" | "unverified";
56
67
  category: ActivityCategory;
57
68
  foregroundRunning: boolean;
58
69
  backgroundRunning: boolean;