pi-better-background-tasks 0.15.4 → 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.
Files changed (38) hide show
  1. package/README.md +13 -0
  2. package/package.json +5 -2
  3. package/runtime-client/artifacts/darwin-arm64.gz +0 -0
  4. package/runtime-client/artifacts/darwin-arm64.json +1 -0
  5. package/runtime-client/artifacts/darwin-x64.gz +0 -0
  6. package/runtime-client/artifacts/darwin-x64.json +1 -0
  7. package/runtime-client/artifacts/linux-arm64.gz +0 -0
  8. package/runtime-client/artifacts/linux-arm64.json +1 -0
  9. package/runtime-client/artifacts/linux-x64.gz +0 -0
  10. package/runtime-client/artifacts/linux-x64.json +1 -0
  11. package/runtime-client/scripts/private-runtime/format.mjs +90 -0
  12. package/runtime-client/src/daemon-owner.mjs +217 -0
  13. package/runtime-client/src/runtime/client.mjs +130 -0
  14. package/runtime-client/src/runtime/root.mjs +41 -0
  15. package/runtime-client/src/runtime/socket.mjs +9 -0
  16. package/runtime-client/src/runtime/status-cli.mjs +14 -0
  17. package/runtime-client/src/runtime/work-client.mjs +88 -0
  18. package/runtime-client/src/startup/artifact.mjs +76 -0
  19. package/runtime-client/src/startup/install.mjs +184 -0
  20. package/runtime-client/src/startup/managed-types.mjs +1 -0
  21. package/runtime-client/src/startup/runtime.mjs +120 -0
  22. package/src/goal-provider.ts +11 -7
  23. package/src/index.ts +3 -0
  24. package/src/observed-waits.ts +88 -26
  25. package/src/output.ts +16 -13
  26. package/src/registry.ts +15 -0
  27. package/src/shared-harness-settings.ts +4 -2
  28. package/src/shared-log-utils.ts +18 -7
  29. package/src/shared-navigator.ts +16 -4
  30. package/src/shared-operation-coordinator/assignment-observation.mjs +63 -3
  31. package/src/shared-operation-coordinator/index.ts +2 -0
  32. package/src/shared-operation-coordinator/src/errors.ts +2 -0
  33. package/src/shared-operation-coordinator/src/schema.ts +20 -0
  34. package/src/shared-operation-coordinator/src/store.ts +35 -0
  35. package/src/shared-operation-coordinator/src/task-cancellation.ts +224 -0
  36. package/src/shared-work-client.mjs +88 -0
  37. package/src/tools.ts +28 -23
  38. package/src/work-observation.ts +117 -0
@@ -49,6 +49,7 @@ import {
49
49
  } from "./sandbox.js";
50
50
  import {
51
51
  openStore,
52
+ cancellationCredential,
52
53
  type AcknowledgeDisposition,
53
54
  type EvidenceKind,
54
55
  type OperationEvidenceRecord,
@@ -835,6 +836,20 @@ function mapEvidence(
835
836
  }));
836
837
  }
837
838
 
