pi-harness-runtime 1.1.507 → 1.1.509

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 (86) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/harness/auto-resume-marker.ts +219 -0
  3. package/harness/scope-expansion-runtime.ts +464 -0
  4. package/harness/scope-expansion.ts +212 -23
  5. package/index.ts +502 -25
  6. package/package.json +1 -1
  7. package/packages/agent-policy/package.json +1 -1
  8. package/packages/auth/package.json +1 -1
  9. package/packages/autonomous-runtime/package.json +1 -1
  10. package/packages/checkpoint/package.json +1 -1
  11. package/packages/clipboard/package.json +1 -1
  12. package/packages/codex-watcher/package.json +1 -1
  13. package/packages/config-capture/package.json +1 -1
  14. package/packages/contracts/package.json +1 -1
  15. package/packages/cookie-sanitizer/package.json +1 -1
  16. package/packages/evaluation-engine/package.json +1 -1
  17. package/packages/event-bus/package.json +1 -1
  18. package/packages/event-store/package.json +1 -1
  19. package/packages/experience-replay/package.json +1 -1
  20. package/packages/file-copy-helper/package.json +1 -1
  21. package/packages/intent-analyzer/package.json +1 -1
  22. package/packages/jev-judge/package.json +1 -1
  23. package/packages/knowledge-retrieval/package.json +1 -1
  24. package/packages/learning-engine/package.json +1 -1
  25. package/packages/logging/package.json +1 -1
  26. package/packages/memory-engine/package.json +1 -1
  27. package/packages/notification/dist/adapters/detail-format.d.ts +1 -1
  28. package/packages/notification/dist/adapters/detail-format.d.ts.map +1 -1
  29. package/packages/notification/dist/adapters/detail-format.js +12 -0
  30. package/packages/notification/dist/adapters/detail-format.js.map +1 -1
  31. package/packages/notification/dist/adapters/email-adapter.d.ts.map +1 -1
  32. package/packages/notification/dist/adapters/email-adapter.js +2 -0
  33. package/packages/notification/dist/adapters/email-adapter.js.map +1 -1
  34. package/packages/notification/dist/adapters/line-adapter.d.ts.map +1 -1
  35. package/packages/notification/dist/adapters/line-adapter.js +2 -0
  36. package/packages/notification/dist/adapters/line-adapter.js.map +1 -1
  37. package/packages/notification/dist/adapters/ntfy-adapter.d.ts.map +1 -1
  38. package/packages/notification/dist/adapters/ntfy-adapter.js +2 -0
  39. package/packages/notification/dist/adapters/ntfy-adapter.js.map +1 -1
  40. package/packages/notification/dist/adapters/telegram-adapter.d.ts +0 -1
  41. package/packages/notification/dist/adapters/telegram-adapter.d.ts.map +1 -1
  42. package/packages/notification/dist/adapters/telegram-adapter.js +2 -3
  43. package/packages/notification/dist/adapters/telegram-adapter.js.map +1 -1
  44. package/packages/notification/dist/notification-center.d.ts +8 -4
  45. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  46. package/packages/notification/dist/notification-center.js +32 -9
  47. package/packages/notification/dist/notification-center.js.map +1 -1
  48. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  49. package/packages/notification/dist/notification-policy.js +6 -0
  50. package/packages/notification/dist/notification-policy.js.map +1 -1
  51. package/packages/notification/dist/pending-question.d.ts +20 -1
  52. package/packages/notification/dist/pending-question.d.ts.map +1 -1
  53. package/packages/notification/dist/pending-question.js +9 -3
  54. package/packages/notification/dist/pending-question.js.map +1 -1
  55. package/packages/notification/dist/types.d.ts +10 -1
  56. package/packages/notification/dist/types.d.ts.map +1 -1
  57. package/packages/notification/package.json +1 -1
  58. package/packages/notification/src/adapters/detail-format.ts +17 -1
  59. package/packages/notification/src/adapters/email-adapter.ts +2 -0
  60. package/packages/notification/src/adapters/line-adapter.ts +2 -0
  61. package/packages/notification/src/adapters/ntfy-adapter.ts +2 -0
  62. package/packages/notification/src/adapters/telegram-adapter.ts +2 -4
  63. package/packages/notification/src/notification-center.ts +32 -9
  64. package/packages/notification/src/notification-policy.ts +6 -0
  65. package/packages/notification/src/pending-question.ts +28 -2
  66. package/packages/notification/src/types.ts +11 -0
  67. package/packages/paperclip-integration/package.json +1 -1
  68. package/packages/performance-optimizer/package.json +1 -1
  69. package/packages/privilege-broker/package.json +1 -1
  70. package/packages/prompt-compiler/package.json +1 -1
  71. package/packages/providers/package.json +1 -1
  72. package/packages/qdrant-skills/package.json +1 -1
  73. package/packages/quota-manager/package.json +1 -1
  74. package/packages/relay/package.json +1 -1
  75. package/packages/skill-mcp-client/package.json +1 -1
  76. package/packages/skills/package.json +1 -1
  77. package/packages/todo-bd-sync/package.json +1 -1
  78. package/packages/token-estimation/package.json +1 -1
  79. package/packages/tooling-preference/package.json +1 -1
  80. package/packages/trajectory/package.json +1 -1
  81. package/packages/tui/package.json +1 -1
  82. package/packages/two-phase-review/package.json +1 -1
  83. package/packages/types/package.json +1 -1
  84. package/packages/webmcp-tester/package.json +1 -1
  85. package/packages/wiki/package.json +1 -1
  86. package/packages/write-review/package.json +1 -1
