pi-harness-runtime 1.1.470 → 1.1.472

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 (65) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/harness/pending-countdown.ts +12 -37
  3. package/index.ts +434 -277
  4. package/package.json +1 -1
  5. package/packages/agent-policy/package.json +1 -1
  6. package/packages/auth/package.json +1 -1
  7. package/packages/autonomous-runtime/package.json +1 -1
  8. package/packages/checkpoint/package.json +1 -1
  9. package/packages/clipboard/package.json +1 -1
  10. package/packages/codex-watcher/package.json +1 -1
  11. package/packages/config-capture/package.json +1 -1
  12. package/packages/contracts/package.json +1 -1
  13. package/packages/cookie-sanitizer/package.json +1 -1
  14. package/packages/evaluation-engine/package.json +1 -1
  15. package/packages/event-bus/package.json +1 -1
  16. package/packages/event-store/package.json +1 -1
  17. package/packages/experience-replay/package.json +1 -1
  18. package/packages/file-copy-helper/package.json +1 -1
  19. package/packages/intent-analyzer/package.json +1 -1
  20. package/packages/jev-judge/dist/auto-continue.d.ts +44 -2
  21. package/packages/jev-judge/dist/auto-continue.d.ts.map +1 -1
  22. package/packages/jev-judge/dist/auto-continue.js +81 -13
  23. package/packages/jev-judge/dist/auto-continue.js.map +1 -1
  24. package/packages/jev-judge/dist/index.d.ts +3 -1
  25. package/packages/jev-judge/dist/index.d.ts.map +1 -1
  26. package/packages/jev-judge/dist/index.js +5 -1
  27. package/packages/jev-judge/dist/index.js.map +1 -1
  28. package/packages/jev-judge/dist/question-risk.d.ts +24 -0
  29. package/packages/jev-judge/dist/question-risk.d.ts.map +1 -1
  30. package/packages/jev-judge/dist/question-risk.js +78 -5
  31. package/packages/jev-judge/dist/question-risk.js.map +1 -1
  32. package/packages/jev-judge/dist/wait-lifecycle.d.ts +248 -0
  33. package/packages/jev-judge/dist/wait-lifecycle.d.ts.map +1 -0
  34. package/packages/jev-judge/dist/wait-lifecycle.js +308 -0
  35. package/packages/jev-judge/dist/wait-lifecycle.js.map +1 -0
  36. package/packages/jev-judge/package.json +1 -1
  37. package/packages/jev-judge/src/auto-continue.ts +110 -13
  38. package/packages/jev-judge/src/index.ts +16 -1
  39. package/packages/jev-judge/src/question-risk.ts +96 -5
  40. package/packages/jev-judge/src/wait-lifecycle.ts +488 -0
  41. package/packages/knowledge-retrieval/package.json +1 -1
  42. package/packages/learning-engine/package.json +1 -1
  43. package/packages/logging/package.json +1 -1
  44. package/packages/memory-engine/package.json +1 -1
  45. package/packages/notification/package.json +1 -1
  46. package/packages/paperclip-integration/package.json +1 -1
  47. package/packages/performance-optimizer/package.json +1 -1
  48. package/packages/privilege-broker/package.json +1 -1
  49. package/packages/prompt-compiler/package.json +1 -1
  50. package/packages/providers/package.json +1 -1
  51. package/packages/qdrant-skills/package.json +1 -1
  52. package/packages/quota-manager/package.json +1 -1
  53. package/packages/relay/package.json +1 -1
  54. package/packages/skill-mcp-client/package.json +1 -1
  55. package/packages/skills/package.json +1 -1
  56. package/packages/todo-bd-sync/package.json +1 -1
  57. package/packages/token-estimation/package.json +1 -1
  58. package/packages/tooling-preference/package.json +1 -1
  59. package/packages/trajectory/package.json +1 -1
  60. package/packages/tui/package.json +1 -1
  61. package/packages/two-phase-review/package.json +1 -1
  62. package/packages/types/package.json +1 -1
  63. package/packages/webmcp-tester/package.json +1 -1
  64. package/packages/wiki/package.json +1 -1
  65. package/packages/write-review/package.json +1 -1
