pi-daddy 0.62.0 → 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 (89) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +28 -3
  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/context-handoff.d.ts +14 -0
  16. package/dist/kernel/context-handoff.d.ts.map +1 -1
  17. package/dist/kernel/context-handoff.js +17 -0
  18. package/dist/kernel/context-handoff.js.map +1 -1
  19. package/dist/kernel/dashboard-choice.d.ts +5 -0
  20. package/dist/kernel/dashboard-choice.d.ts.map +1 -1
  21. package/dist/kernel/dashboard-choice.js.map +1 -1
  22. package/dist/kernel/dashboard-observation.d.ts +31 -0
  23. package/dist/kernel/dashboard-observation.d.ts.map +1 -1
  24. package/dist/kernel/dashboard-observation.js +33 -1
  25. package/dist/kernel/dashboard-observation.js.map +1 -1
  26. package/dist/kernel/dashboard-request.d.ts +4 -0
  27. package/dist/kernel/dashboard-request.d.ts.map +1 -0
  28. package/dist/kernel/dashboard-request.js +8 -0
  29. package/dist/kernel/dashboard-request.js.map +1 -0
  30. package/dist/kernel/delegate.d.ts.map +1 -1
  31. package/dist/kernel/delegate.js +24 -8
  32. package/dist/kernel/delegate.js.map +1 -1
  33. package/dist/products/dashboard-choice-picker.d.ts +2 -0
  34. package/dist/products/dashboard-choice-picker.d.ts.map +1 -1
  35. package/dist/products/dashboard-choice-picker.js +46 -18
  36. package/dist/products/dashboard-choice-picker.js.map +1 -1
  37. package/dist/products/dashboard-cli.d.ts.map +1 -1
  38. package/dist/products/dashboard-cli.js +31 -4
  39. package/dist/products/dashboard-cli.js.map +1 -1
  40. package/dist/products/dashboard-components.d.ts +2 -0
  41. package/dist/products/dashboard-components.d.ts.map +1 -1
  42. package/dist/products/dashboard-components.js +81 -0
  43. package/dist/products/dashboard-components.js.map +1 -1
  44. package/dist/products/dashboard-panels.d.ts.map +1 -1
  45. package/dist/products/dashboard-panels.js +7 -2
  46. package/dist/products/dashboard-panels.js.map +1 -1
  47. package/dist/products/dashboard-screen.d.ts +2 -0
  48. package/dist/products/dashboard-screen.d.ts.map +1 -1
  49. package/dist/products/dashboard-screen.js +12 -3
  50. package/dist/products/dashboard-screen.js.map +1 -1
  51. package/dist/products/dashboard-session-client.d.ts +8 -0
  52. package/dist/products/dashboard-session-client.d.ts.map +1 -1
  53. package/dist/products/dashboard-session-client.js +54 -26
  54. package/dist/products/dashboard-session-client.js.map +1 -1
  55. package/dist/products/dashboard-task-controls.d.ts +6 -0
  56. package/dist/products/dashboard-task-controls.d.ts.map +1 -0
  57. package/dist/products/dashboard-task-controls.js +27 -0
  58. package/dist/products/dashboard-task-controls.js.map +1 -0
  59. package/extensions/dashboard-choice-controls.ts +33 -1
  60. package/extensions/dashboard-session-server.ts +67 -4
  61. package/extensions/dashboard-sources.ts +21 -2
  62. package/extensions/definition-describe.ts +3 -1
  63. package/extensions/delegate-chain.ts +6 -0
  64. package/extensions/delegation-artifacts.ts +34 -0
  65. package/extensions/delegation-operations.ts +30 -1
  66. package/extensions/delegation.ts +26 -2
  67. package/extensions/execute-child.ts +4 -0
  68. package/extensions/grants.ts +3 -0
  69. package/extensions/run-delegation.ts +58 -6
  70. package/extensions/runtime-snapshot.ts +23 -17
  71. package/extensions/session.ts +4 -0
  72. package/extensions/task-dispatch-controller.ts +384 -0
  73. package/extensions/task-inline-control.ts +21 -0
  74. package/extensions/task-worktree-writer.ts +55 -0
  75. package/package.json +1 -1
  76. package/src/governance/runtime-settlement.ts +44 -2
  77. package/src/governance/task-dispatch.ts +427 -0
  78. package/src/kernel/context-handoff.ts +19 -0
  79. package/src/kernel/dashboard-choice.ts +7 -1
  80. package/src/kernel/dashboard-observation.ts +67 -2
  81. package/src/kernel/dashboard-request.ts +8 -0
  82. package/src/kernel/delegate.ts +33 -14
  83. package/src/products/dashboard-choice-picker.ts +51 -16
  84. package/src/products/dashboard-cli.ts +33 -4
  85. package/src/products/dashboard-components.ts +84 -0
  86. package/src/products/dashboard-panels.ts +6 -1
  87. package/src/products/dashboard-screen.ts +14 -3
  88. package/src/products/dashboard-session-client.ts +79 -28
  89. package/src/products/dashboard-task-controls.ts +34 -0
