pi-daddy 0.62.1 → 0.63.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 (79) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.md +14 -0
  3. package/contracts/task-history/v1/README.md +76 -0
  4. package/contracts/task-history/v1/dispatch.ts +38 -0
  5. package/contracts/task-history/v1/observation.schema.json +73 -0
  6. package/contracts/task-history/v1/producer.ts +48 -0
  7. package/dist/governance/runtime-settlement.d.ts +8 -1
  8. package/dist/governance/runtime-settlement.d.ts.map +1 -1
  9. package/dist/governance/runtime-settlement.js +42 -4
  10. package/dist/governance/runtime-settlement.js.map +1 -1
  11. package/dist/governance/task-dispatch.d.ts +85 -0
  12. package/dist/governance/task-dispatch.d.ts.map +1 -0
  13. package/dist/governance/task-dispatch.js +342 -0
  14. package/dist/governance/task-dispatch.js.map +1 -0
  15. package/dist/kernel/dashboard-choice.d.ts +5 -0
  16. package/dist/kernel/dashboard-choice.d.ts.map +1 -1
  17. package/dist/kernel/dashboard-choice.js.map +1 -1
  18. package/dist/kernel/dashboard-observation.d.ts +31 -0
  19. package/dist/kernel/dashboard-observation.d.ts.map +1 -1
  20. package/dist/kernel/dashboard-observation.js +33 -1
  21. package/dist/kernel/dashboard-observation.js.map +1 -1
  22. package/dist/kernel/dashboard-request.d.ts +4 -0
  23. package/dist/kernel/dashboard-request.d.ts.map +1 -0
  24. package/dist/kernel/dashboard-request.js +8 -0
  25. package/dist/kernel/dashboard-request.js.map +1 -0
  26. package/dist/products/dashboard-choice-picker.d.ts +2 -0
  27. package/dist/products/dashboard-choice-picker.d.ts.map +1 -1
  28. package/dist/products/dashboard-choice-picker.js +46 -18
  29. package/dist/products/dashboard-choice-picker.js.map +1 -1
  30. package/dist/products/dashboard-cli.d.ts.map +1 -1
  31. package/dist/products/dashboard-cli.js +31 -4
  32. package/dist/products/dashboard-cli.js.map +1 -1
  33. package/dist/products/dashboard-components.d.ts +2 -0
  34. package/dist/products/dashboard-components.d.ts.map +1 -1
  35. package/dist/products/dashboard-components.js +81 -0
  36. package/dist/products/dashboard-components.js.map +1 -1
  37. package/dist/products/dashboard-panels.d.ts.map +1 -1
  38. package/dist/products/dashboard-panels.js +7 -2
  39. package/dist/products/dashboard-panels.js.map +1 -1
  40. package/dist/products/dashboard-screen.d.ts +2 -0
  41. package/dist/products/dashboard-screen.d.ts.map +1 -1
  42. package/dist/products/dashboard-screen.js +12 -3
  43. package/dist/products/dashboard-screen.js.map +1 -1
  44. package/dist/products/dashboard-session-client.d.ts +8 -0
  45. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  46. package/dist/products/dashboard-session-client.js +54 -26
  47. package/dist/products/dashboard-session-client.js.map +1 -1
  48. package/dist/products/dashboard-task-controls.d.ts +6 -0
  49. package/dist/products/dashboard-task-controls.d.ts.map +1 -0
  50. package/dist/products/dashboard-task-controls.js +27 -0
  51. package/dist/products/dashboard-task-controls.js.map +1 -0
  52. package/extensions/dashboard-choice-controls.ts +33 -1
  53. package/extensions/dashboard-session-server.ts +67 -4
  54. package/extensions/dashboard-sources.ts +21 -2
  55. package/extensions/delegate-chain.ts +6 -0
  56. package/extensions/delegation-artifacts.ts +34 -0
  57. package/extensions/delegation-operations.ts +5 -0
  58. package/extensions/delegation.ts +26 -2
  59. package/extensions/execute-child.ts +4 -0
  60. package/extensions/grants.ts +3 -0
  61. package/extensions/run-delegation.ts +58 -6
  62. package/extensions/runtime-snapshot.ts +23 -17
  63. package/extensions/session.ts +4 -0
  64. package/extensions/task-dispatch-controller.ts +384 -0
  65. package/extensions/task-inline-control.ts +21 -0
  66. package/extensions/task-worktree-writer.ts +55 -0
  67. package/package.json +1 -1
  68. package/src/governance/runtime-settlement.ts +44 -2
  69. package/src/governance/task-dispatch.ts +427 -0
  70. package/src/kernel/dashboard-choice.ts +7 -1
  71. package/src/kernel/dashboard-observation.ts +67 -2
  72. package/src/kernel/dashboard-request.ts +8 -0
  73. package/src/products/dashboard-choice-picker.ts +51 -16
  74. package/src/products/dashboard-cli.ts +33 -4
  75. package/src/products/dashboard-components.ts +84 -0
  76. package/src/products/dashboard-panels.ts +6 -1
  77. package/src/products/dashboard-screen.ts +14 -3
  78. package/src/products/dashboard-session-client.ts +79 -28
  79. package/src/products/dashboard-task-controls.ts +34 -0
