pi-daddy 0.47.1 → 0.48.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 +26 -1
  3. package/dist/executors/child-final.d.ts +3 -0
  4. package/dist/executors/child-final.d.ts.map +1 -1
  5. package/dist/executors/child-final.js +13 -1
  6. package/dist/executors/child-final.js.map +1 -1
  7. package/dist/governance/auto-mode-policy.d.ts.map +1 -1
  8. package/dist/governance/auto-mode-policy.js +32 -1
  9. package/dist/governance/auto-mode-policy.js.map +1 -1
  10. package/dist/governance/dispatch-operation-client.d.ts +4 -0
  11. package/dist/governance/dispatch-operation-client.d.ts.map +1 -0
  12. package/dist/governance/dispatch-operation-client.js +93 -0
  13. package/dist/governance/dispatch-operation-client.js.map +1 -0
  14. package/dist/governance/dispatch-operations.d.ts +17 -0
  15. package/dist/governance/dispatch-operations.d.ts.map +1 -0
  16. package/dist/governance/dispatch-operations.js +81 -0
  17. package/dist/governance/dispatch-operations.js.map +1 -0
  18. package/dist/governance/execution-retention.d.ts +5 -4
  19. package/dist/governance/execution-retention.d.ts.map +1 -1
  20. package/dist/governance/execution-retention.js +3 -1
  21. package/dist/governance/execution-retention.js.map +1 -1
  22. package/dist/governance/native-session.d.ts +10 -1
  23. package/dist/governance/native-session.d.ts.map +1 -1
  24. package/dist/governance/native-session.js +15 -0
  25. package/dist/governance/native-session.js.map +1 -1
  26. package/dist/governance/retention-contract.d.ts +30 -0
  27. package/dist/governance/retention-contract.d.ts.map +1 -1
  28. package/dist/governance/retention-contract.js +9 -4
  29. package/dist/governance/retention-contract.js.map +1 -1
  30. package/dist/kernel/auto-mode.d.ts +1 -0
  31. package/dist/kernel/auto-mode.d.ts.map +1 -1
  32. package/dist/kernel/auto-mode.js.map +1 -1
  33. package/dist/kernel/chain.d.ts +1 -0
  34. package/dist/kernel/chain.d.ts.map +1 -1
  35. package/dist/kernel/chain.js.map +1 -1
  36. package/dist/kernel/delegate.d.ts.map +1 -1
  37. package/dist/kernel/delegate.js +8 -0
  38. package/dist/kernel/delegate.js.map +1 -1
  39. package/dist/kernel/dispatch-operation.d.ts +47 -0
  40. package/dist/kernel/dispatch-operation.d.ts.map +1 -0
  41. package/dist/kernel/dispatch-operation.js +4 -0
  42. package/dist/kernel/dispatch-operation.js.map +1 -0
  43. package/dist/kernel/propagation.d.ts +4 -1
  44. package/dist/kernel/propagation.d.ts.map +1 -1
  45. package/dist/kernel/propagation.js +11 -1
  46. package/dist/kernel/propagation.js.map +1 -1
  47. package/dist/products/activity-timeline.d.ts +8 -0
  48. package/dist/products/activity-timeline.d.ts.map +1 -1
  49. package/dist/products/activity-timeline.js +8 -1
  50. package/dist/products/activity-timeline.js.map +1 -1
  51. package/dist/products/dashboard-screen.d.ts +1 -0
  52. package/dist/products/dashboard-screen.d.ts.map +1 -1
  53. package/dist/products/dashboard-screen.js +20 -2
  54. package/dist/products/dashboard-screen.js.map +1 -1
  55. package/extensions/activity-timeline.ts +12 -2
  56. package/extensions/delegate-chain.ts +46 -4
  57. package/extensions/delegation-operations.ts +171 -0
  58. package/extensions/delegation.ts +34 -10
  59. package/extensions/execute-child.ts +21 -3
  60. package/extensions/execution-evidence.ts +3 -0
  61. package/extensions/fanout-outcome.ts +1 -0
  62. package/extensions/grants.ts +2 -3
  63. package/extensions/run-delegation.ts +58 -3
  64. package/extensions/runtime-snapshot.ts +59 -1
  65. package/package.json +1 -1
  66. package/src/executors/child-final.ts +17 -1
  67. package/src/governance/auto-mode-policy.ts +27 -1
  68. package/src/governance/dispatch-operation-client.ts +96 -0
  69. package/src/governance/dispatch-operations.ts +81 -0
  70. package/src/governance/execution-retention.ts +7 -3
  71. package/src/governance/native-session.ts +28 -1
  72. package/src/governance/retention-contract.ts +9 -4
  73. package/src/kernel/auto-mode.ts +1 -0
  74. package/src/kernel/chain.ts +1 -0
  75. package/src/kernel/delegate.ts +14 -0
  76. package/src/kernel/dispatch-operation.ts +38 -0
  77. package/src/kernel/propagation.ts +18 -1
  78. package/src/products/activity-timeline.ts +10 -0
  79. package/src/products/dashboard-screen.ts +21 -2