@@ -12,6 +12,7 @@ const owners = new WeakMap<
12
12
  store: OperationArtifactStore;
13
13
  request: OperationRequest;
14
14
  reference?: OperationArtifactRef;
15
+ finalRetained?: boolean;
15
16
  display?: Pick<DashboardResultDescription, "agent" | "summary">;
16
17
  publish?: OperationFinalStore["publishArtifact"];
17
18
  }
@@ -27,6 +28,7 @@ export async function claimWithArtifact(
27
28
  display?: Pick<DashboardResultDescription, "agent" | "summary">,
28
29
  /** Exact pre-binding digest, for reading a completed ordinary operation only. Never used for election. */
29
30
  legacyRequestDigest?: string,
31
+ observe?: ReturnType<NonNullable<GrantsSession["bindTaskObservation"]>>,
30
32
  ): Promise<OperationClaim> {
31
33
  if (scope !== session.reloadLifecycle?.operationFinals) throw Error("Operation owner changed before admission");
32
34
  const store = scope?.artifacts;
@@ -131,12 +133,14 @@ export async function claimWithArtifact(
131
133
  }
132
134
  const state = { store, request: { ...request }, publish: scope.publishArtifact, display };
133
135
  owners.set(owned, state);
136
+ await observe?.(request.operationId, "delegation", "admitted", "Delegated work admitted");
134
137
  const started = owned.started!;
135
138
  owned.started = async (cwd, workspaceId) => {
136
139
  await initiative?.assertCurrent({ cwd, workspaceId });
137
140
  store.started(request, cwd, workspaceId);
138
141
  await started(cwd, workspaceId);
139
142
  owned.operation = { ...owned.operation, state: "running", cwd, workspaceId };
143
+ observe?.(request.operationId, "delegation", "running", "Delegated work started");
140
144
  };
141
145
  const finish = owned.finish!;
142
146
  owned.finish = async (status, runtime) => {
@@ -149,6 +153,35 @@ export async function claimWithArtifact(
149
153
  };
150
154
  if (!owners.get(owned)!.reference) retainOperationArtifact(owned, { operation: owned.operation });
151
155
  owned.operation.artifact = owners.get(owned)!.reference;
156
+ const work = runtime?.work;
157
+ if (
158
+ status === "settled" &&
159
+ work === "succeeded" &&
160
+ runtime?.control !== "failed" &&
161
+ owners.get(owned)?.finalRetained
162
+ ) {
163
+ observe?.(
164
+ request.operationId,
165
+ "delegation",
166
+ "result-retained",
167
+ "Delegated work settled with a retained answer",
168
+ /^[A-Za-z0-9][A-Za-z0-9:_-]{0,127}$/.test(request.operationId)
169
+ ? { type: "operation", id: request.operationId }
170
+ : undefined,
171
+ );
172
+ } else if (status === "not-started") {
173
+ observe?.(request.operationId, "delegation", status, "Delegated work did not start");
174
+ } else if (status === "uncertain") {
175
+ observe?.(request.operationId, "delegation", status, "Delegation outcome is uncertain");
176
+ } else {
177
+ const failed = work === "failed" || runtime?.control === "failed";
178
+ observe?.(
179
+ request.operationId,
180
+ "delegation",
181
+ failed ? "failed" : "settled",
182
+ failed ? "Delegated work failed" : "Delegation settled without confirmed delivery",
183
+ );
184
+ }
152
185
  if (status === "settled" && owned.operation.artifact) {
153
186
  // Artifact retention happens before live settlement. Wake the selected work map only after both.
154
187
  try {
@@ -165,6 +198,7 @@ export function retainOperationArtifact(claim: OperationClaim, outcome: Operatio
165
198
  if (!owner) return;
166
199
  const reference = owner.store.finish(owner.request, outcome);
167
200
  owner.reference = reference;
201
+ owner.finalRetained = outcome.final !== undefined;
168
202
  claim.operation.artifact = reference;
169
203
  // Pi receives only a small reference, never duplicated full authored content.
170
204
  try {
@@ -132,6 +132,9 @@ export async function claimDelegationOperation(
132
132
  signal?: AbortSignal,
133
133
  /** Trusted: bound by the calling tool from its own arguments and the session's describe memory; wording only. */
134
134
  definitionBinding?: DefinitionBinding,
135
+ taskObservation: ReturnType<
136
+ NonNullable<GrantsSession["bindTaskObservation"]>
137
+ > | null = session.bindTaskObservation?.(),
135
138
  ): Promise<OperationClaim | undefined> {
136
139
  const operationScope = session.reloadLifecycle?.operationFinals;
137
140
  const operationId = spec.operation_id;
@@ -139,6 +142,7 @@ export async function claimDelegationOperation(
139
142
  assertDelegationAuthority(session);
140
143
  if (!validOperationId(operationId)) throw Error("Invalid operation_id");
141
144
  if (signal?.aborted) throw Error("Operation request aborted");
145
+ const observe = taskObservation ?? undefined;
142
146
  await session.ensureDefinitions?.();
143
147
  assertDefinitionIdentity(session, spec, definitionBinding?.source);
144
148
  const context = { ...(await session.delegationContext()), ...session.parentToolContext?.(ctx) };
@@ -213,6 +217,7 @@ export async function claimDelegationOperation(
213
217
  operationScope,
214
218
  { agent, summary },
215
219
  legacyRequestDigest,
220
+ observe,
216
221
  );
217
222
  };
218
223
  if (!denied) return elect();
@@ -221,6 +226,8 @@ export async function claimDelegationOperation(
221
226
  ? new GovernanceRefusal(preview.refusal)
222
227
  : Error(preview.reason ?? "Operation request is not authorized");
223
228
  const evidenceErrors: unknown[] = [];
229
+ let recordedNotStarted = false;
230
+ let existingState: string | undefined;
224
231
  try {
225
232
  await recordDelegationDecision({ session, plan: preview, ids, agent: spec.agent });
226
233
  } catch (error) {
@@ -233,12 +240,34 @@ export async function claimDelegationOperation(
233
240
  // Election records identity, not permission. Only this newly elected, unlaunched
234
241
  // occurrence may supply no-start proof; a duplicate must never rewrite its owner.
235
242
  const claim = await elect();
236
- if (!claim.reused) await claim.finish!("not-started", { cleanup: { state: "not-started" } });
243
+ if (!claim.reused) {
244
+ await claim.finish!("not-started", { cleanup: { state: "not-started" } });
245
+ recordedNotStarted = true;
246
+ } else existingState = claim.operation.state;
237
247
  } catch (error) {
238
248
  // Keep the typed governance refusal and make missing/conflicting evidence explicit.
239
249
  evidenceErrors.push(error);
240
250
  failure.message += `; operation evidence unavailable: ${String(error)}`;
241
251
  }
252
+ if (preview.refusal?.code === "CONTEXT_REQUEST_INVALID") {
253
+ if (recordedNotStarted) {
254
+ failure.message +=
255
+ ` Operation ${JSON.stringify(operationId)} is recorded not-started; its ID remains terminal. ` +
256
+ (spec.agent && session.definitions.get(spec.agent)?.binding
257
+ ? "Recover the original operation through its workflow owner, then use the corrected delegation arguments it provides. " +
258
+ "Do not invent a replacement operation ID or repeat completed work."
259
+ : "Correct the context arguments and make one new attempt with a new operation_id, keeping this refused record. " +
260
+ "This is an argument correction, not a retry of executed work; all current permission checks still apply.");
261
+ } else if (existingState !== undefined) {
262
+ failure.message +=
263
+ ` Operation ${JSON.stringify(operationId)} already exists (${existingState}). ` +
264
+ "Inspect or recover that original operation before any new attempt; this refusal did not replace its record.";
265
+ } else {
266
+ failure.message +=
267
+ "No reliable operation no-start record was returned. Inspect or recover the original operation before any new attempt; " +
268
+ "this refusal alone does not prove earlier work never started.";
269
+ }
270
+ }
242
271
  if (evidenceErrors.length)
243
272
  failure.cause =
244
273
  evidenceErrors.length === 1
@@ -307,6 +307,8 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
307
307
  prepareArguments: withoutRetiredDelegationArguments,
308
308
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
309
309
  // Reported through Pi's tool_result hook if this call throws after its child ran (2026-11-17).
310
+ const taskAdmission = session.taskDispatch?.capture();
311
+ const taskObservation = session.bindTaskObservation?.() ?? null;
310
312
  const usageReport = childUsageReport(session, _toolCallId);
311
313
  assertDelegationAuthority(session);
312
314
  await session.ensureDefinitions?.();
@@ -319,7 +321,15 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
319
321
  // `delegate` for up to DEFAULT_TIMEOUT_MS — sixty minutes by default.
320
322
  const progress = progressReporter(session, [params.agent ?? "delegate"], onUpdate as never);
321
323
  const occurrence = newDelegationOccurrence(session, 0);
322
- const operationClaim = await claimDelegationOperation(session, spec, occurrence, ctx, signal, definitionBinding);
324
+ const operationClaim = await claimDelegationOperation(
325
+ session,
326
+ spec,
327
+ occurrence,
328
+ ctx,
329
+ signal,
330
+ definitionBinding,
331
+ taskObservation,
332
+ );
323
333
  // Public capture keeps the caller's own request; the bound ID is in details.
324
334
  const capture = publicEvidenceCall(
325
335
  session.publicEvidence,
@@ -349,6 +359,8 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
349
359
  ctx,
350
360
  signal,
351
361
  {
362
+ taskObservation,
363
+ taskAdmission,
352
364
  operationClaim,
353
365
  definitionBinding,
354
366
  onProgress: progress.sink(0),
@@ -418,6 +430,8 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
418
430
  parameters: delegateAllParams,
419
431
  prepareArguments: withoutRetiredDelegationArguments,
420
432
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
433
+ const taskAdmission = session.taskDispatch?.capture();
434
+ const taskObservation = session.bindTaskObservation?.() ?? null;
421
435
  const usageReport = childUsageReport(session, _toolCallId);
422
436
  assertDelegationAuthority(session);
423
437
  const children = params.children ?? [];
@@ -432,7 +446,15 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
432
446
  try {
433
447
  for (const [index, child] of bound.specs.entries())
434
448
  claims.push(
435
- await claimDelegationOperation(session, child, occurrences[index], ctx, signal, bound.bindings[index]),
449
+ await claimDelegationOperation(
450
+ session,
451
+ child,
452
+ occurrences[index],
453
+ ctx,
454
+ signal,
455
+ bound.bindings[index],
456
+ taskObservation,
457
+ ),
436
458
  );
437
459
  } catch (error) {
438
460
  await Promise.all(claims.map((claim) => claim?.finish?.("not-started")));
@@ -479,6 +501,8 @@ export function registerDelegationTools(pi: ExtensionAPI, session: GrantsSession
479
501
  : reserveDelegationCapacity(session, occurrences[index].executionId, split.perChild);
480
502
  enteredDelegation = true;
481
503
  return await runOneDelegation(session, child, occurrences[index], split.perChild, ctx, signal, {
504
+ taskObservation,
505
+ taskAdmission,
482
506
  operationClaim: claims[index],
483
507
  definitionBinding: bound.bindings[index],
484
508
  capacityReservation,
@@ -147,6 +147,9 @@ export interface ChildProgressUpdate {
147
147
  * blaming "ledger" (R-99). The failure is reported alongside the outcome instead of replacing it.
148
148
  */
149
149
  export interface ChildExecutionInput {
150
+ beforeRuntimeBegin?: (
151
+ runtime: import("../src/governance/runtime-settlement.ts").RuntimeSettlement | undefined,
152
+ ) => void;
150
153
  operationClaim?: import("../src/kernel/dispatch-operation.ts").OperationClaim;
151
154
  /** Composition-only launch observation; no permission or result authority. */
152
155
  onExecutorEntry?: () => void;
@@ -179,6 +182,7 @@ export async function executePlannedChild(input: ChildExecutionInput): Promise<D
179
182
  try {
180
183
  const limits = childExecutionLimits(input.session);
181
184
  input = { ...input, cwd: await realpath(input.preparedWorkspace?.workspace.root ?? input.cwd) };
185
+ input.beforeRuntimeBegin?.(runtime);
182
186
  runtime?.begin(input.executionId);
183
187
  registered = Boolean(runtime);
184
188
  // Registered before the child exists and closed once it has settled, on every path: an unknown or finished
@@ -65,6 +65,7 @@ import { bindReloadLifecycle, expectNewSession } from "./reload-environment.ts";
65
65
  import { reconcileActiveDelegationTools } from "./delegation-activation.ts";
66
66
  import { resolveExecutor } from "./executor-session.ts";
67
67
  import { reportSelectedDefinitions, reportSessionStart, type SessionReportContext } from "./session-report.ts";
68
+ import { taskInlineControl } from "./task-inline-control.ts";
68
69
  import { SPAWN_TOOLS, tripwireReason } from "./tripwire.ts";
69
70
  import { reportGrantStoreRefusal } from "./grant-store-refusal.ts";
70
71
  import {
@@ -457,6 +458,8 @@ export default function (pi: ExtensionAPI, trustedSession?: GrantsSession) {
457
458
  * so a tool-name check cannot see it. This catches the ordinary case loudly; it is not a boundary.
458
459
  */
459
460
  pi.on("tool_call", async (event) => {
461
+ const held = await taskInlineControl(event.toolName, session);
462
+ if (held) return held;
460
463
  if (!session.governed || !SPAWN_TOOLS.has(event.toolName)) return undefined;
461
464
 
462
465
  const reason = tripwireReason(event.toolName);
@@ -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;