@@ -334,6 +334,9 @@ async function runOneDelegationImplementation(
334
334
  askNobody?: boolean;
335
335
  /** Epoch ms the child's wall-clock deadline may not pass: the first attempt's, for a retry. */
336
336
  deadlineAt?: number;
337
+ /** Captured before planning. Each real executor attempt consumes its own task reservation. */
338
+ taskObservation?: ReturnType<NonNullable<GrantsSession["bindTaskObservation"]>> | null;
339
+ taskAdmission?: import("./task-dispatch-controller.ts").TaskDispatchAdmission;
337
340
  /** Composition-only observation of what this attempt spent and recorded; see `replay-retry.ts`. */
338
341
  onAttempt?: (facts: AttemptObservation) => void;
339
342
  } = {},
@@ -352,7 +355,10 @@ async function runOneDelegationImplementation(
352
355
  capacityRefusal = structuredRefusal(error.code, error.message, error.details);
353
356
  }
354
357
  let executorEntered = false;
358
+ let admitted: import("./task-dispatch-controller.ts").AdmittedAttempt | undefined;
359
+ let outcome: DelegationOutcome | undefined;
355
360
  try {
361
+ await options.taskAdmission?.assertAvailable();
356
362
  await session.ensureDefinitions?.();
357
363
  assertDefinitionIdentity(session, spec, options.definitionBinding?.source);
358
364
 
@@ -501,6 +507,16 @@ async function runOneDelegationImplementation(
501
507
  plan = { ...plan, ok: false, reason: modelRefusal.message, refusal: modelRefusal };
502
508
  }
503
509
 
510
+ if (plan.ok && options.taskAdmission) {
511
+ try {
512
+ const access = governedWorkspaceAccess(spec.workspace?.access ?? "read", plan.requested);
513
+ const writerFolder = access === "write" ? (preparedWorkspace?.workspace.root ?? ctx.cwd) : undefined;
514
+ admitted = await options.taskAdmission(ids.executionId, writerFolder);
515
+ } catch (error) {
516
+ const message = error instanceof Error ? error.message : "Task dispatch unavailable";
517
+ plan = { ...plan, ok: false, reason: message, refusal: structuredRefusal("EXECUTOR_UNAVAILABLE", message) };
518
+ }
519
+ }
504
520
  // The capability decision provisions the child, so this append remains load-bearing and fails closed.
505
521
  try {
506
522
  await recordDelegationDecision({
@@ -559,11 +575,18 @@ async function runOneDelegationImplementation(
559
575
  runtime: resolvedRuntime,
560
576
  approvalSpent: Boolean(approvalOutcome?.approved.length || preApproved?.length),
561
577
  });
562
- executorEntered = true;
563
- return await executePlannedChild({
578
+ if (!options.operationClaim)
579
+ await options.taskObservation?.(ids.executionId, "delegation", "admitted", "Delegation admitted");
580
+ outcome = await executePlannedChild({
581
+ beforeRuntimeBegin: admitted?.beforeRuntimeBegin,
564
582
  capacityReservation: capacity,
565
583
  operationClaim: options.operationClaim,
566
- onExecutorEntry: options.onExecutorEntry,
584
+ onExecutorEntry: () => {
585
+ executorEntered = true;
586
+ if (!options.operationClaim)
587
+ options.taskObservation?.(ids.executionId, "delegation", "started", "Delegation started");
588
+ options.onExecutorEntry?.();
589
+ },
567
590
  session,
568
591
  plan,
569
592
  agent: spec.agent,
@@ -576,12 +599,36 @@ async function runOneDelegationImplementation(
576
599
  parentToolHost: ctx,
577
600
  preparedWorkspace,
578
601
  resolvedRuntime,
579
- signal,
602
+ signal: admitted ? (signal ? AbortSignal.any([signal, admitted.signal]) : admitted.signal) : signal,
580
603
  onProgress,
581
604
  deadlineAt: options.deadlineAt,
582
605
  onDeadline: (deadlineAt) => options.onAttempt?.({ deadlineAt }),
583
606
  });
607
+ return outcome;
584
608
  } finally {
609
+ if (!options.operationClaim && executorEntered) {
610
+ const settled = outcome?.cleanup?.state === "settled";
611
+ options.taskObservation?.(
612
+ ids.executionId,
613
+ "delegation",
614
+ settled ? "settled" : "cleanup-unconfirmed",
615
+ settled ? "Delegation cleanup confirmed" : "Delegation cleanup unconfirmed",
616
+ );
617
+ }
618
+ try {
619
+ const cleanup = outcome?.cleanup?.state;
620
+ admitted?.finish(
621
+ cleanup === "settled" || cleanup === "not-started" ? cleanup : executorEntered ? "unknown" : "not-started",
622
+ );
623
+ } catch {
624
+ if (outcome) {
625
+ outcome.control = "failed";
626
+ outcome.reason = [outcome.reason, "Task dispatch settlement unconfirmed; reconcile the recorded attempt"]
627
+ .filter(Boolean)
628
+ .join("; ");
629
+ }
630
+ // Native output and exceptions keep their meaning if the control journal becomes unavailable.
631
+ }
585
632
  capacity?.finalize(
586
633
  executorEntered
587
634
  ? { state: "unknown", reason: "execution returned without qualified cleanup" }
@@ -597,11 +644,16 @@ export async function runOneDelegation(
597
644
  const [session, spec, ids, budget, ctx, signal] = args;
598
645
  const workMode = capturedWorkMode(session);
599
646
  const finalScope = operationFinalScope(session);
600
- const options = { ...args[6], ...(workMode ? { workMode } : {}) };
647
+ const taskAdmission = args[6] && "taskAdmission" in args[6] ? args[6].taskAdmission : session.taskDispatch?.capture();
648
+ const taskObservation =
649
+ args[6] && "taskObservation" in args[6] ? args[6].taskObservation : session.bindTaskObservation?.();
650
+ const options = { ...args[6], taskObservation, taskAdmission, ...(workMode ? { workMode } : {}) };
601
651
  const binding = options.definitionBinding;
602
652
  const bindOutcome = (outcome: DelegationOutcome) =>
603
653
  binding ? Object.assign(outcome, { definitionBinding: { ...binding } }) : outcome;
604
- const claim = options.operationClaim ?? (await claimDelegationOperation(session, spec, ids, ctx, signal, binding));
654
+ const claim =
655
+ options.operationClaim ??
656
+ (await claimDelegationOperation(session, spec, ids, ctx, signal, binding, taskObservation ?? null));
605
657
  if (claim?.reused) {
606
658
  options.capacityReservation?.finalize({ state: "not-started", reason: "existing operation reused" });
607
659
  return bindOutcome(existingOperationOutcome(claim, session.depth + 1));
@@ -1,3 +1,5 @@
1
+ import { createTaskDispatchController } from "./task-dispatch-controller.ts";
2
+ import { bindTaskHistory } from "../contracts/task-history/v1/producer.ts";
1
3
  import { registerOperationRecoveryBridge } from "./operation-recovery-bridge.ts";
2
4
  import { registerDashboardPrompts } from "./dashboard-ui-prompts.ts";
3
5
  import { registerInitiativeRuntime } from "./initiative-runtime.ts";
@@ -26,29 +28,32 @@ export function registerRuntimeSnapshot(
26
28
  const generation = {};
27
29
  let bindSequence = 0;
28
30
  let artifactOwner: ArtifactBridgeOwner | undefined;
29
- const initiative = registerInitiativeRuntime(pi, session, () =>
31
+ const currentOwner = () =>
30
32
  bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
31
33
  ? bound
32
- : undefined,
33
- );
34
- const dashboardSources = registerDashboardSources(pi, () =>
35
- bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
36
- ? bound
37
- : undefined,
34
+ : undefined;
35
+ const initiative = registerInitiativeRuntime(pi, session, currentOwner);
36
+ const taskDispatch = createTaskDispatchController(
37
+ pi.events,
38
+ () => (session.depth === 0 ? currentOwner() : undefined),
39
+ agentDir,
40
+ () => session.reloadLifecycle.runtimeSettlement,
38
41
  );
42
+ session.taskDispatch = taskDispatch;
43
+ session.bindTaskObservation = () => {
44
+ const owner = currentOwner();
45
+ if (!owner || session.depth !== 0) return;
46
+ return bindTaskHistory(pi.events, "pi-daddy", {
47
+ cwd: owner.cwd,
48
+ sessionManager: { getSessionId: () => owner.sessionId },
49
+ });
50
+ };
51
+ const dashboardSources = registerDashboardSources(pi, currentOwner);
39
52
  session.dashboardObservations = () => dashboardSources.snapshot();
40
53
  session.dashboardRefreshSources = () => dashboardSources.requestRefresh();
41
54
  session.dashboardChoices = dashboardSources.choices;
42
- session.dashboardLive = registerDashboardLive(pi, () =>
43
- bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
44
- ? bound
45
- : undefined,
46
- );
47
- const prompts = registerDashboardPrompts(pi, () =>
48
- bound?.lifecycle === session.reloadLifecycle && session.reloadLifecycle.runtimeSnapshotGeneration === generation
49
- ? bound
50
- : undefined,
51
- );
55
+ session.dashboardLive = registerDashboardLive(pi, currentOwner);
56
+ const prompts = registerDashboardPrompts(pi, currentOwner);
52
57
  session.dashboardPrompt = prompts.snapshot;
53
58
  session.dashboardArtifacts = [];
54
59
 
@@ -270,6 +275,7 @@ export function registerRuntimeSnapshot(
270
275
  unsubscribeRuntime?.();
271
276
  unsubscribeOperations?.();
272
277
  unsubscribeHistory?.();
278
+ taskDispatch.close();
273
279
  artifactBridge.close();
274
280
  recoveryBridge.close();
275
281
  void initiative.close().catch(() => undefined);
@@ -147,6 +147,10 @@ export function activityChildEnv(activity: { rootId: string; path: string; taskI
147
147
  }
148
148
  /** Keep each child's pane after it finishes, for inspection. Off by default: fan-out would flood it. */
149
149
  export interface GrantsSession extends NativeSessionHost {
150
+ taskDispatch?: ReturnType<typeof import("./task-dispatch-controller.ts").createTaskDispatchController>;
151
+ /** Optional peer callback bound before dispatch. Execution evidence remains with the native owner. */
152
+ bindTaskObservation?: () =>
153
+ ReturnType<typeof import("../contracts/task-history/v1/producer.ts").bindTaskHistory> | undefined;
150
154
  initiativeOperations?: InitiativeOperationBinding;
151
155
  dashboardInitiative?: () => DashboardSourceSnapshot | undefined;
152
156
  refreshInitiative?: () => void;
@@ -0,0 +1,384 @@
1
+ /** Trusted Bookie selection identifies the task. Daddy retains authority over only its own dispatch. */
2
+ import {
3
+ TaskDispatch,
4
+ type DispatchEdit,
5
+ type DispatchView,
6
+ type DispatchOwner,
7
+ isDispatchEdit,
8
+ } from "../src/governance/task-dispatch.ts";
9
+ import { claimTaskWriter } from "./task-worktree-writer.ts";
10
+ import { agentDir } from "../src/kernel/project-paths.ts";
11
+ import {
12
+ readRuntimeExecutionSettlement,
13
+ pinPrelaunchOwner,
14
+ type RuntimeSettlement,
15
+ } from "../src/governance/runtime-settlement.ts";
16
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
17
+
18
+ interface TaskScope {
19
+ projectId: string;
20
+ budgetRootTaskId?: string;
21
+ taskId: string;
22
+ revision: number;
23
+ assertCurrent(): Promise<void>;
24
+ }
25
+ type Host = { cwd: string; sessionId: string };
26
+ export type AdmittedAttempt = {
27
+ beforeRuntimeBegin?: (runtime: RuntimeSettlement | undefined) => void;
28
+ signal: AbortSignal;
29
+ finish(cleanup: "settled" | "not-started" | "unknown"): void;
30
+ };
31
+ export type TaskDispatchAdmission = {
32
+ (executionId: string, writerFolder?: string): Promise<AdmittedAttempt>;
33
+ assertAvailable(): Promise<void>;
34
+ reconcile(executionId: string, cleanup: "settled" | "not-started"): Promise<void>;
35
+ };
36
+ export function createTaskDispatchController(
37
+ bus: ExtensionAPI["events"],
38
+ current: () => Host | undefined,
39
+ directory = agentDir,
40
+ nativeOwner?: () => RuntimeSettlement | undefined,
41
+ ) {
42
+ let lastBoundHost: Host | undefined;
43
+ let previous: TaskDispatch | undefined;
44
+ let lastDisplay:
45
+ | { host: Host; project: string; task: string; root: string; revision: number; checked: number; view: DispatchView }
46
+ | undefined;
47
+ const storeFor = (scope: TaskScope) => {
48
+ const rootId = scope.budgetRootTaskId ?? scope.taskId;
49
+ if (!previous || previous.projectId !== scope.projectId || previous.taskId !== rootId)
50
+ previous = new TaskDispatch(directory(), scope.projectId, rootId);
51
+ return previous;
52
+ };
53
+
54
+ function select() {
55
+ const host = current();
56
+ if (!host) return;
57
+ const response: { scope?: TaskScope; unavailable?: boolean } = {};
58
+ let accepting = true;
59
+ try {
60
+ bus?.emit?.("pi.task-history.v1.scope", {
61
+ version: 1,
62
+ cwd: host.cwd,
63
+ sessionId: host.sessionId,
64
+ unavailable() {
65
+ if (accepting) response.unavailable = true;
66
+ },
67
+ accept(candidate: TaskScope) {
68
+ if (!accepting) return;
69
+ if (response.scope) {
70
+ response.unavailable = true;
71
+ return;
72
+ }
73
+ if (
74
+ candidate &&
75
+ typeof candidate.projectId === "string" &&
76
+ typeof candidate.taskId === "string" &&
77
+ (candidate.budgetRootTaskId === undefined || typeof candidate.budgetRootTaskId === "string") &&
78
+ Number.isSafeInteger(candidate.revision) &&
79
+ typeof candidate.assertCurrent === "function"
80
+ )
81
+ response.scope = candidate;
82
+ else response.unavailable = true;
83
+ },
84
+ });
85
+ } catch {
86
+ response.unavailable = true;
87
+ } finally {
88
+ accepting = false;
89
+ }
90
+ if (response.unavailable || (!response.scope && lastBoundHost === host))
91
+ throw Error("Task scope is temporarily unavailable. Reopen its history before dispatch.");
92
+ if (!response.scope) return;
93
+ lastBoundHost = host;
94
+ const chosen = response.scope;
95
+ const assertCurrent = async () => {
96
+ if (current() !== host) throw Error("Task session changed");
97
+ await chosen.assertCurrent();
98
+ if (current() !== host) throw Error("Task session changed");
99
+ };
100
+ return { scope: chosen, assertCurrent, host, store: storeFor(chosen) };
101
+ }
102
+
103
+ // Recover an interrupted predecessor without replacing its occurrence ID. Missing or ambiguous receipts stay pending.
104
+ async function reconcilePredecessor(binding: NonNullable<ReturnType<typeof select>>) {
105
+ const runtime = nativeOwner?.();
106
+ if (!runtime) return;
107
+ for (const attempt of binding.store.outstanding()) {
108
+ if (attempt.owner !== "pi-daddy" || !attempt.beforeLaunch || attempt.beforeLaunch.ownerId === runtime.ownerId)
109
+ continue;
110
+ const state = await readRuntimeExecutionSettlement(
111
+ directory(),
112
+ attempt.sessionId,
113
+ attempt.cwd,
114
+ attempt.executionId,
115
+ attempt.beforeLaunch,
116
+ ).catch(() => "unknown" as const);
117
+ if (state !== "unknown") {
118
+ await binding.assertCurrent();
119
+ binding.store.settle(attempt.owner, attempt.executionId, state, attempt.taskId ?? binding.store.taskId);
120
+ }
121
+ }
122
+ }
123
+
124
+ const controller = {
125
+ /** An inline effect's owner can consult the shared pause state without spending a delegated attempt. */
126
+ captureInline(): (() => Promise<void>) | undefined {
127
+ let binding: ReturnType<typeof select>;
128
+ try {
129
+ binding = select();
130
+ } catch (error) {
131
+ return async () => {
132
+ throw error;
133
+ };
134
+ }
135
+ if (!binding) return;
136
+ return async () => {
137
+ await binding.assertCurrent();
138
+ binding.store.assertOpen();
139
+ };
140
+ },
141
+ capture(owner: DispatchOwner = "pi-daddy", expectedHost?: Host): TaskDispatchAdmission | undefined {
142
+ if (expectedHost && (current()?.cwd !== expectedHost.cwd || current()?.sessionId !== expectedHost.sessionId))
143
+ return;
144
+ let binding: ReturnType<typeof select>;
145
+ try {
146
+ binding = select();
147
+ } catch (error) {
148
+ const unavailable = async (): Promise<never> => {
149
+ throw error;
150
+ };
151
+ return Object.assign(unavailable, { assertAvailable: unavailable, reconcile: unavailable });
152
+ }
153
+ if (
154
+ !binding ||
155
+ (expectedHost && (binding.host.cwd !== expectedHost.cwd || binding.host.sessionId !== expectedHost.sessionId))
156
+ )
157
+ return;
158
+ const admit = async (executionId: string, writerFolder?: string): Promise<AdmittedAttempt> => {
159
+ const { host, scope, store } = binding;
160
+ await binding.assertCurrent();
161
+ const native = owner === "pi-daddy" ? nativeOwner?.() : undefined;
162
+ if (owner === "pi-daddy" && nativeOwner && !native)
163
+ throw Error("Native owner is unavailable before task admission");
164
+ const beforeLaunch = native ? pinPrelaunchOwner(native, host.sessionId, host.cwd) : undefined;
165
+ const writer =
166
+ owner === "pi-daddy" && writerFolder
167
+ ? await claimTaskWriter(directory(), writerFolder, host, executionId, beforeLaunch)
168
+ : undefined;
169
+ let reserved = false;
170
+ try {
171
+ await binding.assertCurrent();
172
+ store.admit({
173
+ owner,
174
+ executionId,
175
+ taskId: scope.taskId,
176
+ cwd: host.cwd,
177
+ sessionId: host.sessionId,
178
+ ...(beforeLaunch ? { beforeLaunch } : {}),
179
+ });
180
+ reserved = true;
181
+ await binding.assertCurrent();
182
+ } catch (error) {
183
+ try {
184
+ if (reserved) store.settle(owner, executionId, "not-started", scope.taskId);
185
+ } finally {
186
+ writer?.("not-started");
187
+ }
188
+ throw error;
189
+ }
190
+ const controller = new AbortController();
191
+ const checkCancel = () => {
192
+ try {
193
+ if (store.snapshot(scope.revision).state === "cancelling") controller.abort();
194
+ } catch {
195
+ // An unreadable journal does not authorize signalling the running worker.
196
+ }
197
+ };
198
+ checkCancel();
199
+ const timer = setInterval(checkCancel, 2000);
200
+ timer.unref();
201
+ return {
202
+ signal: controller.signal,
203
+ ...(native
204
+ ? {
205
+ beforeRuntimeBegin(runtime: RuntimeSettlement | undefined) {
206
+ if (runtime !== native || runtime !== nativeOwner?.() || current() !== host)
207
+ throw Error("Task reservation's native owner changed before executor entry");
208
+ },
209
+ }
210
+ : {}),
211
+ finish(cleanup) {
212
+ clearInterval(timer);
213
+ if (cleanup === "settled" || cleanup === "not-started") {
214
+ try {
215
+ store.settle(owner, executionId, cleanup, scope.taskId);
216
+ } finally {
217
+ writer?.(cleanup);
218
+ }
219
+ } else if (cleanup !== "unknown") throw Error("Unsupported task cleanup status");
220
+ },
221
+ };
222
+ };
223
+ return Object.assign(admit, {
224
+ assertAvailable: async () => {
225
+ await binding.assertCurrent();
226
+ await reconcilePredecessor(binding);
227
+ binding.store.assertAvailable(owner);
228
+ },
229
+ reconcile: async (executionId: string, cleanup: "settled" | "not-started") => {
230
+ if (cleanup !== "settled" && cleanup !== "not-started") throw Error("A native terminal receipt is required");
231
+ await binding.assertCurrent();
232
+ const pending = binding.store.outstanding().find((a) => a.owner === owner && a.executionId === executionId);
233
+ if (!pending) return;
234
+ if (pending.cwd !== binding.host.cwd) throw Error("Original execution folder changed");
235
+ binding.store.settle(owner, executionId, cleanup, binding.scope.taskId);
236
+ },
237
+ });
238
+ },
239
+ async snapshot(reuseDisplayed = false): Promise<DispatchView | undefined> {
240
+ const binding = select();
241
+ if (!binding) return;
242
+ const { scope, host, store } = binding;
243
+ if (
244
+ reuseDisplayed &&
245
+ lastDisplay &&
246
+ lastDisplay.host === host &&
247
+ lastDisplay.root === store.taskId &&
248
+ lastDisplay.project === scope.projectId &&
249
+ lastDisplay.task === scope.taskId &&
250
+ lastDisplay.revision === scope.revision &&
251
+ Date.now() >= lastDisplay.checked &&
252
+ Date.now() - lastDisplay.checked < 1000
253
+ )
254
+ return lastDisplay.view;
255
+ await binding.assertCurrent();
256
+ const checked = Date.now(),
257
+ view = store.snapshot(scope.revision, scope.taskId);
258
+ view.observedAt = new Date(checked).toISOString();
259
+ lastDisplay = {
260
+ host,
261
+ project: scope.projectId,
262
+ task: scope.taskId,
263
+ root: store.taskId,
264
+ revision: scope.revision,
265
+ checked,
266
+ view,
267
+ };
268
+ return view;
269
+ },
270
+ async change(edit: DispatchEdit, checkClient: () => void): Promise<DispatchView> {
271
+ const b = select();
272
+ const expected = edit.expected;
273
+ if (
274
+ !b ||
275
+ !expected ||
276
+ b.scope.projectId !== expected.projectId ||
277
+ b.scope.taskId !== expected.taskId ||
278
+ b.scope.revision !== expected.selectionRevision ||
279
+ !Number.isSafeInteger(expected.revision)
280
+ )
281
+ throw Error("Selected task changed. Inspect the current task before applying this control.");
282
+ if (b.store.taskId !== b.scope.taskId) throw Error("Select the parent task to change shared dispatch controls.");
283
+ if (!isDispatchEdit(edit)) throw Error("Invalid task control");
284
+ await b.assertCurrent();
285
+ checkClient();
286
+ // The operator acts on the state displayed. Reconciliation itself is safe to repeat.
287
+ if (edit.action === "resume") {
288
+ for (const attempt of b.store.outstanding()) {
289
+ if (attempt.owner !== "pi-daddy") continue;
290
+ const state = await readRuntimeExecutionSettlement(
291
+ directory(),
292
+ attempt.sessionId,
293
+ attempt.cwd,
294
+ attempt.executionId,
295
+ attempt.beforeLaunch,
296
+ ).catch(() => "unknown" as const);
297
+ if (state !== "unknown")
298
+ b.store.settle("pi-daddy", attempt.executionId, state, attempt.taskId ?? b.store.taskId);
299
+ }
300
+ }
301
+ await b.assertCurrent();
302
+ checkClient();
303
+ lastDisplay = undefined;
304
+ b.store.change(edit.action, edit.limit ?? null, expected.revision, edit.owner);
305
+ return b.store.snapshot(b.scope.revision);
306
+ },
307
+ };
308
+ const unsubscribe = bus?.on?.("pi.task-dispatch.v1.bind", (raw: unknown) => {
309
+ const req = raw as {
310
+ version?: unknown;
311
+ owner?: unknown;
312
+ cwd?: unknown;
313
+ sessionId?: unknown;
314
+ accept?: (admit: unknown) => void;
315
+ };
316
+ if (
317
+ !req ||
318
+ req.version !== 1 ||
319
+ !["scout", "harness", "jev"].includes(String(req.owner)) ||
320
+ typeof req.cwd !== "string" ||
321
+ typeof req.sessionId !== "string" ||
322
+ typeof req.accept !== "function"
323
+ )
324
+ return;
325
+ const admit = controller.capture(req.owner as DispatchOwner, { cwd: req.cwd, sessionId: req.sessionId });
326
+ if (!admit) return;
327
+ req.accept(
328
+ Object.assign(
329
+ async (input: { operationId: string }) => {
330
+ if (!input || typeof input.operationId !== "string") throw Error("Missing native attempt id");
331
+ return admit(input.operationId);
332
+ },
333
+ {
334
+ reconcile: async (input: { operationId: string; cleanup: "settled" | "not-started" }) => {
335
+ if (!input || typeof input.operationId !== "string") throw Error("Missing native attempt id");
336
+ await admit.reconcile(input.operationId, input.cleanup);
337
+ },
338
+ },
339
+ ),
340
+ );
341
+ });
342
+ const stopReplay = bus?.on?.("pi.task-history.v1.replay", (raw: unknown) => {
343
+ const req = raw as {
344
+ version?: unknown;
345
+ owner?: unknown;
346
+ cwd?: unknown;
347
+ sessionId?: unknown;
348
+ projectId?: unknown;
349
+ taskId?: unknown;
350
+ after?: unknown;
351
+ limit?: unknown;
352
+ accept?: (read: () => Promise<ReturnType<TaskDispatch["page"]>>) => void;
353
+ };
354
+ const host = current();
355
+ if (
356
+ !req ||
357
+ !host ||
358
+ req.version !== 1 ||
359
+ req.owner !== "pi-daddy" ||
360
+ req.cwd !== host.cwd ||
361
+ req.sessionId !== host.sessionId ||
362
+ typeof req.accept !== "function" ||
363
+ typeof req.after !== "number" ||
364
+ typeof req.limit !== "number"
365
+ )
366
+ return;
367
+ const binding = select();
368
+ if (!binding || req.projectId !== binding.scope.projectId || req.taskId !== binding.scope.taskId) return;
369
+ const after = req.after,
370
+ limit = req.limit;
371
+ req.accept(async () => {
372
+ await binding.assertCurrent();
373
+ const page = binding.store.page(after, limit, binding.scope.taskId);
374
+ await binding.assertCurrent();
375
+ return page;
376
+ });
377
+ });
378
+ return Object.assign(controller, {
379
+ close: () => {
380
+ unsubscribe?.();
381
+ stopReplay?.();
382
+ },
383
+ });
384
+ }
@@ -0,0 +1,21 @@
1
+ const inlineWorkTools = new Set(["write", "edit", "bash", "apply_patch"]);
2
+
3
+ type InlineSession = {
4
+ depth: number;
5
+ ownExecutionId?: string;
6
+ taskDispatch?: { captureInline(): (() => Promise<void>) | undefined };
7
+ };
8
+
9
+ /** Check Pi's root tool call, immediately before its built-in effect may start. */
10
+ export async function taskInlineControl(toolName: string, session: InlineSession) {
11
+ if (!inlineWorkTools.has(toolName) || session.depth !== 0 || session.ownExecutionId) return;
12
+ try {
13
+ await session.taskDispatch?.captureInline()?.();
14
+ } catch (error) {
15
+ const reason =
16
+ error instanceof Error && error.message === "Task dispatch is stopped. Inspect task controls before resuming."
17
+ ? "This task is paused or cancelled. Open task controls to resume when ready."
18
+ : "The selected task could not be verified. Reopen its history before starting new work.";
19
+ return { block: true, reason };
20
+ }
21
+ }
@@ -0,0 +1,55 @@
1
+ /** Serialize opted-in writers by actual working copy. This never creates a grant or changes a worker's cwd. */
2
+ import { dirname, join } from "node:path";
3
+ import { lstat, stat, realpath } from "node:fs/promises";
4
+ import { TaskDispatch } from "../src/governance/task-dispatch.ts";
5
+ import { readRuntimeExecutionSettlement, type PrelaunchOwner } from "../src/governance/runtime-settlement.ts";
6
+ type Host = { cwd: string; sessionId: string };
7
+
8
+ async function workingCopyId(cwd: string) {
9
+ const requested = await realpath(cwd);
10
+ let root = requested;
11
+ for (let cursor = requested; ; cursor = dirname(cursor)) {
12
+ try {
13
+ const marker = await lstat(join(cursor, ".git"));
14
+ if (!marker.isFile() && !marker.isDirectory()) throw Error("Cannot identify the Git working copy");
15
+ root = cursor;
16
+ break;
17
+ } catch (error) {
18
+ if ((error as NodeJS.ErrnoException)?.code !== "ENOENT") throw error;
19
+ }
20
+ if (dirname(cursor) === cursor) break;
21
+ }
22
+ const identity = await stat(root, { bigint: true });
23
+ if (!identity.isDirectory()) throw Error("Working copy is unavailable");
24
+ return `${identity.dev}.${identity.ino}`;
25
+ }
26
+
27
+ export async function claimTaskWriter(
28
+ directory: string,
29
+ target: string,
30
+ host: Host,
31
+ executionId: string,
32
+ beforeLaunch?: PrelaunchOwner,
33
+ ) {
34
+ const id = await workingCopyId(target);
35
+ const store = new TaskDispatch(directory, "working-copy", id, true);
36
+ for (const previous of store.outstanding()) {
37
+ const receipt = await readRuntimeExecutionSettlement(
38
+ directory,
39
+ previous.sessionId,
40
+ previous.cwd,
41
+ previous.executionId,
42
+ previous.beforeLaunch,
43
+ ).catch(() => "unknown" as const);
44
+ if (receipt !== "unknown") store.settle(previous.owner, previous.executionId, receipt);
45
+ }
46
+ store.admit({ owner: "pi-daddy", executionId, ...host, ...(beforeLaunch ? { beforeLaunch } : {}) });
47
+ const finish = (cleanup: "settled" | "not-started") => store.settle("pi-daddy", executionId, cleanup);
48
+ try {
49
+ if (id !== (await workingCopyId(target))) throw Error("Working copy changed during admission");
50
+ } catch (error) {
51
+ finish("not-started");
52
+ throw error;
53
+ }
54
+ return finish;
55
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-daddy",
3
- "version": "0.62.1",
3
+ "version": "0.63.0",
4
4
  "description": "Capability governance for pi sub-agents: spawn Agent Skills (SKILL.md) definitions whose allowed-tools becomes a grant that can only narrow going down a delegation tree, enforced by pi's own --tools allowlist, with an append-only ledger.",
5
5
  "keywords": [
6
6
  "pi-package",