@@ -1,3 +1,5 @@
1
+ import { createDispatchOperations } from "./dispatch-operations.ts";
2
+ import { connectDispatchOperations } from "./dispatch-operation-client.ts";
1
3
  /** Root-owned live Auto authority. Descendants receive read/admit access, never mutation access. */
2
4
  import { randomBytes, randomUUID } from "node:crypto";
3
5
  import { chmod, unlink } from "node:fs/promises";
@@ -38,6 +40,7 @@ export async function createAutoModeAuthority(initial: {
38
40
  source = initial.source,
39
41
  revision = 0,
40
42
  closed = false;
43
+ const operations = createDispatchOperations();
41
44
  const pending = new Map<string, PendingApproval>();
42
45
  const waiters = new Set<() => void>();
43
46
  const sockets = new Set<Socket>();
@@ -92,12 +95,14 @@ export async function createAutoModeAuthority(initial: {
92
95
  const controller = new AbortController();
93
96
  let input = "",
94
97
  handled = false,
95
- untrack: (() => void) | undefined;
98
+ untrack: (() => void) | undefined,
99
+ abandonOperation: (() => void) | undefined;
96
100
  socket.on("error", () => {});
97
101
  socket.once("close", () => {
98
102
  sockets.delete(socket);
99
103
  controller.abort();
100
104
  untrack?.();
105
+ abandonOperation?.();
101
106
  });
102
107
  const reply = (value: unknown) => {
103
108
  if (!socket.destroyed) socket.end(JSON.stringify(value) + "\n");
@@ -129,6 +134,21 @@ export async function createAutoModeAuthority(initial: {
129
134
  } else if (request.action === "pending" && validPending(request.approval)) {
130
135
  socket.setTimeout(0);
131
136
  untrack = trackPending(request.approval);
137
+ } else if (request.action === "operation-claim") {
138
+ const value = operations.claim(request.request);
139
+ if (!value.reused) {
140
+ socket.setTimeout(0);
141
+ abandonOperation = () => operations.abandoned(value.operation.operationId, value.ticket!);
142
+ socket.write(JSON.stringify({ ok: true, value }) + "\n");
143
+ } else reply({ ok: true, value });
144
+ } else if (request.action === "operation-read") {
145
+ reply({ ok: true, value: operations.read(request.operationId) });
146
+ } else if (request.action === "operation-started") {
147
+ operations.started(request.operationId, request.ticket, request.cwd, request.workspaceId);
148
+ reply({ ok: true });
149
+ } else if (request.action === "operation-finish") {
150
+ operations.finish(request.operationId, request.ticket, request.state, request.runtime);
151
+ reply({ ok: true });
132
152
  } else throw new Error("Unknown Auto policy action");
133
153
  } catch (error) {
134
154
  reply({ ok: false, error: String(error) });
@@ -153,7 +173,9 @@ export async function createAutoModeAuthority(initial: {
153
173
  } catch {}
154
174
  };
155
175
  process.once("exit", exit);
176
+ const operationAccess = connectDispatchOperations(reference);
156
177
  return {
178
+ operations: operationAccess,
157
179
  reference,
158
180
  snapshot,
159
181
  read: async () => snapshot(),
@@ -175,6 +197,7 @@ export async function createAutoModeAuthority(initial: {
175
197
  close: async () => {
176
198
  if (closed) return;
177
199
  closed = true;
200
+ operationAccess.close();
178
201
  enabled = false;
179
202
  for (const wake of [...waiters]) wake();
180
203
  for (const socket of sockets) socket.destroy();
@@ -233,6 +256,7 @@ function request(ref: AutoModeRef, action: "read" | "admit" | "wait", signal?: A
233
256
  }
234
257
 
235
258
  export function connectAutoMode(reference: AutoModeRef): AutoModeReader {
259
+ const operations = connectDispatchOperations(reference);
236
260
  let closed = false;
237
261
  const active = new Set<AbortController>();
238
262
  const pending = new Set<Socket>();
@@ -252,6 +276,7 @@ export function connectAutoMode(reference: AutoModeRef): AutoModeReader {
252
276
  };
253
277
  return {
254
278
  reference,
279
+ operations,
255
280
  read: async () => {
256
281
  const value = (await call("read")) as AutoModeSnapshot;
257
282
  if (
@@ -290,6 +315,7 @@ export function connectAutoMode(reference: AutoModeRef): AutoModeReader {
290
315
  },
291
316
  close: async () => {
292
317
  closed = true;
318
+ operations.close();
293
319
  for (const controller of active) controller.abort();
294
320
  for (const socket of pending) socket.destroy();
295
321
  },
@@ -0,0 +1,96 @@
1
+ /** A held claim connection makes caller loss uncertain; another caller never inherits execution. */
2
+ import { createConnection, type Socket } from "node:net";
3
+ import type { AutoModeRef } from "../kernel/auto-mode.ts";
4
+ import type {
5
+ OperationAccess,
6
+ OperationClaim,
7
+ OperationReference,
8
+ OperationRequest,
9
+ } from "../kernel/dispatch-operation.ts";
10
+
11
+ export function connectDispatchOperations(reference: AutoModeRef): OperationAccess {
12
+ const sockets = new Set<Socket>();
13
+ let closed = false;
14
+ const request = (
15
+ action: string,
16
+ input: object,
17
+ signal?: AbortSignal,
18
+ hold = false,
19
+ ): Promise<{ value: any; socket: Socket }> =>
20
+ new Promise((resolve, reject) => {
21
+ if (closed || signal?.aborted) return reject(Error("Operation owner unavailable or request aborted"));
22
+ const socket = createConnection(reference.socketPath);
23
+ sockets.add(socket);
24
+ let output = "",
25
+ answered = false;
26
+ const cleanup = () => signal?.removeEventListener("abort", abort);
27
+ const fail = (error: Error) => {
28
+ cleanup();
29
+ socket.destroy();
30
+ if (!answered) {
31
+ answered = true;
32
+ reject(error);
33
+ }
34
+ };
35
+ const abort = () => fail(Error("Operation request aborted"));
36
+ signal?.addEventListener("abort", abort, { once: true });
37
+ socket.setEncoding("utf8");
38
+ socket.setTimeout(2000, () => fail(Error("Operation owner unavailable")));
39
+ socket.once("error", () => fail(Error("Operation owner unavailable")));
40
+ socket.once("connect", () => socket.write(JSON.stringify({ ...reference, action, ...input }) + "\n"));
41
+ socket.once("close", () => {
42
+ sockets.delete(socket);
43
+ cleanup();
44
+ if (!answered) fail(Error("Operation owner disconnected"));
45
+ });
46
+ socket.on("data", (chunk) => {
47
+ if (answered) return;
48
+ output += chunk;
49
+ if (output.length > 65536) return fail(Error("Operation response too large"));
50
+ const end = output.indexOf("\n");
51
+ if (end < 0) return;
52
+ try {
53
+ const reply = JSON.parse(output.slice(0, end));
54
+ if (reply.ok !== true) throw Error(reply.error ?? "Operation request failed");
55
+ answered = true;
56
+ cleanup();
57
+ socket.setTimeout(0);
58
+ if (!hold || reply.value?.reused) socket.destroy();
59
+ resolve({ value: reply.value, socket });
60
+ } catch (error) {
61
+ fail(error instanceof Error ? error : Error(String(error)));
62
+ }
63
+ });
64
+ });
65
+ return {
66
+ claim: async (input: OperationRequest, signal?: AbortSignal): Promise<OperationClaim> => {
67
+ const { value, socket } = await request("operation-claim", { request: input }, signal, true);
68
+ if (value.reused) return { operation: value.operation, reused: true };
69
+ const update = async (action: string, data: object) => {
70
+ if (socket.destroyed) throw Error("Operation claim owner disconnected; settlement is uncertain");
71
+ return request(action, { operationId: input.operationId, ticket: value.ticket, ...data });
72
+ };
73
+ return {
74
+ operation: value.operation,
75
+ reused: false,
76
+ started: async (cwd, workspaceId) => {
77
+ await update("operation-started", { cwd, workspaceId });
78
+ },
79
+ finish: async (state, runtime) => {
80
+ try {
81
+ await update("operation-finish", { state, runtime });
82
+ Object.assign(value.operation, (await request("operation-read", { operationId: input.operationId })).value);
83
+ } finally {
84
+ socket.destroy();
85
+ }
86
+ },
87
+ };
88
+ },
89
+ read: async (operationId: string) =>
90
+ (await request("operation-read", { operationId })).value as OperationReference | null,
91
+ close: () => {
92
+ closed = true;
93
+ for (const socket of sockets) socket.destroy();
94
+ },
95
+ };
96
+ }
@@ -0,0 +1,81 @@
1
+ /** Atomic leader election at the tree owner. No task text, execution permission or cached output. */
2
+ import { randomBytes } from "node:crypto";
3
+ import type { OperationReference, OperationRequest } from "../kernel/dispatch-operation.ts";
4
+ import { validOperationId } from "../kernel/dispatch-operation.ts";
5
+
6
+ export function createDispatchOperations() {
7
+ const records = new Map<string, { digest: string; ticket: string; value: OperationReference }>();
8
+ const copy = (value: OperationReference) => structuredClone(value);
9
+ const requireTicket = (id: string, ticket: string) => {
10
+ const row = records.get(id);
11
+ if (!row || typeof ticket !== "string" || row.ticket !== ticket) throw Error("Operation owner mismatch");
12
+ return row;
13
+ };
14
+ return {
15
+ claim(request: OperationRequest) {
16
+ if (
17
+ !request ||
18
+ !validOperationId(request.operationId) ||
19
+ typeof request.requestDigest !== "string" ||
20
+ !/^[a-f0-9]{64}$/.test(request.requestDigest) ||
21
+ typeof request.executionId !== "string" ||
22
+ !request.executionId.startsWith("exec:") ||
23
+ request.executionId.length > 128 ||
24
+ typeof request.cwd !== "string" ||
25
+ !request.cwd.startsWith("/") ||
26
+ request.cwd.length > 4096 ||
27
+ !(request.workspaceId === null || typeof request.workspaceId === "string")
28
+ )
29
+ throw Error("Invalid dispatch operation request");
30
+ const old = records.get(request.operationId);
31
+ if (old) {
32
+ if (old.digest !== request.requestDigest)
33
+ throw Error("Operation identity conflict; inspect the original request before choosing a new operation_id");
34
+ return { reused: true, operation: copy(old.value) };
35
+ }
36
+ // Never evict a terminal ID and accidentally permit a mutation to run twice.
37
+ if (records.size >= 4096) throw Error("Session operation registry is full; no dispatch was admitted");
38
+ const now = new Date().toISOString(),
39
+ ticket = randomBytes(24).toString("hex");
40
+ const value: OperationReference = {
41
+ operationId: request.operationId,
42
+ executionId: request.executionId,
43
+ cwd: request.cwd,
44
+ workspaceId: request.workspaceId,
45
+ state: "admitting",
46
+ startedAt: now,
47
+ updatedAt: now,
48
+ };
49
+ records.set(request.operationId, { digest: request.requestDigest, ticket, value });
50
+ return { reused: false, operation: copy(value), ticket };
51
+ },
52
+ read(id: string) {
53
+ if (!validOperationId(id)) throw Error("Invalid operation_id");
54
+ const value = records.get(id)?.value;
55
+ return value ? copy(value) : null;
56
+ },
57
+ started(id: string, ticket: string, cwd: string, workspaceId: string | null) {
58
+ const row = requireTicket(id, ticket);
59
+ if (row.value.state !== "admitting") throw Error("Operation is no longer admitting");
60
+ if (
61
+ typeof cwd !== "string" ||
62
+ !cwd.startsWith("/") ||
63
+ cwd.length > 4096 ||
64
+ !(workspaceId === null || typeof workspaceId === "string")
65
+ )
66
+ throw Error("Invalid operation workspace");
67
+ row.value = { ...row.value, state: "running", cwd, workspaceId, updatedAt: new Date().toISOString() };
68
+ },
69
+ finish(id: string, ticket: string, state: OperationReference["state"], runtime?: OperationReference["runtime"]) {
70
+ const row = requireTicket(id, ticket);
71
+ if (!["settled", "not-started", "uncertain"].includes(state)) throw Error("Invalid operation terminal state");
72
+ if (!["admitting", "running"].includes(row.value.state)) throw Error("Operation already ended");
73
+ row.value = { ...row.value, state, ...(runtime ? { runtime } : {}), updatedAt: new Date().toISOString() };
74
+ },
75
+ abandoned(id: string, ticket: string) {
76
+ const row = requireTicket(id, ticket);
77
+ if (["admitting", "running"].includes(row.value.state))
78
+ row.value = { ...row.value, state: "uncertain", updatedAt: new Date().toISOString() };
79
+ },
80
+ };
81
+ }
@@ -8,6 +8,7 @@ import {
8
8
  type NativeSessionObservation,
9
9
  type NativeSessionManager,
10
10
  type NativeSessionCapture,
11
+ type CapturedSessionBranch,
11
12
  } from "./native-session.ts";
12
13
  export {
13
14
  buildExecutionRetentionManifest,
@@ -26,7 +27,7 @@ export { ENV_EXECUTION_ARCHIVE } from "../kernel/env-names.ts";
26
27
  import { isUnderPiProjectDir } from "../kernel/project-paths.ts";
27
28
 
28
29
  /** Operator-owned archive boundary; never a model-facing parameter or an authority source. */
29
- export const RETENTION_VERSION = "2.0";
30
+ export const RETENTION_VERSION = "2.1";
30
31
  const LIMIT = 1024 * 1024;
31
32
  const MAX_ACTIVE = 32;
32
33
  let active = 0;
@@ -49,7 +50,7 @@ export interface RetainedContent {
49
50
  bytes: number | null;
50
51
  }
51
52
  export interface ExecutionRetentionManifest {
52
- version: "2.0";
53
+ version: "2.0" | "2.1";
53
54
  archiveId: string;
54
55
  identity: RetentionIdentity;
55
56
  native: {
@@ -155,9 +156,10 @@ export function beginExecutionRetention(identity: RetentionIdentity, directory =
155
156
  let nativeTask: Promise<void> | undefined;
156
157
  let nextNative:
157
158
  | {
158
- source: "herdr-id" | "herdr-path" | "pi-session-file" | "pi-session-manager";
159
+ source: "herdr-id" | "herdr-path" | "pi-session-file" | "pi-session-manager" | "pi-captured-final";
159
160
  value: string;
160
161
  manager?: NativeSessionManager;
162
+ capturedBranch?: CapturedSessionBranch;
161
163
  }
162
164
  | undefined;
163
165
  let pinnedSessionId: string | undefined;
@@ -236,6 +238,7 @@ export function beginExecutionRetention(identity: RetentionIdentity, directory =
236
238
  source: reference.source,
237
239
  value: reference.value,
238
240
  ...(reference.manager ? { manager: reference.manager } : {}),
241
+ ...(reference.capturedBranch ? { capturedBranch: { ...reference.capturedBranch } } : {}),
239
242
  };
240
243
  if (nativeTask) return;
241
244
  nativeTask = Promise.resolve()
@@ -258,6 +261,7 @@ export function beginExecutionRetention(identity: RetentionIdentity, directory =
258
261
  path: current.value,
259
262
  source: current.source,
260
263
  manager: current.manager,
264
+ capturedBranch: current.capturedBranch,
261
265
  expectedSessionId: pinnedSessionId,
262
266
  expectedFile: pinnedFile,
263
267
  });
@@ -7,7 +7,8 @@ import { ENV_NATIVE_SESSION_ROOT } from "../kernel/env-names.ts";
7
7
  export { ENV_NATIVE_SESSION_ROOT } from "../kernel/env-names.ts";
8
8
 
9
9
  export const MAX_NATIVE_SESSION_BYTES = 1024 * 1024;
10
- export type NativeSessionSource = "herdr-id" | "herdr-path" | "pi-session-file" | "pi-session-manager";
10
+ export type NativeSessionSource =
11
+ "herdr-id" | "herdr-path" | "pi-session-file" | "pi-session-manager" | "pi-captured-final";
11
12
  export interface NativeSessionObservation {
12
13
  source: NativeSessionSource | null;
13
14
  status: "missing" | "verified" | "invalid" | "changed" | "truncated" | "unsupported";
@@ -25,6 +26,13 @@ export interface NativeSessionCapture {
25
26
  bytes?: Buffer;
26
27
  fileIdentity?: { device: string; inode: string };
27
28
  }
29
+ /** Byte-bound metadata from the executor's qualified native final, not a locator-derived branch. */
30
+ export interface CapturedSessionBranch {
31
+ path: string;
32
+ sessionId: string;
33
+ leafId: string;
34
+ sha256: string;
35
+ }
28
36
  /** Read-only methods of pi 0.84.2's public SessionManager; no runtime/session creation or model work. */
29
37
  export interface NativeSessionManager {
30
38
  getSessionFile(): string | undefined;
@@ -59,6 +67,7 @@ export function parseNativeSessionBytes(
59
67
  expectedSessionId?: string;
60
68
  truncated?: boolean;
61
69
  liveLeaf?: { sessionId: string; leafId: string | null };
70
+ capturedBranch?: CapturedSessionBranch;
62
71
  },
63
72
  ): NativeSessionCapture {
64
73
  const observation = { ...missingNativeSession(), source: input.source, sessionPath: input.path };
@@ -138,6 +147,23 @@ export function parseNativeSessionBytes(
138
147
  observation.branchLeafId = input.liveLeaf.leafId;
139
148
  observation.branchState = "observed";
140
149
  }
150
+ if (input.source === "pi-captured-final" && !input.capturedBranch)
151
+ return fail("invalid", "native-session-final-branch-missing");
152
+ if (input.capturedBranch) {
153
+ const branch = input.capturedBranch;
154
+ if (
155
+ input.source !== "pi-captured-final" ||
156
+ branch.path !== input.path ||
157
+ branch.sessionId !== header.id ||
158
+ branch.sha256 !== observation.sha256 ||
159
+ !ids.has(branch.leafId) ||
160
+ (input.liveLeaf && input.liveLeaf.leafId !== branch.leafId)
161
+ ) {
162
+ return fail("changed", "native-session-final-branch-mismatch");
163
+ }
164
+ observation.branchLeafId = branch.leafId;
165
+ observation.branchState = "observed";
166
+ }
141
167
  observation.status = "verified";
142
168
  observation.reason = observation.branchState === "unknown" ? "active-branch-unknown" : null;
143
169
  return result;
@@ -150,6 +176,7 @@ export async function readNativeSession(input: {
150
176
  expectedSessionId?: string;
151
177
  allowedRoot?: string;
152
178
  manager?: NativeSessionManager;
179
+ capturedBranch?: CapturedSessionBranch;
153
180
  expectedFile?: { device: string; inode: string };
154
181
  }): Promise<NativeSessionCapture> {
155
182
  const gap = (status: NativeSessionObservation["status"], reason: string): NativeSessionCapture => ({
@@ -31,7 +31,7 @@ export const RETENTION_SCHEMA = freeze({
31
31
  $schema: "https://json-schema.org/draft/2020-12/schema",
32
32
  $id: "https://pi-daddy.local/contracts/execution-retention/v2/manifest.schema.json",
33
33
  ...closed({
34
- version: literal("2.0"),
34
+ version: { enum: ["2.0", "2.1"] },
35
35
  archiveId: uuid,
36
36
  identity: closed({
37
37
  executionId: string(),
@@ -54,7 +54,7 @@ export const RETENTION_SCHEMA = freeze({
54
54
  branchLeafId: nullable(string(128)),
55
55
  }),
56
56
  nativeSession: closed({
57
- source: { enum: [null, "herdr-id", "herdr-path", "pi-session-file", "pi-session-manager"] },
57
+ source: { enum: [null, "herdr-id", "herdr-path", "pi-session-file", "pi-session-manager", "pi-captured-final"] },
58
58
  status: { enum: ["missing", "verified", "invalid", "changed", "truncated", "unsupported"] },
59
59
  sessionId: nullable(uuid),
60
60
  sessionPath: nullable(string(4096)),
@@ -101,6 +101,10 @@ export const RETENTION_SCHEMA = freeze({
101
101
  acceptance: literal("not-assessed"),
102
102
  }),
103
103
  allOf: [
104
+ {
105
+ if: { properties: { version: literal("2.0") } },
106
+ then: { properties: { nativeSession: { properties: { source: { not: literal("pi-captured-final") } } } } },
107
+ },
104
108
  {
105
109
  if: { properties: { state: literal("running") } },
106
110
  then: { properties: { outcome: literal(null) } },
@@ -162,7 +166,7 @@ export function buildExecutionRetentionManifest(value: unknown): ExecutionRetent
162
166
  }
163
167
  };
164
168
  inspect(value, 0);
165
- if (!validator.Check(value)) throw new TypeError("invalid execution-retention 2.0 manifest");
169
+ if (!validator.Check(value)) throw new TypeError("invalid execution-retention 2.x manifest");
166
170
  const m = JSON.parse(JSON.stringify(value)) as ExecutionRetentionManifest;
167
171
  if (
168
172
  m.native.sessionId !== m.nativeSession.sessionId ||
@@ -178,7 +182,8 @@ export function buildExecutionRetentionManifest(value: unknown): ExecutionRetent
178
182
  }
179
183
  if (
180
184
  m.nativeSession.branchState === "observed" &&
181
- (m.nativeSession.source !== "pi-session-manager" || m.nativeSession.status !== "verified")
185
+ (!["pi-session-manager", "pi-captured-final"].includes(m.nativeSession.source ?? "") ||
186
+ m.nativeSession.status !== "verified")
182
187
  )
183
188
  throw new TypeError("unverified active native branch");
184
189
  if (
@@ -19,6 +19,7 @@ export interface AutoModeRef {
19
19
  }
20
20
  export interface AutoModeReader {
21
21
  readonly reference: AutoModeRef;
22
+ readonly operations?: import("./dispatch-operation.ts").OperationAccess;
22
23
  read(): Promise<AutoModeSnapshot>;
23
24
  /** Linearization point: only a current ON answer admits new work. No approval is banked. */
24
25
  admit(signal?: AbortSignal): Promise<boolean>;
@@ -152,6 +152,7 @@ export function composeStepTask(template: string, previous: string | undefined):
152
152
 
153
153
  /** One chain step as `runOneDelegation` takes it: the operator's spec with its task composed. */
154
154
  export interface ChainStep {
155
+ operation_id?: string;
155
156
  definitionId?: string;
156
157
  task: string;
157
158
  agent?: string;
@@ -201,6 +201,20 @@ export function planDelegation(request: DelegationRequest, ctx: DelegationContex
201
201
  requested = (request.tools ?? []).map(normaliseCapability);
202
202
  }
203
203
 
204
+ // Coordinator-only qualification does not authorize loading native Codemode or its raw model API in children.
205
+ const coordinatorOnly = requested.filter((capability) =>
206
+ ["tool:codemode", "ext:codemode", "tool:principal_codemode", "ext:principal_codemode"].includes(capability),
207
+ );
208
+ if (coordinatorOnly.length)
209
+ return denied(
210
+ {
211
+ ...empty,
212
+ requested,
213
+ reason: `Codemode is qualified only for the coordinator; governed children cannot receive ${coordinatorOnly.join(", ")}`,
214
+ },
215
+ "UNKNOWN_TOOL",
216
+ );
217
+
204
218
  // ADR-0078. A declared `context:` id is a CEILING, not a request: a definition that permits forking must not
205
219
  // fork on every spawn. So the declared modes come out of `requested` and exactly the one this call asked for
206
220
  // goes back in.
@@ -0,0 +1,38 @@
1
+ /** Explicit operation identity prevents duplicate dispatch, never authorizes work or caches results. */
2
+ export interface OperationReference {
3
+ operationId: string;
4
+ executionId: string;
5
+ state: "admitting" | "running" | "settled" | "not-started" | "uncertain";
6
+ cwd: string;
7
+ workspaceId: string | null;
8
+ startedAt: string;
9
+ updatedAt: string;
10
+ runtime?: {
11
+ control?: "failed";
12
+ work?: "succeeded" | "failed" | "unknown";
13
+ final?: { state: string; sessionId?: string; messageId?: string; leafId?: string; sha256?: string };
14
+ cleanup?: { state: string; receiptPath?: string; executionId?: string };
15
+ };
16
+ }
17
+ export interface OperationRequest {
18
+ operationId: string;
19
+ requestDigest: string;
20
+ executionId: string;
21
+ cwd: string;
22
+ workspaceId: string | null;
23
+ }
24
+ export interface OperationClaim {
25
+ operation: OperationReference;
26
+ reused: boolean;
27
+ /** Only the elected caller receives these methods. Neither grants execution authority. */
28
+ started?(cwd: string, workspaceId: string | null): Promise<void>;
29
+ finish?(state: "settled" | "not-started" | "uncertain", runtime?: OperationReference["runtime"]): Promise<void>;
30
+ }
31
+ export interface OperationAccess {
32
+ claim(request: OperationRequest, signal?: AbortSignal): Promise<OperationClaim>;
33
+ read(operationId: string): Promise<OperationReference | null>;
34
+ close(): void;
35
+ }
36
+ export function validOperationId(value: unknown): value is string {
37
+ return typeof value === "string" && /^[a-zA-Z0-9][a-zA-Z0-9._:/-]{0,159}$/.test(value);
38
+ }
@@ -410,7 +410,24 @@ export function mergeChildEnv(parentEnv: NodeJS.ProcessEnv, planEnv: Record<stri
410
410
  }
411
411
 
412
412
  /** Extract bare tool names from a provider payload's tool array, tolerating provider shape differences. */
413
- export function observeToolNames(payload: unknown): string[] | null {
413
+ export function observeToolNames(
414
+ payload: unknown,
415
+ registered?: readonly { name: string; exposure?: string }[],
416
+ active?: readonly string[],
417
+ ): string[] | null {
418
+ // Pi's provider projection may hide declarations while tools remain callable from Codemode.
419
+ // Exposure metadata is native inventory, not authorization; deriveOwnGrant still intersects inheritance.
420
+ if (registered && active && registered.length > 0 && registered.every((tool) => typeof tool.exposure === "string")) {
421
+ const declared = new Set(active);
422
+ return registered
423
+ .filter(
424
+ (tool) =>
425
+ tool.exposure === "codemode" ||
426
+ tool.exposure === "deferred" ||
427
+ ((tool.exposure === "direct" || tool.exposure === "model-only") && declared.has(tool.name)),
428
+ )
429
+ .map((tool) => tool.name);
430
+ }
414
431
  if (!payload || typeof payload !== "object") return null;
415
432
  const record = payload as Record<string, unknown>;
416
433
  for (const key of ["tools", "functions"]) {
@@ -44,6 +44,8 @@ export interface ActivityEvent {
44
44
  agentId?: string;
45
45
  agent?: string;
46
46
  outcome?: string;
47
+ tool?: string;
48
+ cwd?: string;
47
49
  model?: string;
48
50
  thinking?: string;
49
51
  prompt?: ContentReference;
@@ -63,6 +65,8 @@ export interface TimelineTask {
63
65
  agent?: string;
64
66
  startedAt: string;
65
67
  endedAt?: string;
68
+ lastEvent?: { at: string; kind: string; tool?: string };
69
+ cwd?: string;
66
70
  status: "active" | "finished" | "failed" | "cancelled" | "needs-you";
67
71
  model?: string;
68
72
  thinking?: string;
@@ -122,6 +126,8 @@ function eventOf(value: unknown): ActivityEvent | null {
122
126
  )
123
127
  return null;
124
128
  if (
129
+ (event.tool !== undefined && !validId(event.tool)) ||
130
+ (event.cwd !== undefined && (typeof event.cwd !== "string" || !event.cwd || event.cwd.length > 4096)) ||
125
131
  (event.parentTaskId && !validId(event.parentTaskId)) ||
126
132
  (event.agentId && !validId(event.agentId)) ||
127
133
  (event.agent && !validId(event.agent)) ||
@@ -170,6 +176,10 @@ export function parseActivityTimeline(text: string): ActivityTimeline {
170
176
  };
171
177
  tasks.set(key, task);
172
178
  }
179
+ if (!task.lastEvent || Date.parse(event.at) >= Date.parse(task.lastEvent.at)) {
180
+ task.lastEvent = { at: event.at, kind: event.kind, ...(event.tool ? { tool: event.tool } : {}) };
181
+ if (event.cwd) task.cwd = event.cwd;
182
+ }
173
183
  if (event.kind === "task_started") {
174
184
  task.model = event.model;
175
185
  task.thinking = event.thinking;
@@ -11,6 +11,7 @@ export interface DashboardItem {
11
11
  status: string;
12
12
  elapsed: string;
13
13
  details: string[];
14
+ observation?: string;
14
15
  taskKey?: string;
15
16
  timelinePath?: string;
16
17
  approval?: boolean;
@@ -49,7 +50,10 @@ function wrapped(lines: string[], width: number): string[] {
49
50
  }
50
51
  function elapsed(ms: number): string {
51
52
  const seconds = Math.max(0, Math.floor(ms / 1000));
52
- return `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
53
+ const minutes = Math.floor(seconds / 60);
54
+ return seconds >= 3600
55
+ ? `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, "0")}:${String(seconds % 60).padStart(2, "0")}`
56
+ : `${minutes}:${String(seconds % 60).padStart(2, "0")}`;
53
57
  }
54
58
  const friendlyStatus = (status: string) =>
55
59
  ({
@@ -87,7 +91,10 @@ export function ledgerDashboardItems(projection: DashboardProjection): Dashboard
87
91
  `Execution: ${node.executionId}`,
88
92
  `State: ${friendlyStatus(node.state)} (observation, not acceptance)`,
89
93
  `Grant: ${node.effectiveGrant.join(", ") || "none"}`,
90
- ...(node.workspace ? [`Workspace: ${node.workspace.id} (${node.workspace.access})`] : []),
94
+ ...(node.workspace
95
+ ? [`Workspace: ${node.workspace.id} (${node.workspace.access})`, `Root: ${node.workspace.root}`]
96
+ : ["Workspace binding: none recorded"]),
97
+ `Last lifecycle event: ${node.updatedAt}`,
91
98
  ...(node.runtime?.herdrPaneId ? [`Pane: ${node.runtime.herdrPaneId}`] : []),
92
99
  ...(node.correlation?.phase ? [`Phase: ${node.correlation.phase}`] : []),
93
100
  ...(node.executor ? [`Executor: ${node.executor}`] : []),
@@ -105,11 +112,21 @@ export function activityDashboardItems(
105
112
  label: `${task.agent || "User turn"} [${aliases.selector(task)}]`,
106
113
  status: task.status,
107
114
  elapsed: elapsed(Date.parse(task.endedAt ?? now.toISOString()) - Date.parse(task.startedAt)),
115
+ observation: task.lastEvent
116
+ ? `${task.lastEvent.tool ? `${task.lastEvent.tool} ` : ""}${task.lastEvent.kind.replaceAll("_", " ")} · ${elapsed(Date.parse(now.toISOString()) - Date.parse(task.lastEvent.at))} ago`
117
+ : undefined,
108
118
  agent: Boolean(task.agent || task.agents.length),
109
119
  skills: task.skills.length > 0,
110
120
  details: [
111
121
  `Task: ${aliases.selector(task)}`,
112
122
  `State: ${friendlyStatus(task.status)} (observation, not acceptance)`,
123
+ ...(task.cwd ? [`Working directory: ${task.cwd}`] : ["Working directory: not recorded"]),
124
+ ...(task.lastEvent
125
+ ? [
126
+ `Last observed: ${task.lastEvent.kind}${task.lastEvent.tool ? ` (${task.lastEvent.tool})` : ""} at ${task.lastEvent.at}`,
127
+ ]
128
+ : []),
129
+ "Silence is not proof of a stalled process. Finished is not review approval.",
113
130
  ...(task.parentTaskId ? [`Parent: ${task.parentTaskId}`] : []),
114
131
  ...(task.model ? [`Model: ${task.model}`] : []),
115
132
  ...(task.thinking ? [`Thinking: ${task.thinking}`] : []),
@@ -281,6 +298,8 @@ export function renderDashboardScreen(options: DashboardScreenOptions): string {
281
298
  }
282
299
  const tail = `${friendlyStatus(item.status)} ${item.elapsed}`.trim(),
283
300
  labelWidth = Math.max(1, width - tail.length - 4);
301
+ if (item.key === screen.selectedKey && item.observation)
302
+ rows.push({ text: ` Observed: ${clean(item.observation)}` });
284
303
  rows.push({
285
304
  key: item.key,
286
305
  text: `${item.key === screen.selectedKey ? ">" : " "} ${truncate(clean(item.label), labelWidth)} ${tail}`,