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
@@ -13,6 +13,7 @@ import {
13
13
  unlinkSync,
14
14
  constants,
15
15
  readFileSync,
16
+ readlinkSync,
16
17
  } from "node:fs";
17
18
  import { join } from "node:path";
18
19
  import { readBoundedTextSync } from "../kernel/bounded-read-sync.ts";
@@ -56,6 +57,42 @@ function ownerAlive(id: string): boolean {
56
57
  throw error;
57
58
  }
58
59
  }
60
+ /** A local owner receipt for reservations made before native begin() is permitted to run. */
61
+ export interface PrelaunchOwner {
62
+ ownerId: string;
63
+ ownerScope: string;
64
+ pidNamespace: string;
65
+ }
66
+ export function pinPrelaunchOwner(runtime: RuntimeSettlement, sessionId: string, cwd: string): PrelaunchOwner {
67
+ if (runtime.ownerId !== ownerId() || runtime.sessionId !== sessionId || runtime.cwd !== cwd)
68
+ throw Error("Native execution owner changed before task admission");
69
+ return { ownerId: runtime.ownerId, ownerScope: runtime.ownerScope, pidNamespace: readlinkSync("/proc/self/ns/pid") };
70
+ }
71
+ function prelaunchOwnerGone(pin: PrelaunchOwner, journal: Journal): boolean {
72
+ const match = /^([0-9a-f-]{36}):([1-9][0-9]*):([0-9]+)$/.exec(pin.ownerId);
73
+ if (
74
+ !match ||
75
+ pin.ownerScope !== journal.ownerScope ||
76
+ pin.pidNamespace !== readlinkSync("/proc/self/ns/pid") ||
77
+ match[1] !== readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim()
78
+ )
79
+ return false;
80
+ // Identical /proc view, boot and birth ticks distinguish PID reuse. An inaccessible process or changed
81
+ // namespace is not death. If the proc entry vanished, ask the kernel for positive ESRCH evidence too.
82
+ try {
83
+ const text = readFileSync("/proc/" + match[2] + "/stat", "utf8");
84
+ const ticks = text.slice(text.lastIndexOf(")") + 2).split(" ")[19];
85
+ return /^\d+$/.test(ticks ?? "") && ticks !== match[3];
86
+ } catch (error) {
87
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT") return false;
88
+ try {
89
+ process.kill(Number(match[2]), 0);
90
+ return false;
91
+ } catch (probe) {
92
+ return (probe as NodeJS.ErrnoException).code === "ESRCH";
93
+ }
94
+ }
95
+ }
59
96
  function validate(value: unknown, sessionId: string, cwd: string): Journal {
60
97
  const j = value as Journal;
61
98
  if (
@@ -276,6 +313,7 @@ export async function readRuntimeExecutionSettlement(
276
313
  sessionId: string,
277
314
  cwd: string,
278
315
  executionId: string,
316
+ beforeLaunch?: PrelaunchOwner,
279
317
  ) {
280
318
  const root = join(realpathSync(directory), "pi-daddy", "runtime-settlement");
281
319
  if (realpathSync(root) !== root) throw Error("runtime settlement root changed");
@@ -285,10 +323,14 @@ export async function readRuntimeExecutionSettlement(
285
323
  const path = join(root, settlementHash([sessionId, cwd]) + ".json");
286
324
  const text = readBoundedTextSync(path, { maxBytes: MAX_RECORD, confinedRoot: root }).text;
287
325
  const journal = validate(JSON.parse(text), sessionId, cwd);
326
+ if (beforeLaunch && beforeLaunch.ownerScope !== journal.ownerScope) return "unknown" as const;
288
327
  const e = journal.executions.find((item) => item.id === executionId);
289
- if (!e || e.problem) return "unknown" as const;
328
+ if (e?.problem) return "unknown" as const;
290
329
  let result: "settled" | "not-started" | "unknown" = "unknown";
291
- if (e.state === "not-started" && !e.identity) result = "not-started";
330
+ if (!e) {
331
+ // Only a qualified reservation was fenced to this intact append-preserving runtime journal before launch.
332
+ if (beforeLaunch && prelaunchOwnerGone(beforeLaunch, journal)) result = "not-started";
333
+ } else if (e.state === "not-started" && !e.identity) result = "not-started";
292
334
  else if (e.identity) {
293
335
  const receipt = await readCapturedWorkerReceipt(e.identity);
294
336
  if (receipt && (!e.receiptSha256 || e.receiptSha256 === settlementHash(receipt))) result = "settled";
@@ -0,0 +1,427 @@
1
+ /** Owner journal for parent Pi dispatch. A history replay never launches or cancels a child. */
2
+ import { join } from "node:path";
3
+ import { realpathSync } from "node:fs";
4
+ import { readBoundedTextSync } from "../kernel/bounded-read-sync.ts";
5
+ import { artifactHash, privateArtifactDirectory, publishArtifact } from "./operation-artifact-io.ts";
6
+
7
+ export const dispatchOwners = ["pi-daddy", "scout", "harness", "jev"] as const;
8
+ export type DispatchOwner = (typeof dispatchOwners)[number];
9
+ export interface DispatchCounts {
10
+ admitted: number;
11
+ outstanding: number;
12
+ limit: number | null;
13
+ }
14
+ const isOwner = (value: unknown): value is DispatchOwner => dispatchOwners.includes(value as DispatchOwner);
15
+ const attemptKey = (owner: DispatchOwner, executionId: string) => JSON.stringify([owner, executionId]);
16
+ export type DispatchCommand = "pause" | "cancel" | "resume" | "budget";
17
+ export interface DispatchView {
18
+ projectId: string;
19
+ taskId: string;
20
+ selectionRevision: number;
21
+ /** Only the selected root may change controls shared by its declared child tasks. */
22
+ inherited?: true;
23
+ observedAt?: string;
24
+ revision: number;
25
+ state: "open" | "pausing" | "paused" | "cancelling" | "cancelled";
26
+ counts: Record<DispatchOwner, DispatchCounts>;
27
+ admitted: number;
28
+ outstanding: number;
29
+ limit: number | null;
30
+ }
31
+ export interface DispatchEdit {
32
+ action: DispatchCommand;
33
+ limit?: number | null;
34
+ owner?: DispatchOwner | "task";
35
+ expected: Pick<DispatchView, "projectId" | "taskId" | "selectionRevision" | "revision">;
36
+ }
37
+
38
+ export function isDispatchEdit(value: unknown): value is DispatchEdit {
39
+ if (!value || typeof value !== "object") return false;
40
+ const edit = value as Partial<DispatchEdit>;
41
+ const expected = edit.expected;
42
+ return (
43
+ !!expected &&
44
+ typeof expected === "object" &&
45
+ Object.keys(expected).every((k) => ["projectId", "taskId", "selectionRevision", "revision"].includes(k)) &&
46
+ validText(expected.projectId, 512) &&
47
+ validText(expected.taskId, 160) &&
48
+ Number.isSafeInteger(expected.selectionRevision) &&
49
+ expected.selectionRevision >= 0 &&
50
+ Number.isSafeInteger(expected.revision) &&
51
+ expected.revision >= 0 &&
52
+ Object.keys(edit).every((k) =>
53
+ ["action", "expected", ...(edit.action === "budget" ? ["limit", "owner"] : [])].includes(k),
54
+ ) &&
55
+ (edit.action === "budget"
56
+ ? validTaskLimit(edit.limit) && (edit.owner === undefined || edit.owner === "task" || isOwner(edit.owner))
57
+ : ["pause", "cancel", "resume"].includes(edit.action ?? ""))
58
+ );
59
+ }
60
+
61
+ type Attempt = {
62
+ beforeLaunch?: import("./runtime-settlement.ts").PrelaunchOwner;
63
+ taskId?: string;
64
+ owner: DispatchOwner;
65
+ executionId: string;
66
+ sessionId: string;
67
+ cwd: string;
68
+ };
69
+ type Control =
70
+ | { action: "admit"; attempt: Attempt }
71
+ | { action: "settle"; taskId?: string; owner: DispatchOwner; executionId: string; cleanup: "settled" | "not-started" }
72
+ | { action: "pause" | "cancel" | "resume" }
73
+ | { action: "budget"; owner: DispatchOwner | "task"; limit: number | null };
74
+ const errno = (e: unknown, code: string) => (e as NodeJS.ErrnoException)?.code === code;
75
+ const validText = (v: unknown, max: number): v is string =>
76
+ typeof v === "string" && v.length > 0 && v.length <= max && !/[\x00-\x1f\x7f]/.test(v);
77
+ export const validTaskLimit = (v: unknown): v is number | null =>
78
+ v === null || (typeof v === "number" && Number.isSafeInteger(v) && v >= 0);
79
+
80
+ export class TaskDispatch {
81
+ readonly projectId: string;
82
+ readonly taskId: string;
83
+ private readonly root: string;
84
+ private readonly exclusive: boolean;
85
+ private revision = 0;
86
+ private policyRevision = 0;
87
+ private previousPolicy?: { revision: number; event: Control };
88
+ private taskLimit: number | null = null;
89
+ private mode: "open" | "pause" | "cancel" = "open";
90
+ private readonly counts = Object.fromEntries(
91
+ dispatchOwners.map((owner) => [owner, { admitted: 0, outstanding: 0, limit: null }]),
92
+ ) as Record<DispatchOwner, DispatchCounts>;
93
+ private readonly admitted = new Set<string>();
94
+ private readonly pending = new Map<string, Attempt>();
95
+
96
+ constructor(directory: string, projectId: string, taskId: string, exclusiveWriter = false) {
97
+ this.exclusive = exclusiveWriter;
98
+ if (!validText(projectId, 512) || !validText(taskId, 160)) throw Error("Invalid task identity");
99
+ this.projectId = projectId;
100
+ this.taskId = taskId;
101
+ this.root = join(
102
+ realpathSync(directory),
103
+ "pi-daddy",
104
+ exclusiveWriter ? "task-writers" : "task-dispatch",
105
+ artifactHash(JSON.stringify([projectId, taskId])),
106
+ );
107
+ }
108
+
109
+ snapshot(selectionRevision: number, selectedTaskId = this.taskId): DispatchView {
110
+ this.catchUp();
111
+ const outstanding = this.pending.size;
112
+ const state =
113
+ this.mode === "cancel"
114
+ ? outstanding
115
+ ? "cancelling"
116
+ : "cancelled"
117
+ : this.mode === "pause"
118
+ ? outstanding
119
+ ? "pausing"
120
+ : "paused"
121
+ : "open";
122
+ return {
123
+ projectId: this.projectId,
124
+ taskId: selectedTaskId,
125
+ ...(selectedTaskId !== this.taskId ? { inherited: true as const } : {}),
126
+ selectionRevision,
127
+ revision: this.policyRevision,
128
+ state,
129
+ outstanding,
130
+ admitted: this.admitted.size,
131
+ counts: structuredClone(this.counts),
132
+ limit: this.taskLimit,
133
+ };
134
+ }
135
+
136
+ change(
137
+ action: DispatchCommand,
138
+ limit: number | null,
139
+ expectedRevision: number,
140
+ owner: DispatchOwner | "task" = "task",
141
+ ) {
142
+ const event: Control = action === "budget" ? { action, owner, limit } : { action };
143
+ this.append(event, () => {
144
+ if (this.policyRevision !== expectedRevision) {
145
+ if (
146
+ this.previousPolicy?.revision === expectedRevision &&
147
+ JSON.stringify(event) === JSON.stringify(this.previousPolicy.event)
148
+ )
149
+ return false;
150
+ throw Error("Task policy changed. Refresh before applying a command.");
151
+ }
152
+ if (action === "pause" && this.mode === "cancel" && this.pending.size)
153
+ throw Error("Cancellation is still settling.");
154
+ if (action === "resume" && this.mode === "cancel" && this.pending.size)
155
+ throw Error("Cancellation is still settling. Outstanding executions must be reconciled first.");
156
+ if (
157
+ action === "budget" &&
158
+ (!validTaskLimit(limit) ||
159
+ (limit !== null && limit < (owner === "task" ? this.admitted.size : this.counts[owner].admitted)))
160
+ )
161
+ throw Error("The allowance must cover all previously admitted attempts.");
162
+ });
163
+ }
164
+
165
+ assertOpen() {
166
+ this.catchUp();
167
+ if (this.mode !== "open") throw Error("Task dispatch is stopped. Inspect task controls before resuming.");
168
+ }
169
+
170
+ assertAvailable(owner: DispatchOwner) {
171
+ this.assertOpen();
172
+ if (this.taskLimit !== null && this.admitted.size >= this.taskLimit)
173
+ throw Error("This task's shared attempt allowance is exhausted.");
174
+ const bucket = this.counts[owner];
175
+ if (bucket.limit !== null && bucket.admitted >= bucket.limit)
176
+ throw Error(owner + " task attempt allowance is exhausted.");
177
+ }
178
+
179
+ admit(attempt: Attempt) {
180
+ if (
181
+ (attempt.taskId !== undefined && !validText(attempt.taskId, 160)) ||
182
+ !validText(attempt.executionId, 256) ||
183
+ !validText(attempt.sessionId, 256) ||
184
+ !validText(attempt.cwd, 4096)
185
+ )
186
+ throw Error("Invalid task dispatch identity");
187
+ this.append({ action: "admit", attempt }, () => {
188
+ this.assertAvailable(attempt.owner);
189
+ if (this.exclusive && this.pending.size)
190
+ throw Error(
191
+ "A writer already owns this working copy. Reuse its result or select a separate registered worktree.",
192
+ );
193
+ if (this.admitted.has(attemptKey(attempt.owner, attempt.executionId)))
194
+ throw Error("Task attempt already reserved. Reconcile the existing execution.");
195
+ });
196
+ }
197
+
198
+ settle(owner: DispatchOwner, executionId: string, cleanup: "settled" | "not-started", origin = this.taskId) {
199
+ const entry: Control = { action: "settle", owner, executionId, cleanup, taskId: origin };
200
+ this.append(entry, () => {
201
+ const pending = this.pending.get(attemptKey(owner, executionId));
202
+ if (!pending) return false;
203
+ if ((pending.taskId ?? this.taskId) !== origin) throw Error("Native receipt belongs to a different task");
204
+ return true;
205
+ });
206
+ }
207
+
208
+ outstanding(): Attempt[] {
209
+ this.catchUp();
210
+ return [...this.pending.values()];
211
+ }
212
+
213
+ private recordAt(seq: number): { at: string; event: Control } | undefined {
214
+ let text: string;
215
+ try {
216
+ text = readBoundedTextSync(join(this.root, seq + ".json"), { maxBytes: 16_384, confinedRoot: this.root }).text;
217
+ } catch (error) {
218
+ if (errno(error, "ENOENT")) return;
219
+ throw error;
220
+ }
221
+ const record = JSON.parse(text);
222
+ if (
223
+ record?.version !== 1 ||
224
+ record.seq !== seq ||
225
+ record.taskId !== this.taskId ||
226
+ record.projectId !== this.projectId ||
227
+ typeof record.at !== "string" ||
228
+ !Number.isFinite(Date.parse(record.at)) ||
229
+ new Date(record.at).toISOString() !== record.at ||
230
+ !record.event
231
+ )
232
+ throw Error("Task dispatch history is unavailable or incompatible");
233
+ return { at: record.at, event: record.event as Control };
234
+ }
235
+
236
+ private readable(): boolean {
237
+ try {
238
+ privateArtifactDirectory(this.root);
239
+ return true;
240
+ } catch (error) {
241
+ if (errno(error, "ENOENT") && this.revision === 0) return false;
242
+ throw error;
243
+ }
244
+ }
245
+
246
+ private catchUp() {
247
+ if (!this.readable()) return;
248
+ for (;;) {
249
+ const event = this.recordAt(this.revision + 1)?.event;
250
+ if (!event) return;
251
+ this.apply(event);
252
+ this.revision++;
253
+ }
254
+ }
255
+
256
+ /** Return bounded, metadata-only observations of the journal. There is no dispatch path in replay. */
257
+ page(after: number, limit: number, selectedTaskId = this.taskId) {
258
+ if (
259
+ !Number.isSafeInteger(after) ||
260
+ after < 0 ||
261
+ after > Number.MAX_SAFE_INTEGER - 51 ||
262
+ !Number.isSafeInteger(limit) ||
263
+ limit < 1 ||
264
+ limit > 50
265
+ )
266
+ throw Error("Invalid task history cursor or page size");
267
+ const events: Array<{
268
+ version: 1;
269
+ owner: "pi-daddy";
270
+ operationId: string;
271
+ kind: string;
272
+ state: string;
273
+ label: string;
274
+ }> = [];
275
+ const provenance: { sequence: number; recordedAt: string }[] = [];
276
+ const present = this.readable();
277
+ if (after && (!present || !this.recordAt(after))) throw Error("Task history cursor is unavailable");
278
+ let next = after;
279
+ while (present && next - after < limit) {
280
+ const seq = next + 1,
281
+ record = this.recordAt(seq);
282
+ if (!record) break;
283
+ const event = record.event;
284
+ next = seq;
285
+ const origin =
286
+ event.action === "admit" ? event.attempt?.taskId : event.action === "settle" ? event.taskId : undefined;
287
+ if ((origin ?? this.taskId) !== selectedTaskId) continue;
288
+ let state: string, label: string, identity: string;
289
+ switch (event.action) {
290
+ case "admit":
291
+ case "settle": {
292
+ const owner = event.action === "admit" ? event.attempt?.owner : event.owner;
293
+ const id = event.action === "admit" ? event.attempt?.executionId : event.executionId;
294
+ if (
295
+ !isOwner(owner) ||
296
+ !validText(id, 256) ||
297
+ (event.action === "settle" && !["settled", "not-started"].includes(event.cleanup))
298
+ )
299
+ throw Error("Invalid task dispatch receipt");
300
+ identity = JSON.stringify([owner, id]);
301
+ state = event.action === "admit" ? "admitted" : event.cleanup;
302
+ label =
303
+ event.action === "admit"
304
+ ? owner + " attempt admitted"
305
+ : event.cleanup === "settled"
306
+ ? owner + " cleanup confirmed"
307
+ : owner + " attempt confirmed unstarted";
308
+ break;
309
+ }
310
+ case "budget":
311
+ case "pause":
312
+ case "cancel":
313
+ case "resume":
314
+ if (
315
+ event.action === "budget" &&
316
+ ((!isOwner(event.owner) && event.owner !== "task") || !validTaskLimit(event.limit))
317
+ )
318
+ throw Error("Invalid task budget");
319
+ identity = "policy-" + seq;
320
+ state = event.action;
321
+ label =
322
+ event.action === "budget"
323
+ ? event.owner + " attempt cap " + (event.limit === null ? "removed" : "set to " + event.limit)
324
+ : event.action === "pause"
325
+ ? "Pause requested"
326
+ : event.action === "cancel"
327
+ ? "Cancellation requested"
328
+ : "Dispatch resumed";
329
+ break;
330
+ default:
331
+ throw Error("Unsupported task receipt");
332
+ }
333
+ provenance.push({ sequence: seq, recordedAt: record.at });
334
+ events.push({
335
+ version: 1,
336
+ owner: "pi-daddy",
337
+ operationId: "dispatch-" + artifactHash(JSON.stringify([this.projectId, this.taskId, identity])),
338
+ kind: "dispatch",
339
+ state,
340
+ label,
341
+ });
342
+ next = seq;
343
+ }
344
+ return { after, next, more: present && Boolean(this.recordAt(next + 1)), events, provenance };
345
+ }
346
+
347
+ private apply(event: Control) {
348
+ switch (event?.action) {
349
+ case "admit": {
350
+ const a = event.attempt;
351
+ if (
352
+ !a ||
353
+ (a.taskId !== undefined && !validText(a.taskId, 160)) ||
354
+ !validText(a.executionId, 256) ||
355
+ !validText(a.sessionId, 256) ||
356
+ !validText(a.cwd, 4096) ||
357
+ !isOwner(a.owner) ||
358
+ this.admitted.has(attemptKey(a.owner, a.executionId))
359
+ )
360
+ throw Error("Invalid task dispatch reservation");
361
+ this.admitted.add(attemptKey(a.owner, a.executionId));
362
+ this.pending.set(attemptKey(a.owner, a.executionId), a);
363
+ this.counts[a.owner].admitted++;
364
+ this.counts[a.owner].outstanding++;
365
+ break;
366
+ }
367
+ case "settle":
368
+ if (
369
+ !["settled", "not-started"].includes(event.cleanup) ||
370
+ !isOwner(event.owner) ||
371
+ (this.pending.get(attemptKey(event.owner, event.executionId))?.taskId ?? this.taskId) !==
372
+ (event.taskId ?? this.taskId) ||
373
+ !this.pending.delete(attemptKey(event.owner, event.executionId))
374
+ )
375
+ throw Error("Invalid task dispatch settlement");
376
+ this.counts[event.owner].outstanding--;
377
+ break;
378
+ case "budget":
379
+ if ((event.owner !== "task" && !isOwner(event.owner)) || !validTaskLimit(event.limit))
380
+ throw Error("Invalid task dispatch allowance");
381
+ if (event.owner === "task") this.taskLimit = event.limit;
382
+ else this.counts[event.owner].limit = event.limit;
383
+ break;
384
+ case "pause":
385
+ case "cancel":
386
+ this.mode = event.action;
387
+ break;
388
+ case "resume":
389
+ this.mode = "open";
390
+ break;
391
+ default:
392
+ throw Error("Unknown task dispatch record");
393
+ }
394
+ if (["budget", "pause", "cancel", "resume"].includes(event?.action)) {
395
+ this.previousPolicy = { revision: this.policyRevision, event };
396
+ this.policyRevision = this.revision + 1;
397
+ }
398
+ }
399
+
400
+ private append(event: Control, admit: () => void | boolean) {
401
+ privateArtifactDirectory(this.root, true);
402
+ for (;;) {
403
+ this.catchUp();
404
+ if (admit() === false) return;
405
+ const seq = this.revision + 1;
406
+ const entry = {
407
+ version: 1,
408
+ seq,
409
+ projectId: this.projectId,
410
+ taskId: this.taskId,
411
+ at: new Date().toISOString(),
412
+ event,
413
+ };
414
+ const data = JSON.stringify(entry) + "\n";
415
+ if (Buffer.byteLength(data) > 16_384) throw Error("Task dispatch record exceeds its size bound");
416
+ try {
417
+ publishArtifact(this.root, seq + ".json", data, false);
418
+ } catch (error) {
419
+ if (errno(error, "EEXIST")) continue;
420
+ throw error;
421
+ }
422
+ this.apply(event);
423
+ this.revision = seq;
424
+ return;
425
+ }
426
+ }
427
+ }
@@ -15,7 +15,11 @@ export interface DashboardChoiceTarget {
15
15
  expectedOwner: { sessionId: string; cwd: string; generation: string };
16
16
  }
17
17
  export type DashboardChoiceAction = DashboardChoiceTarget &
18
- ({ action: "inspect-choice" } | { action: "answer-choice"; revision: string; answer: DashboardChoiceAnswer });
18
+ (
19
+ | { action: "inspect-choice" }
20
+ | { action: "answer-choice"; revision: string; answer: DashboardChoiceAnswer }
21
+ | { action: "reclassify-choice"; revision: string }
22
+ );
19
23
  export type DashboardChoiceOutcome = "saved" | "refused" | "unconfirmed";
20
24
  export interface DashboardChoiceRegistration {
21
25
  version: 1;
@@ -23,6 +27,8 @@ export interface DashboardChoiceRegistration {
23
27
  cwd: string;
24
28
  sourceGeneration: string;
25
29
  renew?(): Promise<void>;
30
+ /** Explicit user correction only: retain the note, stop offering this record as a separate decision. */
31
+ reclassify?(id: string, revision: string, assertCurrent: () => void): Promise<DashboardChoiceOutcome>;
26
32
  inspect(id: string, assertCurrent: () => void): Promise<DashboardChoiceDetail | undefined>;
27
33
  answer(
28
34
  id: string,
@@ -47,11 +47,34 @@ export interface DashboardInventory {
47
47
  limited: boolean;
48
48
  entries: DashboardInventoryEntry[];
49
49
  }
50
+ interface DashboardTaskObservation {
51
+ owner: string;
52
+ state: string;
53
+ label: string;
54
+ recordedAt: string;
55
+ }
56
+ export interface DashboardTaskHistory {
57
+ taskId: string;
58
+ title: string;
59
+ observations: number;
60
+ lastObservation?: DashboardTaskObservation;
61
+ /** Additional bounded observations only when taskProgress was negotiated. */
62
+ recentProgress?: DashboardTaskObservation[];
63
+ lastCheckpoint?: {
64
+ state: "captured" | "published";
65
+ capturedAt: string;
66
+ files: number;
67
+ missing: number;
68
+ excluded: number;
69
+ };
70
+ }
50
71
  export interface DashboardSourceUpdate {
51
72
  sequence: number;
52
73
  items: DashboardContribution[];
53
74
  /** Send only after the registration reply advertises capabilities.inventory === 1. */
54
75
  inventory?: DashboardInventory;
76
+ /** Bookie can withdraw this selection independently of the source lease. */
77
+ taskHistory?: DashboardTaskHistory;
55
78
  }
56
79
  export interface DashboardSourceRefresh {
57
80
  state: "idle" | "checking" | "failed";
@@ -69,7 +92,7 @@ export type DashboardSourceRegistrationReply =
69
92
  version: 1;
70
93
  ok: true;
71
94
  generation: string;
72
- capabilities?: { inventory: 1; refresh: 1 };
95
+ capabilities?: { inventory: 1; refresh: 1; taskHistory?: 1; taskProgress?: 1 };
73
96
  publish(update: DashboardSourceUpdate): boolean;
74
97
  close(): void;
75
98
  };
@@ -79,6 +102,7 @@ export interface DashboardSourceRegistration {
79
102
  cwd: string;
80
103
  producer: string;
81
104
  producerVersion: string;
105
+ capabilities?: { taskHistory?: 1; taskProgress?: 1 };
82
106
  /** Authorized metadata reads only, with cancellation; no automatic work or model calls. */
83
107
  refresh?: DashboardSourceRefreshCallback;
84
108
  reply(value: DashboardSourceRegistrationReply): void;
@@ -167,14 +191,55 @@ export function validDashboardInventory(value: unknown): value is DashboardInven
167
191
  return false;
168
192
  }
169
193
  }
194
+ export function validDashboardTaskHistory(value: unknown): value is DashboardTaskHistory {
195
+ const keys = (data: Record<string, unknown>, allowed: string[]) =>
196
+ Object.keys(data).every((k) => allowed.includes(k));
197
+ if (
198
+ !object(value) ||
199
+ !keys(value, ["taskId", "title", "observations", "lastObservation", "recentProgress", "lastCheckpoint"]) ||
200
+ !bounded(value.taskId, 160) ||
201
+ !bounded(value.title, 160) ||
202
+ !Number.isSafeInteger(value.observations) ||
203
+ Number(value.observations) < 0
204
+ )
205
+ return false;
206
+ const instant = (s: unknown) => bounded(s, 32) && Number.isFinite(Date.parse(s)) && new Date(s).toISOString() === s;
207
+ const observation = (row: unknown) =>
208
+ object(row) &&
209
+ keys(row, ["owner", "state", "label", "recordedAt"]) &&
210
+ ["bookie", "pi-daddy", "principal", "scout", "harness"].includes(String(row.owner)) &&
211
+ bounded(row.state, 64) &&
212
+ bounded(row.label, 240) &&
213
+ instant(row.recordedAt);
214
+ const { lastObservation, recentProgress, lastCheckpoint } = value;
215
+ if (lastObservation !== undefined && (!value.observations || !observation(lastObservation))) return false;
216
+ if (
217
+ recentProgress !== undefined &&
218
+ (!Array.isArray(recentProgress) ||
219
+ recentProgress.length > Math.min(4, Number(value.observations)) ||
220
+ !recentProgress.every(observation))
221
+ )
222
+ return false;
223
+ return (
224
+ lastCheckpoint === undefined ||
225
+ (object(lastCheckpoint) &&
226
+ keys(lastCheckpoint, ["state", "capturedAt", "files", "missing", "excluded"]) &&
227
+ (lastCheckpoint.state === "captured" || lastCheckpoint.state === "published") &&
228
+ instant(lastCheckpoint.capturedAt) &&
229
+ [lastCheckpoint.files, lastCheckpoint.missing, lastCheckpoint.excluded].every(
230
+ (n) => typeof n === "number" && Number.isSafeInteger(n) && n >= 0,
231
+ ))
232
+ );
233
+ }
170
234
  export function validDashboardSourceUpdate(value: unknown): value is DashboardSourceUpdate {
171
235
  if (
172
236
  !object(value) ||
173
- Object.keys(value).some((k) => !["sequence", "items", "inventory"].includes(k)) ||
237
+ Object.keys(value).some((k) => !["sequence", "items", "inventory", "taskHistory"].includes(k)) ||
174
238
  !Number.isSafeInteger(value.sequence) ||
175
239
  Number(value.sequence) < 0 ||
176
240
  !Array.isArray(value.items) ||
177
241
  value.items.length > 8 ||
242
+ (value.taskHistory !== undefined && !validDashboardTaskHistory(value.taskHistory)) ||
178
243
  (value.inventory !== undefined && !validDashboardInventory(value.inventory))
179
244
  )
180
245
  return false;
@@ -0,0 +1,8 @@
1
+ /** Socket deadlines shared by the terminal and the authenticated session owner. */
2
+ export function isDashboardChoiceRequest(action: unknown): boolean {
3
+ return action === "inspect-choice" || action === "answer-choice" || action === "reclassify-choice";
4
+ }
5
+
6
+ export function dashboardRequestTimeout(action?: unknown): number {
7
+ return isDashboardChoiceRequest(action) || action === "task-dispatch" ? 30_000 : 2_000;
8
+ }