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
@@ -46,6 +46,14 @@ export interface QuestionRiskInput {
46
46
  askType?: string;
47
47
  /** The complete question text. */
48
48
  text?: string;
49
+ /**
50
+ * The concrete action the agent proposes.
51
+ *
52
+ * The risk is about the action, not about the whole message: a message
53
+ * that talks about many things carries words that have nothing to do with
54
+ * the action that is proposed.
55
+ */
56
+ proposedAction?: string;
49
57
  }
50
58
 
51
59
  interface RiskPattern {
@@ -54,6 +62,53 @@ interface RiskPattern {
54
62
  pattern: RegExp;
55
63
  }
56
64
 
65
+ /**
66
+ * How much of the action reaches the classifier.
67
+ */
68
+ export const MAX_ACTION_CHARS = 600;
69
+
70
+ /**
71
+ * The verbs that state a concrete action.
72
+ *
73
+ * The risk is about the action that is proposed, so the action has to be
74
+ * found in the message. A sentence that names no action does not belong to
75
+ * the action: it talks about the request, not about what happens.
76
+ */
77
+ const ACTION_VERBS =
78
+ /\b(delete|deletes|deleting|removed?|removing|drop|dropped|dropping|wipe|wipes|wiping|erase|erases|erasing|purge|purges|purging|truncate|truncates|truncating|revoke|revokes|revoking|rotate|rotates|rotating|reset|resets|resetting|rebuild|rebuilds|reinstall|reinstalls|uninstall|uninstalls|deploy|deploys|deploying|publish|publishes|publishing|release|releases|releasing|ship|ships|shipping|push|pushes|pushing|merge|merges|merging|rebase|rebases|force[- ]?push|squash|squashes|send|sends|sending|post|posts|posting|mail|mails|email|emails|notify|notifies|upload|uploads|uploading|transfer|transfers|wire|wires|pay|pays|paying|invoice|invoices|refund|refunds|migrate|migrates|migrating|upgrade|upgrades|downgrade|downgrades|install|installs|installing|overwrite|overwrites|overwriting|replace|replaces|replacing|rename|renames|renaming|move|moves|moving|copy|copies|copying|run|runs|running|execute|executes|restart|restarts|stop|stops|stopping|kill|kills|killing|close|closes|closing|grant|grants|granting|enable|enables|enabling|disable|disables|disabling|update|updates|updating|modify|modifies|modifying|write|writes|writing|patch|patches|patching|commit|commits|committing|revert|reverts|refactor|refactors|rewrite|rewrites|format|formats|lint|lints|generate|generates|create|creates|add|adds|implement|implements|build|builds|compile|compiles|seed|seeds|backfill|backfills|sync|syncs|fetch|fetches|query|queries|benchmark|benchmarks|profile|profiles|cleanup|cleanups|clean|cleans|prune|prunes)\b/i;
79
+
80
+ /**
81
+ * The action the agent proposes.
82
+ *
83
+ * The message carries the ask ("may I proceed?") and the action ("I will
84
+ * delete the branch"). The risk is about the action, so the action is
85
+ * extracted: the sentences of the message that state what happens. The
86
+ * question sentence itself is not an action - it asks, it does not act.
87
+ *
88
+ * When the message names no action, the question text is the action: the
89
+ * risk of the question is then the risk of the ask.
90
+ */
91
+ export function extractProposedAction(
92
+ contextText: string | undefined,
93
+ questionText: string | undefined,
94
+ ): string {
95
+ const question = (questionText ?? "").trim();
96
+ const context = (contextText ?? "").trim();
97
+ if (context.length === 0) return question.slice(0, MAX_ACTION_CHARS);
98
+
99
+ const sentences = context
100
+ .split(/(?<=[.!?])\s+|\n+/)
101
+ .map((sentence) => sentence.trim())
102
+ .filter((sentence) => sentence.length > 0);
103
+ const actionSentences = sentences.filter(
104
+ (sentence) => sentence !== question && ACTION_VERBS.test(sentence),
105
+ );
106
+ if (actionSentences.length === 0) {
107
+ return question.slice(0, MAX_ACTION_CHARS);
108
+ }
109
+ return actionSentences.join(" ").slice(0, MAX_ACTION_CHARS);
110
+ }
111
+
57
112
  /**
58
113
  * Words that name an action that destroys, drops or overwrites something.
59
114
  */
@@ -86,6 +141,36 @@ const SENSITIVE_PATTERNS: RiskPattern[] = [
86
141
  { name: "credentials", pattern: /\b(secret|credential|api[\s-]?key|token|password)\b/ },
87
142
  ];
88
143
 
144
+ /**
145
+ * The words that turn an action into a prohibition.
146
+ *
147
+ * "do not delete anything" is a prohibition, not a proposal: the risk of a
148
+ * message must not turn the words of a prohibition into a destructive
149
+ * action that blocks the work for good.
150
+ */
151
+ const NEGATION_WORDS =
152
+ /\b(do not|don'?t|never|without|avoid|refrain from|no need to)\b/;
153
+
154
+ /**
155
+ * Is the action at this position prohibited?
156
+ *
157
+ * The negation has to stand in front of the action, in the same clause: a
158
+ * negation that belongs to another clause ("delete the branch, do not touch
159
+ * main") does not prohibit the deletion.
160
+ */
161
+ function isNegated(text: string, index: number): boolean {
162
+ const before = text.slice(Math.max(0, index - 40), index);
163
+ // The clause of the action starts after the last sentence break.
164
+ const clause = before.split(/[.;!?\n]/).pop() ?? before;
165
+ return NEGATION_WORDS.test(clause);
166
+ }
167
+
168
+ /**
169
+ * Match the patterns of one kind of risk in a text.
170
+ *
171
+ * A pattern that is prohibited does not count: the words of a prohibition
172
+ * are not a proposal.
173
+ */
89
174
  function matchPatterns(
90
175
  text: string,
91
176
  patterns: RiskPattern[],
@@ -93,10 +178,11 @@ function matchPatterns(
93
178
  ): boolean {
94
179
  let matched = false;
95
180
  for (const { name, pattern } of patterns) {
96
- if (pattern.test(text)) {
97
- signals.push(name);
98
- matched = true;
99
- }
181
+ const match = pattern.exec(text);
182
+ if (!match) continue;
183
+ if (isNegated(text, match.index)) continue;
184
+ signals.push(name);
185
+ matched = true;
100
186
  }
101
187
  return matched;
102
188
  }
@@ -122,7 +208,12 @@ function matchPatterns(
122
208
  export function classifyQuestionRisk(
123
209
  input: QuestionRiskInput,
124
210
  ): QuestionRiskFacts {
125
- const text = (input.text ?? "").toLowerCase();
211
+ // The risk is about the action that is proposed. The proposed action
212
+ // describes it best; without one the question text does. The whole
213
+ // message is not the input: it carries the words of everything the
214
+ // agent said, and a word is not a risk.
215
+ const action = (input.proposedAction ?? input.text ?? "").trim();
216
+ const text = action.toLowerCase();
126
217
  const kind = input.kind;
127
218
  const signals: string[] = [];
128
219
 
@@ -0,0 +1,488 @@
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
+
29
+ import type { DecisionOutcome, DecisionScope } from "./auto-continue.js";
30
+
31
+ /**
32
+ * The state of a wait.
33
+ *
34
+ * - `idle`: nothing is waiting.
35
+ * - `waiting`: a question waits for a human answer.
36
+ * - `evaluating`: the decision of the question is running.
37
+ * - `decided`: Jev decided; the outcome says what the work does.
38
+ * - `human_required`: the decision needs a human; the work is blocked.
39
+ * - `evaluation_error`: the evaluation failed; no decision was made.
40
+ */
41
+ export type WaitLifecycleState =
42
+ | "idle"
43
+ | "waiting"
44
+ | "evaluating"
45
+ | "decided"
46
+ | "human_required"
47
+ | "evaluation_error";
48
+
49
+ /** The question a wait is about. */
50
+ export interface WaitRequest {
51
+ /** The canonical request ID of the question. */
52
+ requestId: string;
53
+ /** The session the question was asked in. */
54
+ sessionId: string;
55
+ /** The kind of the question ("approval", "choice", ...). */
56
+ kind?: string;
57
+ /** The typed ask of the question. */
58
+ askType?: string;
59
+ /** The text of the question. */
60
+ text?: string;
61
+ /** The message the question was detected in. */
62
+ contextText?: string;
63
+ /** The concrete alternatives of a choice question. */
64
+ alternatives?: string[];
65
+ }
66
+
67
+ /** The result of one evaluation. */
68
+ export interface WaitEvaluation {
69
+ /** The outcome of the decision. */
70
+ outcome: DecisionOutcome;
71
+ /** The option the evaluation selected for a choice question. */
72
+ selectedOption?: string;
73
+ /** The scope the evaluation selected. */
74
+ scope?: DecisionScope;
75
+ /** The reasoning of the decision. */
76
+ reasoning: string;
77
+ /** The policy rule that changed the outcome, when one did. */
78
+ policyApplied?: string;
79
+ /** The risk level the evaluation gave the action. */
80
+ riskLevel?: string;
81
+ /**
82
+ * The evaluation failed.
83
+ *
84
+ * A failed evaluation is not a decision: it says nothing about the
85
+ * action, so it must never be recorded as "Jev decided to wait".
86
+ */
87
+ error?: { kind: "provider" | "unknown"; message: string };
88
+ /**
89
+ * The request the evaluation was made for.
90
+ *
91
+ * The controller stamps it: a decision belongs to the request it was
92
+ * evaluated for, and to no other request. A result that arrives after
93
+ * its request was answered, replaced or cancelled must never be
94
+ * applied to the request that happens to be current when the result is
95
+ * applied.
96
+ */
97
+ requestId?: string;
98
+ /**
99
+ * The session the evaluation was made in.
100
+ *
101
+ * The controller stamps it for the same reason: a decision of one
102
+ * session is not a decision of another.
103
+ */
104
+ sessionId?: string;
105
+ }
106
+
107
+ /**
108
+ * The countdown of the wait.
109
+ *
110
+ * The controller owns the countdown; the implementation owns the display.
111
+ * The deadline is derived from the moment the question was asked, so the
112
+ * countdown and the decision can never drift apart.
113
+ */
114
+ export interface WaitCountdown {
115
+ /** Start the countdown of a request (or replace the running one). */
116
+ start(requestId: string, startedAt: number): void;
117
+ /** Release the countdown. */
118
+ stop(): void;
119
+ /** Is the countdown running? */
120
+ readonly active: boolean;
121
+ }
122
+
123
+ /** What the controller reports about a state change. */
124
+ export interface WaitStateDetail {
125
+ /** The request the state belongs to. */
126
+ requestId: string | null;
127
+ /** The state that was reached. */
128
+ state: WaitLifecycleState;
129
+ /** The decision, when the state was reached by one. */
130
+ evaluation?: WaitEvaluation;
131
+ /** The reason of the state, in words. */
132
+ reason: string;
133
+ }
134
+
135
+ /** The dependencies of the controller. */
136
+ export interface WaitLifecycleDeps {
137
+ /** The clock. The tests drive it. */
138
+ now?: () => number;
139
+ /** The countdown of the wait. */
140
+ countdown?: WaitCountdown;
141
+ /** The minutes the question waits for a human answer. */
142
+ waitMinutes: number;
143
+ /** The session the runtime is in. The tests drive it. */
144
+ currentSessionId?: () => string | null;
145
+ /** The evaluation of one request. */
146
+ evaluate: (
147
+ request: WaitRequest,
148
+ waitedMs: number,
149
+ ) => Promise<WaitEvaluation>;
150
+ /** The state of the wait changed. */
151
+ onState?: (state: WaitLifecycleState, detail: WaitStateDetail) => void;
152
+ /** A failure of the controller itself. */
153
+ onError?: (error: unknown) => void;
154
+ }
155
+
156
+ /** Why an evaluation was not applied. */
157
+ export type WaitDiscardReason =
158
+ | "no-request"
159
+ | "not-waiting"
160
+ | "not-due"
161
+ | "stale"
162
+ | "other-session";
163
+
164
+ /** What the controller did with an evaluation. */
165
+ export interface WaitLifecycleResult {
166
+ /** Did the evaluation change the state? */
167
+ applied: boolean;
168
+ /** The state of the wait afterwards. */
169
+ state: WaitLifecycleState;
170
+ /** The decision, when there was one. */
171
+ evaluation?: WaitEvaluation;
172
+ /** The reason, in words. */
173
+ reason: string;
174
+ /** Why the evaluation was not applied, when it was not. */
175
+ discardReason?: WaitDiscardReason;
176
+ }
177
+
178
+ /** The message of a failure, in one line. */
179
+ function messageOf(error: unknown): string {
180
+ const text = error instanceof Error ? error.message : String(error);
181
+ return text.replace(/\s+/g, " ").trim().slice(0, 200);
182
+ }
183
+
184
+ /**
185
+ * The controller of a wait for a human answer.
186
+ *
187
+ * The controller owns the lifecycle of one question at a time: a new
188
+ * question replaces the old one, an answer ends the wait, and a late result
189
+ * of an older request is discarded.
190
+ */
191
+ export class WaitLifecycleController {
192
+ private readonly deps: WaitLifecycleDeps;
193
+ private readonly now: () => number;
194
+ private state: WaitLifecycleState = "idle";
195
+ private request: WaitRequest | null = null;
196
+ private questionAt = 0;
197
+ /**
198
+ * Bumped on every change of the request.
199
+ *
200
+ * A result of an older generation belongs to a request that is gone: it
201
+ * is discarded instead of changing the state of the new one.
202
+ */
203
+ private generation = 0;
204
+
205
+ constructor(deps: WaitLifecycleDeps) {
206
+ this.deps = deps;
207
+ this.now = deps.now ?? (() => Date.now());
208
+ }
209
+
210
+ /** The state of the wait. */
211
+ get currentState(): WaitLifecycleState {
212
+ return this.state;
213
+ }
214
+
215
+ /** The request the wait belongs to. */
216
+ get currentRequestId(): string | null {
217
+ return this.request?.requestId ?? null;
218
+ }
219
+
220
+ /** The session the waiting question was asked in. */
221
+ get currentSessionId(): string | null {
222
+ return this.request?.sessionId ?? null;
223
+ }
224
+
225
+ /** The moment the question was asked (in milliseconds). */
226
+ get questionAskedAt(): number | null {
227
+ return this.request ? this.questionAt : null;
228
+ }
229
+
230
+ /** Is the wait about this request? */
231
+ owns(requestId: string | undefined | null): boolean {
232
+ return !!requestId && this.request?.requestId === requestId;
233
+ }
234
+
235
+ /**
236
+ * Does this evaluation belong to the request that waits?
237
+ *
238
+ * The evaluation carries the identity of the request it was made for.
239
+ * A result of a request that was answered, replaced or cancelled is
240
+ * stale: it must not be applied to the request that is current now,
241
+ * because that request is a different question with its own decision.
242
+ *
243
+ * An evaluation without an identity belongs to nothing and is stale by
244
+ * default: the answer to "may I apply this?" is then "no".
245
+ */
246
+ ownsEvaluation(evaluation: WaitEvaluation): boolean {
247
+ if (!evaluation.requestId) return false;
248
+ if (!this.owns(evaluation.requestId)) return false;
249
+ return this.currentSessionId === evaluation.sessionId;
250
+ }
251
+
252
+ /** The milliseconds since the question was asked. */
253
+ elapsedMs(): number {
254
+ if (!this.request) return 0;
255
+ return Math.max(0, this.now() - this.questionAt);
256
+ }
257
+
258
+ /**
259
+ * The minutes since the question was asked.
260
+ *
261
+ * This is the one elapsed time: the countdown, the evaluation and the
262
+ * fallback of the judge all measure the same wait.
263
+ */
264
+ waitedMinutes(): number {
265
+ return this.elapsedMs() / 60_000;
266
+ }
267
+
268
+ /** Is the deadline of the decision reached? */
269
+ isDue(): boolean {
270
+ return this.elapsedMs() >= this.deps.waitMinutes * 60_000;
271
+ }
272
+
273
+ /**
274
+ * A question was asked: the wait starts.
275
+ *
276
+ * A question that replaces another one invalidates the evaluation of
277
+ * the old one: the generation is bumped, so a late result of the old
278
+ * request cannot change the state of the new one.
279
+ */
280
+ begin(request: WaitRequest): void {
281
+ this.generation += 1;
282
+ this.request = request;
283
+ this.questionAt = this.now();
284
+ this.setState("waiting", "the question waits for an answer");
285
+ try {
286
+ this.deps.countdown?.start(request.requestId, this.questionAt);
287
+ } catch (error) {
288
+ this.report(error);
289
+ }
290
+ }
291
+
292
+ /**
293
+ * The question was answered by a human: the wait is over.
294
+ *
295
+ * The evaluation of that request - if it is still running - is
296
+ * invalidated: its result belongs to a question that has an answer.
297
+ */
298
+ answer(requestId: string): void {
299
+ if (!this.owns(requestId)) return;
300
+ this.end("idle", "the question was answered");
301
+ }
302
+
303
+ /**
304
+ * The session changed: the wait belongs to a session that is gone.
305
+ */
306
+ invalidate(reason: string): void {
307
+ if (!this.request && this.state === "idle") return;
308
+ this.end("idle", reason);
309
+ }
310
+
311
+ /** The wait is over for any reason. */
312
+ cancel(): void {
313
+ this.end("idle", "the wait was cancelled");
314
+ }
315
+
316
+ /**
317
+ * The deadline is reached: evaluate the current request once.
318
+ *
319
+ * The evaluation runs only when the wait is still waiting, the deadline
320
+ * is reached and the session is the one the question was asked in. A
321
+ * second call - the countdown and the fallback poll can both arrive -
322
+ * does nothing: the state is no longer "waiting".
323
+ */
324
+ async evaluateDue(): Promise<WaitLifecycleResult> {
325
+ const request = this.request;
326
+ if (!request) {
327
+ return {
328
+ applied: false,
329
+ state: this.state,
330
+ reason: "no question is waiting",
331
+ discardReason: "no-request",
332
+ };
333
+ }
334
+ if (this.state !== "waiting") {
335
+ return {
336
+ applied: false,
337
+ state: this.state,
338
+ reason: `the wait is ${this.state}`,
339
+ discardReason: "not-waiting",
340
+ };
341
+ }
342
+ if (!this.isDue()) {
343
+ return {
344
+ applied: false,
345
+ state: this.state,
346
+ reason: "the question has not waited long enough",
347
+ discardReason: "not-due",
348
+ };
349
+ }
350
+ const session = this.deps.currentSessionId?.() ?? request.sessionId;
351
+ if (session !== request.sessionId) {
352
+ return {
353
+ applied: false,
354
+ state: this.state,
355
+ reason: "the question belongs to another session",
356
+ discardReason: "other-session",
357
+ };
358
+ }
359
+
360
+ const generation = this.generation;
361
+ this.setState("evaluating", "the decision of the question is running");
362
+ let evaluation: WaitEvaluation;
363
+ try {
364
+ evaluation = await this.deps.evaluate(request, this.elapsedMs());
365
+ } catch (error) {
366
+ // A failing evaluation is an error, not a decision.
367
+ evaluation = {
368
+ outcome: "wait",
369
+ reasoning: "",
370
+ error: { kind: "provider", message: messageOf(error) },
371
+ };
372
+ }
373
+
374
+ // The identity of the request is captured here and stamped on the
375
+ // result. The decision belongs to the request it was evaluated for:
376
+ // it cannot be applied to a request that only happens to be current
377
+ // when the result arrives.
378
+ evaluation = {
379
+ ...evaluation,
380
+ requestId: request.requestId,
381
+ sessionId: request.sessionId,
382
+ };
383
+
384
+ // Every late result is discarded: the question was answered, replaced
385
+ // or the session changed while the evaluation ran.
386
+ if (generation !== this.generation || this.request?.requestId !== request.requestId) {
387
+ return {
388
+ applied: false,
389
+ state: this.state,
390
+ reason: "the evaluation is stale",
391
+ discardReason: "stale",
392
+ };
393
+ }
394
+ const currentSession = this.deps.currentSessionId?.() ?? request.sessionId;
395
+ if (currentSession !== request.sessionId) {
396
+ return {
397
+ applied: false,
398
+ state: this.state,
399
+ reason: "the question belongs to another session",
400
+ discardReason: "other-session",
401
+ };
402
+ }
403
+
404
+ if (evaluation.error) {
405
+ // The provider failed: the work is not continued and nothing is
406
+ // decided. The question stays open for the human.
407
+ this.setState(
408
+ "evaluation_error",
409
+ `the evaluation failed: ${evaluation.error.message}`,
410
+ evaluation,
411
+ );
412
+ return {
413
+ applied: true,
414
+ state: "evaluation_error",
415
+ evaluation,
416
+ reason: evaluation.error.message,
417
+ };
418
+ }
419
+
420
+ if (evaluation.outcome === "wait") {
421
+ // A decision to wait is a blocked state: the work pauses and a
422
+ // human is needed. The wait does not arm another attempt.
423
+ this.setState(
424
+ "human_required",
425
+ evaluation.reasoning || "the decision asks for a human",
426
+ evaluation,
427
+ );
428
+ return {
429
+ applied: true,
430
+ state: "human_required",
431
+ evaluation,
432
+ reason: evaluation.reasoning,
433
+ };
434
+ }
435
+
436
+ this.setState(
437
+ "decided",
438
+ evaluation.reasoning || `the decision is ${evaluation.outcome}`,
439
+ evaluation,
440
+ );
441
+ return {
442
+ applied: true,
443
+ state: "decided",
444
+ evaluation,
445
+ reason: evaluation.reasoning,
446
+ };
447
+ }
448
+
449
+ /** End the wait: the request is gone and the countdown is released. */
450
+ private end(state: WaitLifecycleState, reason: string): void {
451
+ this.generation += 1;
452
+ this.request = null;
453
+ this.setState(state, reason);
454
+ try {
455
+ this.deps.countdown?.stop();
456
+ } catch (error) {
457
+ this.report(error);
458
+ }
459
+ }
460
+
461
+ /** Report a state change. */
462
+ private setState(
463
+ state: WaitLifecycleState,
464
+ reason: string,
465
+ evaluation?: WaitEvaluation,
466
+ ): void {
467
+ this.state = state;
468
+ try {
469
+ this.deps.onState?.(state, {
470
+ requestId: this.request?.requestId ?? null,
471
+ state,
472
+ evaluation,
473
+ reason,
474
+ });
475
+ } catch (error) {
476
+ this.report(error);
477
+ }
478
+ }
479
+
480
+ /** Report a failure without letting the report become a new failure. */
481
+ private report(error: unknown): void {
482
+ try {
483
+ this.deps.onError?.(error);
484
+ } catch {
485
+ // The report of a failure must not become a new failure.
486
+ }
487
+ }
488
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/knowledge-retrieval",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Knowledge retrieval via TencentDB-Agent-Memory MCP (RFC-0105)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/learning-engine",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Learning engine for extracting lessons from runtime execution (RFC-0058)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/logging",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "type": "module",
5
5
  "description": "Centralized structured application logging with buffered Cloudflare R2 and webhook transports",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/memory-engine",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Memory engine with OKF integration for durable knowledge management (RFC-0060)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/notification",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "pi-harness-runtime — notification",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/paperclip-integration",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Paperclip API integration: poll agent inbox, route tasks to pi.dev, Telegram alerts",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/performance-optimizer",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Performance optimization analyzer for pi-harness runtime (RFC-0056)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/privilege-broker",
3
- "version": "1.1.470",
3
+ "version": "1.1.472",
4
4
  "description": "Privilege Broker — capability registry and command executor for autonomous runtime (RFC-0101 §7)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",