@@ -0,0 +1,308 @@
1
+ /**
2
+ * The lifecycle of a wait for a human answer.
3
+ *
4
+ * The harness asks a human a question and waits. When the wait is over the
5
+ * question is decided once - by the human, by Jev, or not at all. This
6
+ * module owns that lifecycle:
7
+ *
8
+ * waiting -> evaluating -> decided | human_required | evaluation_error
9
+ *
10
+ * It owns the request the wait belongs to, the session it was asked in, the
11
+ * moment the question was asked, the cancellation and the countdown. The
12
+ * countdown and the decision are measured from that one timestamp, so the
13
+ * time that reaches the evaluation is the same time the countdown shows.
14
+ *
15
+ * The rules that matter:
16
+ *
17
+ * - One evaluation per request. A decision to wait ends the automatic
18
+ * attempt: the work pauses and a human is needed. Another attempt would
19
+ * be a second evaluation of the same question, and it is what turned a
20
+ * five minute wait into a repeating countdown.
21
+ * - A provider failure is an evaluation error, not a decision. It never
22
+ * becomes "Jev decided to wait": the two mean different things to the
23
+ * reader of the log and to the work.
24
+ * - Every late result is discarded. An evaluation that finishes after the
25
+ * question was answered, replaced or the session changed must not change
26
+ * anything: the state belongs to the request that is still waiting.
27
+ */
28
+ /** The message of a failure, in one line. */
29
+ function messageOf(error) {
30
+ const text = error instanceof Error ? error.message : String(error);
31
+ return text.replace(/\s+/g, " ").trim().slice(0, 200);
32
+ }
33
+ /**
34
+ * The controller of a wait for a human answer.
35
+ *
36
+ * The controller owns the lifecycle of one question at a time: a new
37
+ * question replaces the old one, an answer ends the wait, and a late result
38
+ * of an older request is discarded.
39
+ */
40
+ export class WaitLifecycleController {
41
+ deps;
42
+ now;
43
+ state = "idle";
44
+ request = null;
45
+ questionAt = 0;
46
+ /**
47
+ * Bumped on every change of the request.
48
+ *
49
+ * A result of an older generation belongs to a request that is gone: it
50
+ * is discarded instead of changing the state of the new one.
51
+ */
52
+ generation = 0;
53
+ constructor(deps) {
54
+ this.deps = deps;
55
+ this.now = deps.now ?? (() => Date.now());
56
+ }
57
+ /** The state of the wait. */
58
+ get currentState() {
59
+ return this.state;
60
+ }
61
+ /** The request the wait belongs to. */
62
+ get currentRequestId() {
63
+ return this.request?.requestId ?? null;
64
+ }
65
+ /** The session the waiting question was asked in. */
66
+ get currentSessionId() {
67
+ return this.request?.sessionId ?? null;
68
+ }
69
+ /** The moment the question was asked (in milliseconds). */
70
+ get questionAskedAt() {
71
+ return this.request ? this.questionAt : null;
72
+ }
73
+ /** Is the wait about this request? */
74
+ owns(requestId) {
75
+ return !!requestId && this.request?.requestId === requestId;
76
+ }
77
+ /**
78
+ * Does this evaluation belong to the request that waits?
79
+ *
80
+ * The evaluation carries the identity of the request it was made for.
81
+ * A result of a request that was answered, replaced or cancelled is
82
+ * stale: it must not be applied to the request that is current now,
83
+ * because that request is a different question with its own decision.
84
+ *
85
+ * An evaluation without an identity belongs to nothing and is stale by
86
+ * default: the answer to "may I apply this?" is then "no".
87
+ */
88
+ ownsEvaluation(evaluation) {
89
+ if (!evaluation.requestId)
90
+ return false;
91
+ if (!this.owns(evaluation.requestId))
92
+ return false;
93
+ return this.currentSessionId === evaluation.sessionId;
94
+ }
95
+ /** The milliseconds since the question was asked. */
96
+ elapsedMs() {
97
+ if (!this.request)
98
+ return 0;
99
+ return Math.max(0, this.now() - this.questionAt);
100
+ }
101
+ /**
102
+ * The minutes since the question was asked.
103
+ *
104
+ * This is the one elapsed time: the countdown, the evaluation and the
105
+ * fallback of the judge all measure the same wait.
106
+ */
107
+ waitedMinutes() {
108
+ return this.elapsedMs() / 60_000;
109
+ }
110
+ /** Is the deadline of the decision reached? */
111
+ isDue() {
112
+ return this.elapsedMs() >= this.deps.waitMinutes * 60_000;
113
+ }
114
+ /**
115
+ * A question was asked: the wait starts.
116
+ *
117
+ * A question that replaces another one invalidates the evaluation of
118
+ * the old one: the generation is bumped, so a late result of the old
119
+ * request cannot change the state of the new one.
120
+ */
121
+ begin(request) {
122
+ this.generation += 1;
123
+ this.request = request;
124
+ this.questionAt = this.now();
125
+ this.setState("waiting", "the question waits for an answer");
126
+ try {
127
+ this.deps.countdown?.start(request.requestId, this.questionAt);
128
+ }
129
+ catch (error) {
130
+ this.report(error);
131
+ }
132
+ }
133
+ /**
134
+ * The question was answered by a human: the wait is over.
135
+ *
136
+ * The evaluation of that request - if it is still running - is
137
+ * invalidated: its result belongs to a question that has an answer.
138
+ */
139
+ answer(requestId) {
140
+ if (!this.owns(requestId))
141
+ return;
142
+ this.end("idle", "the question was answered");
143
+ }
144
+ /**
145
+ * The session changed: the wait belongs to a session that is gone.
146
+ */
147
+ invalidate(reason) {
148
+ if (!this.request && this.state === "idle")
149
+ return;
150
+ this.end("idle", reason);
151
+ }
152
+ /** The wait is over for any reason. */
153
+ cancel() {
154
+ this.end("idle", "the wait was cancelled");
155
+ }
156
+ /**
157
+ * The deadline is reached: evaluate the current request once.
158
+ *
159
+ * The evaluation runs only when the wait is still waiting, the deadline
160
+ * is reached and the session is the one the question was asked in. A
161
+ * second call - the countdown and the fallback poll can both arrive -
162
+ * does nothing: the state is no longer "waiting".
163
+ */
164
+ async evaluateDue() {
165
+ const request = this.request;
166
+ if (!request) {
167
+ return {
168
+ applied: false,
169
+ state: this.state,
170
+ reason: "no question is waiting",
171
+ discardReason: "no-request",
172
+ };
173
+ }
174
+ if (this.state !== "waiting") {
175
+ return {
176
+ applied: false,
177
+ state: this.state,
178
+ reason: `the wait is ${this.state}`,
179
+ discardReason: "not-waiting",
180
+ };
181
+ }
182
+ if (!this.isDue()) {
183
+ return {
184
+ applied: false,
185
+ state: this.state,
186
+ reason: "the question has not waited long enough",
187
+ discardReason: "not-due",
188
+ };
189
+ }
190
+ const session = this.deps.currentSessionId?.() ?? request.sessionId;
191
+ if (session !== request.sessionId) {
192
+ return {
193
+ applied: false,
194
+ state: this.state,
195
+ reason: "the question belongs to another session",
196
+ discardReason: "other-session",
197
+ };
198
+ }
199
+ const generation = this.generation;
200
+ this.setState("evaluating", "the decision of the question is running");
201
+ let evaluation;
202
+ try {
203
+ evaluation = await this.deps.evaluate(request, this.elapsedMs());
204
+ }
205
+ catch (error) {
206
+ // A failing evaluation is an error, not a decision.
207
+ evaluation = {
208
+ outcome: "wait",
209
+ reasoning: "",
210
+ error: { kind: "provider", message: messageOf(error) },
211
+ };
212
+ }
213
+ // The identity of the request is captured here and stamped on the
214
+ // result. The decision belongs to the request it was evaluated for:
215
+ // it cannot be applied to a request that only happens to be current
216
+ // when the result arrives.
217
+ evaluation = {
218
+ ...evaluation,
219
+ requestId: request.requestId,
220
+ sessionId: request.sessionId,
221
+ };
222
+ // Every late result is discarded: the question was answered, replaced
223
+ // or the session changed while the evaluation ran.
224
+ if (generation !== this.generation || this.request?.requestId !== request.requestId) {
225
+ return {
226
+ applied: false,
227
+ state: this.state,
228
+ reason: "the evaluation is stale",
229
+ discardReason: "stale",
230
+ };
231
+ }
232
+ const currentSession = this.deps.currentSessionId?.() ?? request.sessionId;
233
+ if (currentSession !== request.sessionId) {
234
+ return {
235
+ applied: false,
236
+ state: this.state,
237
+ reason: "the question belongs to another session",
238
+ discardReason: "other-session",
239
+ };
240
+ }
241
+ if (evaluation.error) {
242
+ // The provider failed: the work is not continued and nothing is
243
+ // decided. The question stays open for the human.
244
+ this.setState("evaluation_error", `the evaluation failed: ${evaluation.error.message}`, evaluation);
245
+ return {
246
+ applied: true,
247
+ state: "evaluation_error",
248
+ evaluation,
249
+ reason: evaluation.error.message,
250
+ };
251
+ }
252
+ if (evaluation.outcome === "wait") {
253
+ // A decision to wait is a blocked state: the work pauses and a
254
+ // human is needed. The wait does not arm another attempt.
255
+ this.setState("human_required", evaluation.reasoning || "the decision asks for a human", evaluation);
256
+ return {
257
+ applied: true,
258
+ state: "human_required",
259
+ evaluation,
260
+ reason: evaluation.reasoning,
261
+ };
262
+ }
263
+ this.setState("decided", evaluation.reasoning || `the decision is ${evaluation.outcome}`, evaluation);
264
+ return {
265
+ applied: true,
266
+ state: "decided",
267
+ evaluation,
268
+ reason: evaluation.reasoning,
269
+ };
270
+ }
271
+ /** End the wait: the request is gone and the countdown is released. */
272
+ end(state, reason) {
273
+ this.generation += 1;
274
+ this.request = null;
275
+ this.setState(state, reason);
276
+ try {
277
+ this.deps.countdown?.stop();
278
+ }
279
+ catch (error) {
280
+ this.report(error);
281
+ }
282
+ }
283
+ /** Report a state change. */
284
+ setState(state, reason, evaluation) {
285
+ this.state = state;
286
+ try {
287
+ this.deps.onState?.(state, {
288
+ requestId: this.request?.requestId ?? null,
289
+ state,
290
+ evaluation,
291
+ reason,
292
+ });
293
+ }
294
+ catch (error) {
295
+ this.report(error);
296
+ }
297
+ }
298
+ /** Report a failure without letting the report become a new failure. */
299
+ report(error) {
300
+ try {
301
+ this.deps.onError?.(error);
302
+ }
303
+ catch {
304
+ // The report of a failure must not become a new failure.
305
+ }
306
+ }
307
+ }
308
+ //# sourceMappingURL=wait-lifecycle.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wait-lifecycle.js","sourceRoot":"","sources":["../src/wait-lifecycle.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAuJH,6CAA6C;AAC7C,SAAS,SAAS,CAAC,KAAc;IAChC,MAAM,IAAI,GAAG,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpE,OAAO,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,KAAK,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC;AACvD,CAAC;AAED;;;;;;GAMG;AACH,MAAM,OAAO,uBAAuB;IAClB,IAAI,CAAoB;IACxB,GAAG,CAAe;IAC3B,KAAK,GAAuB,MAAM,CAAC;IACnC,OAAO,GAAuB,IAAI,CAAC;IACnC,UAAU,GAAG,CAAC,CAAC;IACvB;;;;;OAKG;IACK,UAAU,GAAG,CAAC,CAAC;IAEvB,YAAY,IAAuB;QAClC,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,GAAG,GAAG,IAAI,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC;IAC3C,CAAC;IAED,6BAA6B;IAC7B,IAAI,YAAY;QACf,OAAO,IAAI,CAAC,KAAK,CAAC;IACnB,CAAC;IAED,uCAAuC;IACvC,IAAI,gBAAgB;QACnB,OAAO,IAAI,CAAC,OAAO,EAAE,SAAS,IAAI,IAAI,CAAC;IACxC,CAAC;IAED,qDAAqD;IACrD,IAAI,gBAAgB;QACnB,OAAO,IAAI,CAAC,OAAO,EAAE,SAAS,IAAI,IAAI,CAAC;I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
2
  "name": "@pi-harness/jev-judge",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Jev Judge - Structured decision model for agent routing, E2E testing, and automated decisions",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -16,7 +16,9 @@ import {