@@ -0,0 +1,464 @@
1
+ /**
2
+ * The runtime of the scope expansion.
3
+ *
4
+ * The controller (`harness/scope-expansion.ts`) owns the state of a
5
+ * proposal. This module owns the moments around it:
6
+ *
7
+ * - the proposal is created and delivered, and the window of the decision
8
+ * starts with the delivery,
9
+ * - the pending question is registered, so the answer of the human has a
10
+ * canonical identity,
11
+ * - the deadline fires once and lets Jev decide the exact proposal,
12
+ * - the decision of the human is read again after the delivery and before
13
+ * the dispatch: a rejection that arrived late still prevents the work,
14
+ * - the authorized group finishes and the session stops again.
15
+ *
16
+ * Everything the runtime needs from the outside is injected, so the
17
+ * behaviour is deterministic in a test.
18
+ */
19
+
20
+ import {
21
+ MAX_SCOPE_CANDIDATES,
22
+ SCOPE_EXPANSION_WINDOW_MS,
23
+ ScopeExpansionController,
24
+ createScopeProposal,
25
+ scopeProposalMessage,
26
+ type ScopeCandidate,
27
+ type ScopeDecision,
28
+ type ScopeProposal,
29
+ } from "./scope-expansion.ts";
30
+
31
+ /** What a caller wants to propose. */
32
+ export interface ScopeProposalRequest {
33
+ /** The identity of the request whose work is finished. */
34
+ requestId: string;
35
+ /** The workspace the work happens in. */
36
+ workspace: string;
37
+ /** The generation of the completion. */
38
+ generation: number;
39
+ /** The candidates of the backlog. */
40
+ candidates: ScopeCandidate[];
41
+ /** What would be done. */
42
+ scope: string;
43
+ /** How the work would be validated. */
44
+ validation: string;
45
+ /** The material risks or costs. */
46
+ risks?: string[];
47
+ /** The choices the human has. */
48
+ choices?: string[];
49
+ /** The ids the proposal names. Defaults to every candidate. */
50
+ proposedIds?: string[];
51
+ }
52
+
53
+ /** The outcome of a human answer. */
54
+ export type HumanScopeOutcome = "approve" | "reject";
55
+
56
+ /** The handle of a timer of the runtime. */
57
+ export type ScopeTimerHandle = ReturnType<typeof setTimeout> | number;
58
+
59
+ export interface ScopeExpansionRuntimeDeps {
60
+ /** The clock of the runtime. */
61
+ now(): number;
62
+ /**
63
+ * Deliver a message to the channels of the human.
64
+ *
65
+ * The result says whether at least one route accepted the message.
66
+ */
67
+ deliver(
68
+ text: string,
69
+ meta: { id: string; kind: "proposal" | "decision"; questionId?: string },
70
+ ): Promise<{ delivered: boolean; failures: string[] }>;
71
+ /** Jev decides the proposal when the human did not answer. */
72
+ judge(proposal: ScopeProposal): Promise<ScopeDecision>;
73
+ /** Start the authorized work. */
74
+ dispatch(proposal: ScopeProposal, ids: string[]): void;
75
+ /**
76
+ * Register the pending question of a proposal.
77
+ *
78
+ * The returned id is the canonical question id: it correlates the
79
+ * buttons of the notification with the answer of the human.
80
+ */
81
+ registerQuestion(proposal: ScopeProposal): string | undefined;
82
+ /**
83
+ * Cancel a question that nobody was told about.
84
+ *
85
+ * A question of a proposal that was not delivered must not stay open: an
86
+ * open question blocks the work of the session.
87
+ */
88
+ cancelQuestion?(questionId: string): void;
89
+ /**
90
+ * The latest human decision of a proposal.
91
+ *
92
+ * It is read after the delivery of the decision and before the
93
+ * dispatch, so a rejection that arrived late still prevents the work.
94
+ */
95
+ latestHumanDecision?(proposal: ScopeProposal): HumanScopeOutcome | undefined;
96
+ /**
97
+ * Are the authorized issues of the group finished?
98
+ *
99
+ * The check is mechanical: the work of the group is done when the
100
+ * issues of the group are closed.
101
+ */
102
+ groupFinished?(proposal: ScopeProposal, ids: string[]): boolean | Promise<boolean>;
103
+ /** The timer of the deadline. */
104
+ setTimeout?(callback: () => void | Promise<void>, ms: number): ScopeTimerHandle;
105
+ /** The cancel of the timer. */
106
+ clearTimeout?(handle: ScopeTimerHandle): void;
107
+ /** The log of the runtime. */
108
+ log?(message: string): void;
109
+ }
110
+
111
+ export class ScopeExpansionRuntime {
112
+ private readonly deps: ScopeExpansionRuntimeDeps;
113
+ private readonly controller: ScopeExpansionController;
114
+ private timers = new Map<string, ScopeTimerHandle>();
115
+ /** The proposal of every generation, for the group check. */
116
+ private dispatched = new Map<string, { proposal: ScopeProposal; ids: string[] }>();
117
+ /**
118
+ * The runtime was disposed.
119
+ *
120
+ * A disposed runtime belongs to a session that ended: it decides
121
+ * nothing, it dispatches nothing and it keeps no timer. Without this
122
+ * flag a timer of the default clock - the one the wiring uses - would
123
+ * fire after the session and start work in a session that is gone.
124
+ */
125
+ private disposed = false;
126
+ /** The proposal of every registered question. */
127
+ private questions = new Map<string, string>();
128
+ /** The question of every proposal. */
129
+ private questionIds = new Map<string, string>();
130
+ /** The number of the proposals of this runtime. */
131
+ private proposalCounter = 0;
132
+
133
+ constructor(deps: ScopeExpansionRuntimeDeps) {
134
+ this.deps = deps;
135
+ this.controller = new ScopeExpansionController({
136
+ now: () => deps.now(),
137
+ deliver: (text, meta) =>
138
+ deps.deliver(text, {
139
+ ...meta,
140
+ questionId: meta.questionId ?? this.questionIds.get(meta.id),
141
+ }),
142
+ judge: (proposal) => deps.judge(proposal),
143
+ dispatch: (proposal, ids) => {
144
+ // A disposed runtime belongs to a session that ended: it
145
+ // dispatches nothing.
146
+ if (this.disposed) {
147
+ this.deps.log?.(
148
+ `The scope proposal ${proposal.id} is not dispatched: the runtime is disposed.`,
149
+ );
150
+ return;
151
+ }
152
+ // The ids that were dispatched are the ids of the group: the
153
+ // check of the group asks about the work that started, not
154
+ // about the ids a decision named.
155
+ this.dispatched.set(proposal.id, {
156
+ proposal,
157
+ ids: [...ids],
158
+ });
159
+ deps.dispatch(proposal, ids);
160
+ },
161
+ log: (message) => deps.log?.(message),
162
+ latestHumanDecision: (proposal) =>
163
+ deps.latestHumanDecision?.(proposal),
164
+ });
165
+ }
166
+
167
+ /** The proposals that wait for an answer. */
168
+ get open(): ScopeProposal[] {
169
+ return this.controller.open;
170
+ }
171
+
172
+ /** The proposal with this identity. */
173
+ get(id: string): ScopeProposal | undefined {
174
+ return this.controller.get(id);
175
+ }
176
+
177
+ /**
178
+ * Propose a new scope.
179
+ *
180
+ * The proposal is delivered before the window of the decision starts: a
181
+ * proposal that reaches no route must not start a countdown that nobody
182
+ * can stop.
183
+ */
184
+ async propose(request: ScopeProposalRequest): Promise<ScopeProposal | null> {
185
+ if (this.disposed) return null;
186
+ // The candidates are bounded here as well: a proposal that names an
187
+ // id beyond the bound would find no known candidate and would
188
+ // throw where the caller expects nothing to happen.
189
+ const candidates = request.candidates.slice(0, MAX_SCOPE_CANDIDATES);
190
+ if (candidates.length === 0) {
191
+ this.deps.log?.("No scope proposal: the backlog has no candidate.");
192
+ return null;
193
+ }
194
+ const proposedIds =
195
+ request.proposedIds?.filter((id) => candidates.some((c) => c.id === id)) ??
196
+ candidates.map((candidate) => candidate.id);
197
+ if (proposedIds.length === 0) {
198
+ this.deps.log?.("No scope proposal: no candidate is known.");
199
+ return null;
200
+ }
201
+ // The identity of a proposal is unique: two proposals of the same
202
+ // generation with the same first id would answer each other, and the
203
+ // second answer of the human would be dropped.
204
+ const base = `scope-${request.generation}-${proposedIds[0]}`;
205
+ let id = base;
206
+ if (this.controller.get(base)) {
207
+ this.proposalCounter += 1;
208
+ id = `scope-${request.generation}-${this.proposalCounter}-${proposedIds[0]}`;
209
+ }
210
+ const proposal = createScopeProposal({
211
+ id,
212
+ sessionId: "",
213
+ requestId: request.requestId,
214
+ generation: request.generation,
215
+ workspace: request.workspace,
216
+ candidates,
217
+ proposedIds,
218
+ scope: request.scope,
219
+ validation: request.validation,
220
+ risks: request.risks ?? [],
221
+ now: this.deps.now(),
222
+ });
223
+ if (!this.controller.register(proposal)) {
224
+ return null;
225
+ }
226
+ // The question is registered before the delivery: the buttons of the
227
+ // notification carry the canonical question id, and the id exists
228
+ // only when the question does.
229
+ const questionId = this.deps.registerQuestion(proposal);
230
+ if (questionId) {
231
+ this.questions.set(questionId, proposal.id);
232
+ this.questionIds.set(proposal.id, questionId);
233
+ }
234
+ let delivered = false;
235
+ try {
236
+ delivered = await this.controller.deliverProposal(proposal);
237
+ } catch (error) {
238
+ // A delivery that throws is a delivery that happened nowhere: the
239
+ // proposal must not stay registered with an open question.
240
+ this.deps.log?.(
241
+ `The delivery of the scope proposal ${proposal.id} failed: ${String(error)}`,
242
+ );
243
+ delivered = false;
244
+ }
245
+ if (!delivered) {
246
+ // A proposal that reached nobody leaves no open question behind:
247
+ // an open question blocks the work of the session.
248
+ if (questionId) {
249
+ this.deps.cancelQuestion?.(questionId);
250
+ this.questions.delete(questionId);
251
+ this.questionIds.delete(proposal.id);
252
+ }
253
+ return null;
254
+ }
255
+ this.scheduleEvaluation(proposal);
256
+ return proposal;
257
+ }
258
+
259
+ /**
260
+ * The answer of the human.
261
+ *
262
+ * The first answer wins, and the answer beats an evaluation that is
263
+ * still running.
264
+ */
265
+ async answer(
266
+ proposalId: string,
267
+ outcome: HumanScopeOutcome,
268
+ reasoning: string,
269
+ ): Promise<{ started: boolean; reason?: string }> {
270
+ if (this.disposed) {
271
+ return { started: false, reason: "the runtime is disposed" };
272
+ }
273
+ const decision = this.controller.answer(proposalId, outcome, reasoning);
274
+ if (!decision) {
275
+ return { started: false, reason: "the proposal has no open answer" };
276
+ }
277
+ const result = await this.controller.applyDecision(proposalId);
278
+ // The question of a decided proposal is closed: an open question
279
+ // blocks the work of the session.
280
+ this.closeQuestion(proposalId);
281
+ return result;
282
+ }
283
+
284
+ /**
285
+ * The answer of the human, by the identity of the question.
286
+ *
287
+ * The channels answer a question, not a proposal: the canonical
288
+ * question id is what the callback carries.
289
+ */
290
+ async answerByQuestion(
291
+ questionId: string,
292
+ outcome: HumanScopeOutcome,
293
+ reasoning: string,
294
+ ): Promise<{ started: boolean; reason?: string }> {
295
+ if (this.disposed) {
296
+ return { started: false, reason: "the runtime is disposed" };
297
+ }
298
+ const proposalId = this.questions.get(questionId);
299
+ if (!proposalId) {
300
+ return { started: false, reason: "the question belongs to no proposal" };
301
+ }
302
+ return this.answer(proposalId, outcome, reasoning);
303
+ }
304
+
305
+ /** The proposal of a canonical question id. */
306
+ proposalForQuestion(questionId: string): ScopeProposal | undefined {
307
+ const proposalId = this.questions.get(questionId);
308
+ if (!proposalId) return undefined;
309
+ return this.controller.get(proposalId);
310
+ }
311
+
312
+ /** The canonical question id of a proposal. */
313
+ questionIdFor(proposalId: string): string | undefined {
314
+ return this.questionIds.get(proposalId);
315
+ }
316
+
317
+ /**
318
+ * The evaluation of a proposal whose deadline has passed.
319
+ *
320
+ * The evaluation happens once, and the decision is delivered before the
321
+ * work starts.
322
+ */
323
+ async evaluateDue(proposalId: string): Promise<ScopeDecision | null> {
324
+ if (this.disposed) return null;
325
+ const decision = await this.controller.evaluateDue(proposalId);
326
+ if (!decision) return null;
327
+ // The controller turns a failed evaluation into a wait: it
328
+ // authorizes nothing, and the decision is still delivered, so the
329
+ // human learns that the window ended without an answer.
330
+ await this.controller.applyDecision(proposalId);
331
+ // The decision that was applied is the decision that counts: the
332
+ // controller may have replaced the decision of the evaluation.
333
+ // The question of a decided proposal is closed: an open question
334
+ // blocks the work of the session.
335
+ this.closeQuestion(proposalId);
336
+ return this.controller.get(proposalId)?.decision ?? decision;
337
+ }
338
+
339
+ /**
340
+ * The work of the authorized group finished.
341
+ *
342
+ * The session stops again: the approval of that group does not authorize
343
+ * the next group of the backlog.
344
+ */
345
+ async checkGroupFinished(): Promise<void> {
346
+ for (const entry of this.dispatched.values()) {
347
+ const { proposal, ids } = entry;
348
+ if (ids.length === 0) continue;
349
+ if (!(await this.deps.groupFinished?.(proposal, ids))) continue;
350
+ this.controller.finishGroup(proposal.id);
351
+ this.clearTimer(proposal.id);
352
+ this.closeQuestion(proposal.id);
353
+ this.dispatched.delete(proposal.id);
354
+ }
355
+ }
356
+
357
+ /**
358
+ * Stop the runtime: no timer survives the session.
359
+ *
360
+ * The timer of the default clock is cancelled with the same clock that
361
+ * armed it: a runtime that keeps its timer would decide the backlog of
362
+ * a session that ended, and the decision would start work in a session
363
+ * that does not exist any more.
364
+ */
365
+ dispose(): void {
366
+ this.disposed = true;
367
+ for (const handle of this.timers.values()) {
368
+ this.cancelTimer(handle);
369
+ }
370
+ this.timers.clear();
371
+ // A question of a proposal that nobody answered must not stay open:
372
+ // the controller of the questions lives in the process, and an open
373
+ // question of a dead session blocks the next one.
374
+ for (const questionId of this.questions.keys()) {
375
+ this.deps.cancelQuestion?.(questionId);
376
+ }
377
+ this.questions.clear();
378
+ this.questionIds.clear();
379
+ this.dispatched.clear();
380
+ }
381
+
382
+ private scheduleEvaluation(proposal: ScopeProposal): void {
383
+ const delay = Math.max(0, proposal.deadlineAt - this.deps.now());
384
+ const handle = this.armTimer(() => {
385
+ this.timers.delete(proposal.id);
386
+ return (async () => {
387
+ if (this.disposed) return;
388
+ try {
389
+ const decision = await this.evaluateDue(proposal.id);
390
+ // A timer that fired before the deadline leaves the window
391
+ // open: the timer is armed again for the rest of it, so
392
+ // the proposal always ends in a decision.
393
+ if (decision === null && !this.disposed) {
394
+ const current = this.controller.get(proposal.id);
395
+ if (current?.state === "proposed") {
396
+ this.scheduleEvaluation(proposal);
397
+ }
398
+ }
399
+ } catch (error) {
400
+ this.deps.log?.(
401
+ `The evaluation of the scope proposal ${proposal.id} failed: ${String(error)}`,
402
+ );
403
+ }
404
+ })();
405
+ }, delay);
406
+ this.timers.set(proposal.id, handle);
407
+ }
408
+
409
+ /** Arm a timer on the clock of the runtime, or on the default clock. */
410
+ private armTimer(
411
+ callback: () => void | Promise<void>,
412
+ ms: number,
413
+ ): ScopeTimerHandle {
414
+ const setTimer =
415
+ this.deps.setTimeout ??
416
+ ((cb: () => void, delay: number) => setTimeout(cb, delay));
417
+ return setTimer(callback, ms);
418
+ }
419
+
420
+ /** Cancel a timer on the clock that armed it. */
421
+ private cancelTimer(handle: ScopeTimerHandle): void {
422
+ const clearTimer =
423
+ this.deps.clearTimeout ??
424
+ ((h: ScopeTimerHandle) =>
425
+ clearTimeout(h as ReturnType<typeof setTimeout>));
426
+ clearTimer(handle);
427
+ }
428
+
429
+ private clearTimer(id: string): void {
430
+ const handle = this.timers.get(id);
431
+ if (handle === undefined) return;
432
+ this.cancelTimer(handle);
433
+ this.timers.delete(id);
434
+ }
435
+
436
+ /**
437
+ * Close the question of a proposal.
438
+ *
439
+ * A proposal that reached its end does not keep a question open: an
440
+ * open question blocks the work of the session.
441
+ */
442
+ private closeQuestion(proposalId: string): void {
443
+ const questionId = this.questionIds.get(proposalId);
444
+ if (!questionId) return;
445
+ this.deps.cancelQuestion?.(questionId);
446
+ this.questions.delete(questionId);
447
+ this.questionIds.delete(proposalId);
448
+ }
449
+
450
+ /**
451
+ * The message of a proposal, for the caller that delivers it itself.
452
+ */
453
+ message(proposal: ScopeProposal): string {
454
+ return scopeProposalMessage(proposal);
455
+ }
456
+ }
457
+
458
+ /**
459
+ * The window of a decision, in milliseconds.
460
+ *
461
+ * The runtime uses the same constant as the controller: one source of the
462
+ * five minutes.
463
+ */
464
+ export const SCOPE_WINDOW_MS = SCOPE_EXPANSION_WINDOW_MS;