839
+ /** Shared terminal publication contract for the host and fixed server cancel adapter. */
840
+ export function supervisorTerminalPublication(operation: OperationRecord, inspection: SupervisorInspection, refs = evidenceFor(inspection)) {
841
+ const status = inspection.status;
842
+ const outcome = terminalOutcome(status);
843
+ return {
844
+ operationId: operation.operationId,
845
+ eventId: `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`,
846
+ outcome, owner: operation.owner,
847
+ evidence: refs.map(ref => ({ kind: ref.kind, ref: ref.ref, ...(ref.summary ? { summary: ref.summary } : {}), detailLost: ref.detailLost })),
848
+ ...(outcome === "lost" ? { detailLost: true } : {}),
849
+ reason: inspection.result ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}` : "supervisor lost: no terminal evidence",
850
+ };
851
+ }
852
+
838
853
  export class ObservedWaitHost {
839
854
  readonly service: BackgroundOperationService;
840
855
  private store?: Store;
@@ -880,6 +895,7 @@ export class ObservedWaitHost {
880
895
  private continuation?: ContinuationAdapter;
881
896
  private continuationError?: string;
882
897
  private readonly launches = new Map<string, LaunchContext>();
898
+ private readonly localCancels = new Set<string>();
883
899
  private readonly rpcRuns = new Map<string, RpcRunBinding>();
884
900
  private readonly waitOwners = new Map<string, OwnerIdentity>();
885
901
  private readonly stagedCheckpoints = new Map<string, { evidence: JsonRecord; toolCallId: string; checkpointRecorded: boolean }>();
@@ -1470,11 +1486,68 @@ export class ObservedWaitHost {
1470
1486
  return this.log(taskId, this.ownerFor(ctx), options);
1471
1487
  }
1472
1488
 
1473
- async stopForParent(ctx: ExtensionContext, taskId: string): Promise<StatusView> {
1489
+ async stopForParent(ctx: ExtensionContext, taskId: string, requestId?: string): Promise<StatusView> {
1474
1490
  this.noteParentContext(ctx);
1491
+ if (requestId) {
1492
+ try { return await this.stopThroughRuntime(ctx, taskId, requestId); }
1493
+ catch (error) {
1494
+ if (/not_accepted|accepted:|outcome_unknown/.test(String(error))) throw error;
1495
+ throw new Error(`not_accepted: ${String(error)}`);
1496
+ }
1497
+ }
1475
1498
  return this.stop(taskId, this.ownerFor(ctx));
1476
1499
  }
1477
1500
 
1501
+ /** Called from an actual admitted parent tool context, not a wire owner claim. */
1502
+ authorizeCancellationForParent(ctx: ExtensionContext, taskId: string, requestId: string): string {
1503
+ if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation admission is still draining");
1504
+ const operation = this.ownedOperation(taskId, this.ownerFor(ctx));
1505
+ if (this.supervisionAuthority(operation) === "foreign") throw new Error("permission-unavailable: live legacy or unknown supervisor prevents cancellation handoff");
1506
+ const proof = cancellationCredential();
1507
+ const previous = this.requireStore().getTaskCancellation({ owner: operation.owner, idempotencyKey: requestId });
1508
+ if (previous && previous.operationId !== operation.operationId) throw new Error("not_accepted: request-conflict: cancellation key belongs to another task");
1509
+ this.requireStore().admitTaskCancellation({ credentialHash: proof.hash, directory: this.directory, request: previous ?? {
1510
+ owner: operation.owner, idempotencyKey: requestId, operationId: operation.operationId,
1511
+ expectedLaunchToken: operation.launchToken, expectedTerminalRevision: operation.terminalRevision,
1512
+ expectedHostId: operation.supervision?.hostId ?? "unavailable", reason: "explicit stop",
1513
+ } });
1514
+ return proof.credential;
1515
+ }
1516
+
1517
+ private async stopThroughRuntime(ctx: ExtensionContext, taskId: string, requestId: string): Promise<StatusView> {
1518
+ this.ownedOperation(taskId, this.ownerFor(ctx));
1519
+ const root = realpathSync(dirname(this.storePath));
1520
+ const registrationPath = join(root, "server-registration-v1.json");
1521
+ if (!existsSync(registrationPath)) {
1522
+ const installer = "../runtime-client/src/runtime/client.mjs";
1523
+ await (await import(installer)).ensureRuntime({ agentDir: root });
1524
+ }
1525
+ const registration = JSON.parse(readFileSync(registrationPath, "utf8"));
1526
+ if (registration.agentDir !== root || registration.version !== 1) throw new Error("not_accepted: invalid canonical runtime registration");
1527
+ const module = "./shared-work-client.mjs";
1528
+ const { WorkClient } = await import(module);
1529
+ const client = new WorkClient(join(registration.serverDir, "pi-server.sock"), root, ["runtime-cancellation-v1"]);
1530
+ let submitted = false;
1531
+ try {
1532
+ await client.ready;
1533
+ await client.request("runtime_cancellation_status");
1534
+ const credential = this.authorizeCancellationForParent(ctx, taskId, requestId);
1535
+ const previous = await client.request("runtime_query_cancellation", { credential });
1536
+ let receipt = previous;
1537
+ if (previous.state === "not_accepted") {
1538
+ submitted = true;
1539
+ receipt = await client.request("runtime_cancel_task", { credential });
1540
+ }
1541
+ if (receipt.state === "outcome_unknown" || !receipt.result) throw new Error(`${receipt.state}: cancellation ${requestId}; query the same request before retrying`);
1542
+ return this.statusForParent(ctx, taskId);
1543
+ } catch (error) {
1544
+ const message = String(error);
1545
+ if (/not_accepted|accepted:|outcome_unknown/.test(message)) throw error;
1546
+ if (!submitted) throw new Error(`not_accepted: cancellation ${requestId}: ${message}`);
1547
+ throw new Error(`outcome_unknown: cancellation ${requestId}; reconnect and query the same request before retrying: ${message}`);
1548
+ } finally { client.close(); }
1549
+ }
1550
+
1478
1551
  // ---- read-only projections for list, navigator and Goal -----------------
1479
1552
 
1480
1553
  /**
@@ -1794,14 +1867,19 @@ export class ObservedWaitHost {
1794
1867
  private async stop(taskId: string, owner: OwnerIdentity): Promise<StatusView> {
1795
1868
  const store = this.requireStore();
1796
1869
  const operation = this.ownedOperation(taskId, owner);
1797
- const result = await this.supervisor.stop(taskId);
1798
- const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1799
- this.reconcileInspection(operation, inspection);
1800
- const current = store.getOperation(operation.operationId) ?? operation;
1801
- if (current.terminalRevision === 0 && inspection?.terminal) {
1802
- this.recordTerminal(current, inspection);
1803
- }
1804
- return this.status(taskId, owner);
1870
+ if (store.taskCancellationManaged(operation.operationId)) throw new Error("not_accepted: cancellation admission transferred to server; use the registered stop tool with the original request_id");
1871
+ if (this.localCancels.has(taskId)) throw new Error("not_accepted: old cancellation is already in flight");
1872
+ this.localCancels.add(taskId);
1873
+ try {
1874
+ const result = await this.supervisor.stop(taskId, { token: operation.launchToken });
1875
+ const inspection = result?.inspection ?? this.supervisor.inspect(taskId);
1876
+ this.reconcileInspection(operation, inspection);
1877
+ const current = store.getOperation(operation.operationId) ?? operation;
1878
+ if (current.terminalRevision === 0 && inspection?.terminal) {
1879
+ this.recordTerminal(current, inspection);
1880
+ }
1881
+ return this.status(taskId, owner);
1882
+ } finally { this.localCancels.delete(taskId); }
1805
1883
  }
1806
1884
 
1807
1885
  formatStatus(view: StatusView): string {
@@ -3003,26 +3081,10 @@ export class ObservedWaitHost {
3003
3081
  const store = this.requireStore();
3004
3082
  const status = inspection.status;
3005
3083
  const outcome = terminalOutcome(status);
3006
- const eventId = `${operation.taskId}:${inspection.result?.endedAt ?? inspection.lost?.recordedAt ?? inspection.observedAt}:${status}`;
3007
3084
  const refs = evidenceFor(inspection);
3008
3085
  let recorded;
3009
3086
  try {
3010
- recorded = store.recordTerminalOutcome({
3011
- operationId: operation.operationId,
3012
- eventId,
3013
- outcome,
3014
- owner: operation.owner,
3015
- evidence: refs.map((ref) => ({
3016
- kind: ref.kind,
3017
- ref: ref.ref,
3018
- ...(ref.summary ? { summary: ref.summary } : {}),
3019
- detailLost: ref.detailLost,
3020
- })),
3021
- ...(outcome === "lost" ? { detailLost: true } : {}),
3022
- reason: inspection.result
3023
- ? `supervisor ${status} exit=${inspection.result.exitCode ?? "null"}`
3024
- : "supervisor lost: no terminal evidence",
3025
- });
3087
+ recorded = store.recordTerminalOutcome(supervisorTerminalPublication(operation, inspection, refs));
3026
3088
  } catch (error) {
3027
3089
  // A timer and a tool call can observe the same terminal record. The store
3028
3090
  // keeps the first revision; a replay is never a second execution.
package/src/output.ts CHANGED
@@ -133,7 +133,7 @@ function stringifyObserved(value: unknown): string {
133
133
 
134
134
  /** Cursor scope: pagination and revision cursors never cross session scopes. */
135
135
  function scopeKey(options: OutputOptions): string {
136
- return sessionScopeKey({ all: options.all, unavailable: options.sessionUnavailable, origin: options.origin });
136
+ return sessionScopeKey({ all: options.all, unavailable: options.sessionUnavailable, origin: options.origin, processId: process.pid });
137
137
  }
138
138
 
139
139
  function taskGaps(meta: BackgroundTaskMeta): EvidenceGap[] {
@@ -810,11 +810,11 @@ function compactRow(meta: BackgroundTaskMeta, incidents: number): string {
810
810
  const remote = meta.ssh ? ` ${oneLine(meta.ssh.target, 60)}${meta.remote?.session ? ` ${meta.remote.session}` : ""}` : "";
811
811
  const incident = incidents > 0 ? ` · ${incidents} incident${incidents === 1 ? "" : "s"}` : "";
812
812
  const label = meta.name ? ` ${oneLine(meta.name, 60)}` : "";
813
- return `${meta.id} ${meta.status} ${meta.kind} ${age}${incident}${remote}${label}`;
813
+ const waits = (meta as BackgroundTaskMeta & { waits?: unknown[] }).waits?.length;
814
+ return `${meta.id} ${meta.status} ${meta.kind} ${age}${incident}${remote}${label}${waits ? ` waits=${waits}` : ""}`;
814
815
  }
815
816
 
816
- export function formatList(options: OutputOptions = {}): string {
817
- const index = listTaskRecords();
817
+ export function formatList(options: OutputOptions = {}, index = listTaskRecords()): string {
818
818
  if (index.indexError) {
819
819
  return assembleBackgroundContent({
820
820
  surface: "list",
@@ -838,8 +838,8 @@ export function formatList(options: OutputOptions = {}): string {
838
838
  });
839
839
  }
840
840
  const wanted = options.statuses && options.statuses.length > 0 ? new Set(options.statuses) : undefined;
841
- let unreadable = 0;
842
- let unknown = 0;
841
+ let unreadable = index.page?.unreadable ?? 0;
842
+ let unknown = index.page?.unknown ?? 0;
843
843
  const allowed: BackgroundTaskMeta[] = [];
844
844
  for (const record of index.records) {
845
845
  if (!record.meta) {
@@ -848,7 +848,8 @@ export function formatList(options: OutputOptions = {}): string {
848
848
  }
849
849
  const ownership = classifyOwnership(record.meta, options);
850
850
  if (ownership === "allow") {
851
- if (!wanted || wanted.has(record.meta.status)) allowed.push(record.meta);
851
+ if (!wanted || wanted.has(record.meta.status) || wanted.has("running") && (record.meta as BackgroundTaskMeta & { durable?: boolean; active?: boolean }).durable
852
+ && (record.meta as BackgroundTaskMeta & { active?: boolean }).active) allowed.push(record.meta);
852
853
  } else if (ownership === "unknown") {
853
854
  unknown += 1;
854
855
  }
@@ -857,12 +858,13 @@ export function formatList(options: OutputOptions = {}): string {
857
858
  const statusesKey = [...(options.statuses ?? [])].sort().join(",");
858
859
  const resource = `list:${scope}:${statusesKey}`;
859
860
  const limit = Math.max(1, Math.min(Math.floor(options.limit ?? DEFAULT_LIST_ENTRIES), MAX_LIST_ENTRIES));
861
+ const total = index.page?.total ?? allowed.length;
860
862
  const states = new Map(allowed.map((meta) => [meta.id, failureStateFor(meta.id)] as const));
861
863
  const incidentsOf = (id: string) => actionableFailures(states.get(id)!).length;
862
864
  const revision = inspectStatusRevision({
863
865
  resource,
864
- contentRevision: revisionOf(allowed.map((meta) => [meta.id, meta.status, meta.endedAt ?? null])),
865
- failureRevision: revisionOf(allowed.map((meta) => [meta.id, failureRevision(states.get(meta.id)!)])),
866
+ contentRevision: index.page?.contentRevision ?? revisionOf(allowed.map((meta) => [meta.id, meta.status, meta.endedAt ?? null])),
867
+ failureRevision: revisionOf([index.page?.failureRevision, allowed.map((meta) => [meta.id, failureRevision(states.get(meta.id)!)])]),
866
868
  cursor: cursorKind(options.cursor) === "s" ? options.cursor : undefined,
867
869
  });
868
870
  const scopeLabel = options.all ? "all sessions" : "current session";
@@ -871,7 +873,7 @@ export function formatList(options: OutputOptions = {}): string {
871
873
  surface: "list",
872
874
  maxBytes: options.maxBytes,
873
875
  sections: {
874
- identity: `${allowed.length} background task${allowed.length === 1 ? "" : "s"} (${scopeLabel}) · unchanged`,
876
+ identity: `${total} background task${total === 1 ? "" : "s"} (${scopeLabel}) · unchanged`,
875
877
  decision: formatUnchangedEvidence(options.cursor),
876
878
  },
877
879
  statusCursor: revision.nextCursor,
@@ -884,7 +886,7 @@ export function formatList(options: OutputOptions = {}): string {
884
886
  const listFailure = (budget: number): string | undefined => {
885
887
  const newest = failing[0];
886
888
  if (!newest) return undefined;
887
- const count = `${withIncidents} task${withIncidents === 1 ? "" : "s"} with unresolved incidents; newest ${newest.id} has ${incidentsOf(newest.id)}. Full incidents: bg_task_status id=${newest.id}.`;
889
+ const count = `${withIncidents} task${withIncidents === 1 ? "" : "s"}${index.page ? " on this page" : ""} with unresolved incidents; newest ${newest.id} has ${incidentsOf(newest.id)}. Full incidents: bg_task_status id=${newest.id}.`;
888
890
  const top = formatFailureLines(states.get(newest.id)!)[0] ?? "";
889
891
  // The lead-in is a pointer, not the incident page: at most a short preview.
890
892
  const room = Math.min(LIST_LEAD_PREVIEW_BYTES, budget - utf8ByteLength(count) - 1);
@@ -908,9 +910,9 @@ export function formatList(options: OutputOptions = {}): string {
908
910
  sections: {
909
911
  identity: options.sessionUnavailable && !options.all
910
912
  ? "Current session identity is unavailable; task ownership cannot be verified."
911
- : allowed.length === 0
913
+ : total === 0
912
914
  ? `No background tasks found (${scopeLabel}).`
913
- : `${allowed.length} background task${allowed.length === 1 ? "" : "s"} (${scopeLabel}), newest first`,
915
+ : `${total} background task${total === 1 ? "" : "s"} (${scopeLabel}), newest first${allowed.some(meta => (meta as BackgroundTaskMeta & { durable?: boolean }).durable) ? "; durable background operations included" : ""}`,
914
916
  failure: withIncidents ? listFailure : undefined,
915
917
  diagnostics: notes.join("\n") || undefined,
916
918
  },
@@ -921,6 +923,7 @@ export function formatList(options: OutputOptions = {}): string {
921
923
  resource,
922
924
  limit,
923
925
  maxBytes: budget,
926
+ ...(index.page ? { indexed: { total, before: index.page.before } } : {}),
924
927
  keyOf: (meta) => ({ time: meta.startedAt, id: meta.id }),
925
928
  render: (meta) => compactRow(meta, incidentsOf(meta.id)),
926
929
  }),
package/src/registry.ts CHANGED
@@ -158,6 +158,7 @@ export function inspectMeta(id: string): MetaInspection {
158
158
  export interface TaskIndex {
159
159
  records: MetaInspection[];
160
160
  indexError?: string;
161
+ page?: { total: number; before: number; contentRevision: string; failureRevision: string; unreadable: number; unknown: number };
161
162
  }
162
163
 
163
164
  /** List every task directory, including unreadable metadata. */
@@ -231,6 +232,20 @@ export function listActiveMetasForOrigin(origin: BackgroundTaskCallbackOrigin):
231
232
  .sort((a, b) => b.startedAt - a.startedAt);
232
233
  }
233
234
 
235
+ /** Passive shared-runtime query: no backfill, cache repair, or completed-history scan. */
236
+ export function observeMetasForOrigin(origin: BackgroundTaskCallbackOrigin, activeOnly = true): BackgroundTaskMeta[] {
237
+ const directory = activeOnly ? originActiveIndexDir(origin) : originIndexDir(origin);
238
+ let ids: string[];
239
+ try { ids = readdirSync(directory).filter(id => id !== ".initialized"); }
240
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return []; throw error; }
241
+ return ids.map(id => {
242
+ const record = inspectMeta(id);
243
+ if (record.found && !record.meta) throw new Error(`Unverified background task ${id}: ${record.error}`);
244
+ return record.meta;
245
+ }).filter((meta): meta is BackgroundTaskMeta => !!meta && !!meta.callbackOrigin && belongsToOrigin(meta, origin)
246
+ && (!activeOnly || meta.status === "running")).sort((a, b) => b.startedAt - a.startedAt);
247
+ }
248
+
234
249
  function readMetaForSweep(id: string): BackgroundTaskMeta | undefined {
235
250
  const cached = metaCache.get(id);
236
251
  if (cached && isTerminalStatus(cached.status)) return cached;
@@ -34,10 +34,12 @@ function section(settings: Record<string, unknown>): Record<string, unknown> {
34
34
  }
35
35
 
36
36
  function acquire(path: string): () => void {
37
- for (let attempt = 0; attempt < 10; attempt++) {
37
+ // A live writer can be briefly descheduled; allow contention without stealing its lock.
38
+ const maxAttempts = 100;
39
+ for (let attempt = 0; attempt < maxAttempts; attempt++) {
38
40
  try { return lockfile.lockSync(path, { realpath: false }); }
39
41
  catch (error) {
40
- if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === 9) throw error;
42
+ if ((error as NodeJS.ErrnoException).code !== "ELOCKED" || attempt === maxAttempts - 1) throw error;
41
43
  Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20);
42
44
  }
43
45
  }
@@ -1124,10 +1124,12 @@ export function sessionScopeKey(input: {
1124
1124
  origin?: ScopeOrigin;
1125
1125
  /** Key when there is no origin at all (for example, a per-process scope). */
1126
1126
  fallback?: string;
1127
+ /** Sessionless ownership may be limited to the process that launched work. */
1128
+ processId?: number;
1127
1129
  }): string {
1128
1130
  if (input.all) return "all";
1129
1131
  if (input.unavailable) return "session:unavailable";
1130
- if (input.origin) return `session:${originScopeDigest(input.origin)}`;
1132
+ if (input.origin) return `session:${originScopeDigest(input.origin)}${!input.origin.sessionId && input.processId !== undefined ? `:process:${input.processId}` : ""}`;
1131
1133
  return input.fallback ?? "none";
1132
1134
  }
1133
1135
 
@@ -1176,6 +1178,8 @@ export interface RowPageRequest<T> {
1176
1178
  maxBytes: number;
1177
1179
  keyOf: (item: T) => RowKey;
1178
1180
  render: (item: T) => string;
1181
+ /** Global counts when the items were selected by an indexed keyset query. */
1182
+ indexed?: { total: number; before: number };
1179
1183
  }
1180
1184
 
1181
1185
  export interface RowPage extends VerbatimPage {
@@ -1208,6 +1212,12 @@ export function isRowCursor(cursor: string | undefined): boolean {
1208
1212
  return decodeRowCursor(cursor) !== undefined;
1209
1213
  }
1210
1214
 
1215
+ /** Resolve a list anchor only in the scope/filter that issued it. */
1216
+ export function rowCursorKey(cursor: string | undefined, resource: string): RowKey | undefined {
1217
+ const parsed = decodeRowCursor(cursor);
1218
+ return parsed?.r === resourceTag(resource) && Number.isFinite(parsed.t) ? { time: parsed.t, id: parsed.i } : undefined;
1219
+ }
1220
+
1211
1221
  /** Sorts before every real row: a cursor anchored here starts at the first row. */
1212
1222
  const HEAD_ROW_KEY: RowKey = { time: Number.MAX_SAFE_INTEGER, id: "" };
1213
1223
 
@@ -1235,7 +1245,7 @@ function clipRow(row: string, maxBytes: number): string {
1235
1245
  export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): RowPage {
1236
1246
  const keyed = items.map((item) => ({ item, key: request.keyOf(item) }))
1237
1247
  .sort((a, b) => rowOrder(a.key, b.key));
1238
- const total = keyed.length;
1248
+ const total = request.indexed?.total ?? keyed.length;
1239
1249
  const limit = Math.max(1, Math.floor(request.limit));
1240
1250
  const maxBytes = Math.max(0, Math.floor(request.maxBytes));
1241
1251
  let start = 0;
@@ -1248,14 +1258,14 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1248
1258
  } else {
1249
1259
  const anchor: RowKey = { time: parsed.t, id: parsed.i };
1250
1260
  start = keyed.findIndex((row) => rowOrder(row.key, anchor) > 0);
1251
- if (start < 0) start = total;
1261
+ if (start < 0) start = keyed.length;
1252
1262
  }
1253
1263
  }
1254
1264
  const lines: string[] = [];
1255
1265
  let used = 0;
1256
1266
  let clippedRows = 0;
1257
1267
  let index = start;
1258
- for (; index < total && lines.length < limit; index += 1) {
1268
+ for (; index < keyed.length && lines.length < limit; index += 1) {
1259
1269
  const row = request.render(keyed[index]!.item);
1260
1270
  const sep = lines.length ? 1 : 0;
1261
1271
  const size = utf8ByteLength(row);
@@ -1276,11 +1286,12 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1276
1286
  break;
1277
1287
  }
1278
1288
  const shown = lines.length;
1279
- const remaining = Math.max(0, total - index);
1289
+ const before = request.indexed?.before ?? start;
1290
+ const remaining = Math.max(0, total - before - lines.length);
1280
1291
  const current = request.cursor && !reset ? request.cursor : undefined;
1281
1292
  // The next page starts after the last row shown, or — when no row fit —
1282
1293
  // at this page's own start, so a caller can always retry with a larger page.
1283
- const anchor = shown > 0 ? keyed[index - 1]!.key : start > 0 ? keyed[start - 1]!.key : HEAD_ROW_KEY;
1294
+ const anchor = shown > 0 ? keyed[index - 1]!.key : rowCursorKey(current, request.resource) ?? (start > 0 ? keyed[start - 1]!.key : HEAD_ROW_KEY);
1284
1295
  const nextCursor = remaining > 0
1285
1296
  ? encodeRowCursor({ k: "l", r: resource, t: anchor.time, i: anchor.id })
1286
1297
  : undefined;
@@ -1295,7 +1306,7 @@ export function pageRows<T>(items: readonly T[], request: RowPageRequest<T>): Ro
1295
1306
  gaps: [],
1296
1307
  shown,
1297
1308
  total,
1298
- before: start,
1309
+ before,
1299
1310
  remaining,
1300
1311
  clippedRows,
1301
1312
  };
@@ -111,7 +111,7 @@ type NavigatorState = {
111
111
  detailOverlayRows?: number;
112
112
  dispose?: () => void;
113
113
  /** The mounted detail overlay, reused instead of stacking a second one. */
114
- overlay?: { showDetail(navigatorId: string): void; focus(): void };
114
+ overlay?: { showDetail(navigatorId: string): void; refreshDetail(): void; focus(): void };
115
115
  };
116
116
 
117
117
  const GLOBAL_KEY = Symbol.for("pi-better-harness.navigator.state");
@@ -262,6 +262,7 @@ export function refreshBackgroundWorkNavigator(ctx?: ExtensionContext): void {
262
262
  if (!isNavigatorUiAvailable(activeCtx)) return;
263
263
  try {
264
264
  refreshMainListWidget();
265
+ s.overlay?.refreshDetail();
265
266
  } catch { /* ignore */ }
266
267
  }
267
268
 
@@ -954,6 +955,7 @@ function openNavigator(): void {
954
955
  }, selectedId);
955
956
  overlayRef = {
956
957
  showDetail: (navigatorId) => component.showDetail(navigatorId),
958
+ refreshDetail: () => component.refreshDetail(),
957
959
  focus: () => {
958
960
  if (s.overlay !== overlayRef) return;
959
961
  try { handle?.focus?.(); } catch { /* ignore */ }
@@ -1030,9 +1032,9 @@ function createOverlayComponent(
1030
1032
  startDetailTimer();
1031
1033
  });
1032
1034
 
1033
- function refreshRows(): void {
1035
+ function refreshRows(rows = listRows()): void {
1034
1036
  const selectedId = state().mainListSelectedId ?? overlayState.rows[overlayState.selected]?.navigatorId;
1035
- overlayState.rows = listRows();
1037
+ overlayState.rows = rows;
1036
1038
  const nextIdx = selectedId ? overlayState.rows.findIndex((row) => row.navigatorId === selectedId) : -1;
1037
1039
  overlayState.selected = nextIdx >= 0 ? nextIdx : Math.min(overlayState.selected, Math.max(0, overlayState.rows.length - 1));
1038
1040
  }
@@ -1160,7 +1162,8 @@ function createOverlayComponent(
1160
1162
  return {
1161
1163
  render(width: number) {
1162
1164
  closeIfEditorReplaced();
1163
- refreshRows();
1165
+ // The main-list refresh owns provider I/O; streaming paints reuse its snapshot.
1166
+ refreshRows(state().mainListRows ?? []);
1164
1167
  const rail = buildMainListLayout(overlayState.rows, width, deps.truncate, fg, {
1165
1168
  selectedId: selectedRow()?.navigatorId,
1166
1169
  focused: true,
@@ -1260,6 +1263,15 @@ function createOverlayComponent(
1260
1263
  backToMain();
1261
1264
  }
1262
1265
  },
1266
+ /** Observation arrival updates this row without resetting selection or folded sections. */
1267
+ refreshDetail() {
1268
+ if (closed) return;
1269
+ const wasLoading = detail?.status === "rebuilding";
1270
+ detail = detailFor(detailId, Date.now(), { logTailLines: logTailRows }) ?? detail;
1271
+ if (wasLoading) applyDefaultExpandedSections(detail, expandedSections);
1272
+ startDetailTimer();
1273
+ requestRender();
1274
+ },
1263
1275
  /** Show another row's detail in this overlay (the main list moved while it was unfocused). */
1264
1276
  showDetail(navigatorId: string) {
1265
1277
  if (closed) return;
@@ -1,12 +1,13 @@
1
1
  // Generated from packages/operation-coordinator/assignment-observation.mjs. Do not edit directly.
2
2
  import { createRequire } from "node:module";
3
+ import { createHash } from "node:crypto";
3
4
 
4
5
  /** Read-only, bounded projection input. Never creates/migrates a database. */
5
- export function readAssignmentWaits(path, owner) {
6
+ export function readAssignmentWaits(path, owner, connection) {
6
7
  let db;
7
8
  try {
8
9
  const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
9
- db = new DatabaseSync(path, { readOnly: true });
10
+ db = connection ?? new DatabaseSync(path, { readOnly: true });
10
11
  // v4 adds repair accounting; the observed wait/outcome fields are unchanged.
11
12
  if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) {
12
13
  return { verified: false, waits: [], reason: "Unsupported coordinator schema; assignment state is unverified." };
@@ -38,6 +39,65 @@ export function readAssignmentWaits(path, owner) {
38
39
  } catch {
39
40
  return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
40
41
  } finally {
41
- db?.close();
42
+ if (!connection) db?.close();
42
43
  }
43
44
  }
45
+
46
+ /** A root read model owns this connection; ordinary observers remain one-shot. */
47
+ export function createAssignmentReader(path) {
48
+ let db;
49
+ let identity;
50
+ const statements = new Map();
51
+ return {
52
+ revision() {
53
+ const { statSync } = createRequire(import.meta.url)("node:fs");
54
+ const stat = statSync(path, { bigint: true });
55
+ const next = `${stat.dev}:${stat.ino}`;
56
+ if (identity !== next) {
57
+ db?.close();
58
+ db = undefined;
59
+ statements.clear();
60
+ identity = next;
61
+ }
62
+ const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
63
+ db ??= new DatabaseSync(path, { readOnly: true });
64
+ return `${identity}:${db.prepare("PRAGMA data_version").get().data_version}`;
65
+ },
66
+ read(owner) {
67
+ try {
68
+ this.revision();
69
+ return readAssignmentWaits(path, owner, { prepare(sql) {
70
+ if (!statements.has(sql)) statements.set(sql, db.prepare(sql));
71
+ return statements.get(sql);
72
+ } });
73
+ } catch {
74
+ return { verified: false, waits: [], reason: "Coordinator state is unverified; compatible supervision is unavailable." };
75
+ }
76
+ },
77
+ conversationRevisions() {
78
+ try {
79
+ this.revision();
80
+ if (!["1", "2", "3", "4"].includes(db.prepare("SELECT value FROM schema_meta WHERE key = 'schema_version'").get()?.value)) return undefined;
81
+ const hashes = new Map();
82
+ const add = (sessionId, workspace, value) => {
83
+ const key = JSON.stringify([sessionId, workspace]);
84
+ if (!hashes.has(key)) hashes.set(key, createHash("sha256"));
85
+ hashes.get(key).update(JSON.stringify(value));
86
+ };
87
+ // One source pass per changed database revision, instead of one
88
+ // projection/query/log parse for every historical attempt.
89
+ for (const row of db.prepare(`SELECT w.*, (SELECT json_group_array(attempt_id)
90
+ FROM resume_claims c WHERE c.wait_id = w.wait_id AND c.generation = w.generation) AS claimed_attempts
91
+ FROM waits w WHERE owner_kind = 'worker-conversation' ORDER BY wait_id, generation`).all()) {
92
+ add(row.owner_session_id, row.owner_workspace, row);
93
+ }
94
+ for (const row of db.prepare("SELECT record_json FROM assignment_outcomes ORDER BY assignment_id").all()) {
95
+ const record = JSON.parse(row.record_json);
96
+ add(record.owner.sessionId, record.owner.workspace, record);
97
+ }
98
+ return new Map([...hashes].map(([key, hash]) => [key, hash.digest("hex")]));
99
+ } catch { return undefined; }
100
+ },
101
+ close() { db?.close(); db = undefined; statements.clear(); identity = undefined; },
102
+ };
103
+ }
@@ -45,6 +45,8 @@
45
45
  * to be durable.
46
46
  */
47
47
  export { SCHEMA_VERSION, TERMINAL_WAIT_PHASES } from "./src/types.ts";
48
+ export type { TaskCancellationIntent, TaskCancellationRequest } from "./src/task-cancellation.ts";
49
+ export { cancellationCredential } from "./src/task-cancellation.ts";
48
50
  export type { AssignmentOutcomeInput, AssignmentOutcomeRecord } from "./src/assignment-outcomes.ts";
49
51
  export type {
50
52
  AcknowledgeDisposition,
@@ -21,6 +21,8 @@ export type StoreErrorCode =
21
21
  | "unknown-operation"
22
22
  /** An operation already exists with different immutable launch identity. */
23
23
  | "operation-conflict"
24
+ /** An idempotency key was reused with different request content. */
25
+ | "request-conflict"
24
26
  /** The background task id belongs to a different owner. */
25
27
  | "task-ownership"
26
28
  /** The caller is not the recorded owner of the record it wants to change. */
@@ -19,6 +19,20 @@ import { StoreError } from "./errors.ts";
19
19
  import { columnText, getRow, getRows, run, type StoreContext } from "./sqlite.ts";
20
20
 
21
21
  const DDL: readonly string[] = [
22
+ `CREATE TABLE task_cancellation_authorities (
23
+ credential_hash TEXT PRIMARY KEY,
24
+ request_json TEXT NOT NULL,
25
+ directory TEXT NOT NULL
26
+ )`,
27
+ `CREATE TABLE task_cancellation_requests (
28
+ owner_key TEXT NOT NULL,
29
+ request_key TEXT NOT NULL,
30
+ operation_id TEXT NOT NULL REFERENCES operations (operation_id),
31
+ intent_json TEXT NOT NULL,
32
+ result_json TEXT,
33
+ state TEXT NOT NULL CHECK (state IN ('accepted', 'stop-requested')),
34
+ PRIMARY KEY (owner_key, request_key)
35
+ )`,
22
36
  `CREATE TABLE assignment_repairs (
23
37
  fault_key TEXT PRIMARY KEY,
24
38
  assignment_id TEXT NOT NULL,
@@ -323,9 +337,15 @@ function ensureAdditiveSchema(ctx: StoreContext): void {
323
337
  && hasIndex()
324
338
  && hasTable("discovery_claims")
325
339
  && hasTable("coordinator_state")
340
+ && hasTable("task_cancellation_requests")
341
+ && hasTable("task_cancellation_authorities")
342
+ && getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")
326
343
  ) return;
327
344
 
328
345
  ctx.transaction(() => {
346
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_requests"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
347
+ if (!getRows(ctx, "PRAGMA table_info(task_cancellation_requests)").some(row => row.name === "result_json")) ctx.db.exec("ALTER TABLE task_cancellation_requests ADD COLUMN result_json TEXT");
348
+ ctx.db.exec(DDL.find((sql) => sql.startsWith("CREATE TABLE task_cancellation_authorities"))!.replace("CREATE TABLE", "CREATE TABLE IF NOT EXISTS"));
329
349
  if (!hasColumn()) {
330
350
  ctx.db.exec("ALTER TABLE operations ADD COLUMN supervision_host_id TEXT");
331
351
  ctx.db.exec(`UPDATE operations