16
16
  describeChoiceOption,
17
17
  renderChoiceExcerpt,
18
18
  MAX_CHOICE_OPTIONS,
19
+ type ChoiceDecisionContext,
19
20
  } from "./decision-context.js";
21
+ import { classifyQuestionRisk } from "./question-risk.js";
20
22
 
21
23
  /**
22
24
  * Task tracking state
@@ -29,6 +31,8 @@ export interface TaskState {
29
31
  userResponded: boolean;
30
32
  lastUserActivity?: Date;
31
33
  sessionStartTime: Date;
34
+ /** The moment the question was asked (the wait is measured from it). */
35
+ questionAskedAt?: Date;
32
36
  /** The bounded decision context (question, risk, task state). */
33
37
  context?: DecisionContext;
34
38
  }
@@ -377,6 +381,14 @@ export interface AutoContinueDecision {
377
381
  selectedOption?: string;
378
382
  /** The scope the evaluation selected. */
379
383
  scope?: DecisionScope;
384
+ /**
385
+ * The evaluation failed.
386
+ *
387
+ * A failed evaluation is not a decision: the outcome above is only the
388
+ * fallback of the failure, and the runtime must not record it as a
389
+ * decision of Jev.
390
+ */
391
+ evaluationError?: { kind: "provider" | "unknown"; message: string };
380
392
  }
381
393
 
382
394
  /**
@@ -413,13 +425,16 @@ export class AutoContinueJudge {
413
425
  private jev: JevJudge;
414
426
  private config: Required<AutoContinueConfig>;
415
427
 
416
- constructor(config: AutoContinueConfig) {
428
+ constructor(config: AutoContinueConfig, judge?: JevJudge) {
417
429
  this.config = {
418
430
  ...DEFAULT_CONFIG,
419
431
  ...config,
420
432
  } as Required<AutoContinueConfig>;
421
433
 
422
- this.jev = new JevJudge(config);
434
+ // The judge can be injected. The evaluation is the boundary to the
435
+ // provider, and a test has to be able to make that boundary fail: a
436
+ // provider failure is not a decision, and that has to be provable.
437
+ this.jev = judge ?? new JevJudge(config);
423
438
  }
424
439
 
425
440
  /**
@@ -512,16 +527,21 @@ export class AutoContinueJudge {
512
527
  const alternatives = (
513
528
  taskState.context?.question?.alternatives ?? []
514
529
  ).slice(0, MAX_CHOICE_OPTIONS);
515
- if (alternatives.length >= 2) {
530
+ // The facts of the alternatives. The risk of the selected option is
531
+ // derived from them, so they are kept for the whole decision.
532
+ const choiceContext: ChoiceDecisionContext | null =
533
+ alternatives.length >= 2
534
+ ? buildChoiceDecisionContext({
535
+ question: taskState.context?.question?.text ?? "",
536
+ alternatives,
537
+ contextText: taskState.context?.question?.contextText,
538
+ })
539
+ : null;
540
+ if (choiceContext) {
516
541
  const criteria: Record<string, string> = {};
517
542
  // The criterion carries the meaning of the option, not only its
518
543
  // label: "implement A" alone does not tell the evaluation what
519
544
  // A does.
520
- const choiceContext = buildChoiceDecisionContext({
521
- question: taskState.context?.question?.text ?? "",
522
- alternatives,
523
- contextText: taskState.context?.question?.contextText,
524
- });
525
545
  alternatives.forEach((alternative, index) => {
526
546
  const option = choiceContext.options[index];
527
547
  criteria[`option_${index + 1}`] = option
@@ -555,13 +575,66 @@ export class AutoContinueJudge {
555
575
 
556
576
  const result = await this.jev.evaluate(state, questions);
557
577
 
558
- return this.applyPolicy(this.buildDecision(result, taskState), taskState);
578
+ const decision = this.buildDecision(result, taskState);
579
+ // The risk of the option that was selected, not only the risk of the
580
+ // question: an alternative can ask for something the question did not
581
+ // mention.
582
+ this.applySelectedOptionRisk(decision, taskState, choiceContext);
583
+ return this.applyPolicy(decision, taskState);
559
584
  } catch (error) {
560
585
  logError("[AutoContinueJudge]", `Jev call failed: ${error}`);
561
- return this.applyPolicy(this.fallbackDecision(taskState), taskState);
586
+ const decision = this.fallbackDecision(taskState);
587
+ // The evaluation failed. The fallback is not a decision of Jev: it is
588
+ // marked, so the runtime can tell a provider failure from a decision
589
+ // to wait.
590
+ decision.evaluationError = {
591
+ kind: "provider",
592
+ message: error instanceof Error ? error.message : String(error),
593
+ };
594
+ return this.applyPolicy(decision, taskState);
562
595
  }
563
596
  }
564
597
 
598
+ /**
599
+ * The risk of the option the evaluation selected.
600
+ *
601
+ * The option carries its own action, and that action can be riskier than
602
+ * the question that offered it. An option that needs an explicit human
603
+ * authorization is not decided autonomously, whatever the evaluation
604
+ * proposed.
605
+ */
606
+ private applySelectedOptionRisk(
607
+ decision: AutoContinueDecision,
608
+ taskState: TaskState,
609
+ choiceContext: ChoiceDecisionContext | null,
610
+ ): void {
611
+ if (!decision.selectedOption || !choiceContext) return;
612
+ // The decision names the alternative the evaluation picked. The option
613
+ // of the context is found by its position: the alternatives and the
614
+ // options have the same order.
615
+ const alternatives = taskState.context?.question?.alternatives ?? [];
616
+ const index = alternatives.indexOf(decision.selectedOption);
617
+ const option = index >= 0 ? choiceContext.options[index] : undefined;
618
+ if (!option) return;
619
+ // The action of the option: its label (what the agent offered), its
620
+ // description and its constraints. The label alone can name the
621
+ // action: "delete the production database" is the action.
622
+ const action = [option.label, option.description, ...option.constraints]
623
+ .filter((part) => part.length > 0)
624
+ .join(" ");
625
+ if (action.length === 0) return;
626
+ const risk = classifyQuestionRisk({
627
+ kind: taskState.context?.question?.kind,
628
+ askType: taskState.context?.question?.askType,
629
+ text: action,
630
+ });
631
+ if (!risk.requiresExplicitAuthorization) return;
632
+ decision.outcome = "wait";
633
+ decision.action = "wait";
634
+ decision.policyApplied = "selected-option-requires-authorization";
635
+ decision.reasoning = `${decision.reasoning} - the selected option needs an explicit human authorization`;
636
+ }
637
+
565
638
  /**
566
639
  * Apply the deterministic policy to a proposed decision.
567
640
  *
@@ -906,26 +979,50 @@ export function buildDecisionState(taskState: TaskState): Record<string, unknown
906
979
 
907
980
  /**
908
981
  * Helper: Create task state from todo list
982
+ *
983
+ * The wait is measured from the moment the question was asked. The last
984
+ * activity of the user is only the fallback: a session that coded for twenty
985
+ * minutes and then waited five minutes for an answer must not tell the
986
+ * evaluation that it waited twenty-five minutes.
909
987
  */
910
988
  export function createTaskState(
911
989
  completedTasks: string[],
912
990
  remainingTasks: string[],
913
991
  lastUserActivity?: Date,
914
992
  sessionStartTime?: Date,
915
- context?: DecisionContext
993
+ context?: DecisionContext,
994
+ options?: TaskStateOptions
916
995
  ): TaskState {
917
996
  const totalTasks = completedTasks.length + remainingTasks.length;
997
+ const now = options?.now ?? (() => Date.now());
998
+ const waitStartedAt = options?.questionAskedAt ?? lastUserActivity;
918
999
 
919
1000
  return {
920
1001
  completedTasks,
921
1002
  remainingTasks,
922
1003
  totalTasks,
923
- waitTimeMinutes: lastUserActivity
924
- ? Math.round((Date.now() - lastUserActivity.getTime()) / 60000)
1004
+ waitTimeMinutes: waitStartedAt
1005
+ ? Math.round((now() - waitStartedAt.getTime()) / 60000)
925
1006
  : 0,
926
1007
  userResponded: false,
927
1008
  lastUserActivity,
928
1009
  sessionStartTime: sessionStartTime ?? new Date(),
1010
+ questionAskedAt: options?.questionAskedAt,
929
1011
  context,
930
1012
  };
931
1013
  }
1014
+
1015
+ /**
1016
+ * The optional facts of a task state.
1017
+ */
1018
+ export interface TaskStateOptions {
1019
+ /**
1020
+ * The moment the question was asked.
1021
+ *
1022
+ * The wait is measured from it, so the countdown, the evaluation and the
1023
+ * fallback of the judge see the same time.
1024
+ */
1025
+ questionAskedAt?: Date;
1026
+ /** The clock. The tests drive it. */
1027
+ now?: () => number;
1028
+ }
@@ -734,7 +734,7 @@ export {
734
734
  export type { AutonomyInstructionInput } from "./autonomy-instruction.js";
735
735
 
736
736
  // Export the deterministic risk classifier of a pending question
737
- export { classifyQuestionRisk } from "./question-risk.js";
737
+ export { classifyQuestionRisk, extractProposedAction } from "./question-risk.js";
738
738
  export type { QuestionRiskFacts, QuestionRiskInput } from "./question-risk.js";
739
739
 
740
740
  // Export WrapUpJudge
@@ -876,3 +876,18 @@ export type { ValidationVerdict, ValidationTieBreaker } from "./validation-tie-b
876
876
  // Export Task Intake
877
877
  export { TaskIntakeController, createTaskIntake } from "./task-intake.js";
878
878
  export type { TaskIntakeConfig, TaskIntakeResult } from "./task-intake.js";
879
+
880
+ // Export the lifecycle of a wait for a human answer. The controller owns
881
+ // the request, the session, the moment the question was asked and the one
882
+ // evaluation of that question.
883
+ export { WaitLifecycleController } from "./wait-lifecycle.js";
884
+ export type {
885
+ WaitCountdown,
886
+ WaitDiscardReason,
887
+ WaitEvaluation,
888
+ WaitLifecycleDeps,
889
+ WaitLifecycleResult,
890
+ WaitLifecycleState,
891
+ WaitRequest,
892
+ WaitStateDetail,
893
+ } from "./wait-lifecycle.js";