pi-harness-runtime 1.1.507 → 1.1.508

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 (80) hide show
  1. package/CHANGELOG.md +84 -0
  2. package/harness/auto-resume-marker.ts +177 -0
  3. package/harness/scope-expansion-runtime.ts +337 -0
  4. package/harness/scope-expansion.ts +80 -6
  5. package/index.ts +396 -7
  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.map +1 -1
  45. package/packages/notification/dist/notification-center.js +14 -0
  46. package/packages/notification/dist/notification-center.js.map +1 -1
  47. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  48. package/packages/notification/dist/notification-policy.js +3 -0
  49. package/packages/notification/dist/notification-policy.js.map +1 -1
  50. package/packages/notification/dist/types.d.ts +10 -1
  51. package/packages/notification/dist/types.d.ts.map +1 -1
  52. package/packages/notification/package.json +1 -1
  53. package/packages/notification/src/adapters/detail-format.ts +17 -1
  54. package/packages/notification/src/adapters/email-adapter.ts +2 -0
  55. package/packages/notification/src/adapters/line-adapter.ts +2 -0
  56. package/packages/notification/src/adapters/ntfy-adapter.ts +2 -0
  57. package/packages/notification/src/adapters/telegram-adapter.ts +2 -4
  58. package/packages/notification/src/notification-center.ts +14 -0
  59. package/packages/notification/src/notification-policy.ts +3 -0
  60. package/packages/notification/src/types.ts +11 -0
  61. package/packages/paperclip-integration/package.json +1 -1
  62. package/packages/performance-optimizer/package.json +1 -1
  63. package/packages/privilege-broker/package.json +1 -1
  64. package/packages/prompt-compiler/package.json +1 -1
  65. package/packages/providers/package.json +1 -1
  66. package/packages/qdrant-skills/package.json +1 -1
  67. package/packages/quota-manager/package.json +1 -1
  68. package/packages/relay/package.json +1 -1
  69. package/packages/skill-mcp-client/package.json +1 -1
  70. package/packages/skills/package.json +1 -1
  71. package/packages/todo-bd-sync/package.json +1 -1
  72. package/packages/token-estimation/package.json +1 -1
  73. package/packages/tooling-preference/package.json +1 -1
  74. package/packages/trajectory/package.json +1 -1
  75. package/packages/tui/package.json +1 -1
  76. package/packages/two-phase-review/package.json +1 -1
  77. package/packages/types/package.json +1 -1
  78. package/packages/webmcp-tester/package.json +1 -1
  79. package/packages/wiki/package.json +1 -1
  80. package/packages/write-review/package.json +1 -1
@@ -184,6 +184,7 @@ export function scopeDecisionMessage(
184
184
  `Scope: ${decision.selectedIds.length > 0 ? decision.selectedIds.join(", ") : "none"}.`,
185
185
  `Reason: ${decision.reasoning}`,
186
186
  `Action: ${action}.`,
187
+ `Proposed: ${proposal.scope}`,
187
188
  ].join("\n");
188
189
  }
189
190
 
@@ -219,7 +220,10 @@ export interface ScopeExpansionDeps {
219
220
  * The result says whether at least one route accepted the message. An
220
221
  * acknowledgement is a submission, not a reading.
221
222
  */
222
- deliver(text: string, meta: { id: string; kind: "proposal" | "decision" }): Promise<{
223
+ deliver(
224
+ text: string,
225
+ meta: { id: string; kind: "proposal" | "decision"; questionId?: string },
226
+ ): Promise<{
223
227
  delivered: boolean;
224
228
  failures: string[];
225
229
  }>;
@@ -227,6 +231,14 @@ export interface ScopeExpansionDeps {
227
231
  judge(proposal: ScopeProposal): Promise<ScopeDecision>;
228
232
  /** Start the authorized work. */
229
233
  dispatch(proposal: ScopeProposal, ids: string[]): void;
234
+ /**
235
+ * The latest human decision of a proposal.
236
+ *
237
+ * It is read after the delivery of the decision and before the
238
+ * dispatch: a rejection that arrived while the decision was on its way
239
+ * still prevents the work.
240
+ */
241
+ latestHumanDecision?(proposal: ScopeProposal): "approve" | "reject" | undefined;
230
242
  /** The log of the controller. */
231
243
  log?(message: string): void;
232
244
  }
@@ -376,10 +388,31 @@ export class ScopeExpansionController {
376
388
  if (proposal.state === "dispatched" || proposal.state === "finished") {
377
389
  return { started: false, reason: "the proposal was already executed" };
378
390
  }
379
- const scope = authorizedScope(proposal, decision);
391
+ // The human decides. The answer is read before the delivery, so the
392
+ // delivered message and the executed work agree.
393
+ let effective = decision;
394
+ const latestBefore = this.deps.latestHumanDecision?.(proposal);
395
+ if (latestBefore === "reject") {
396
+ effective = {
397
+ outcome: "reject",
398
+ selectedIds: [],
399
+ reasoning: "the human rejected the proposal",
400
+ source: "human",
401
+ };
402
+ proposal.decision = effective;
403
+ } else if (latestBefore === "approve" && decision.source !== "human") {
404
+ effective = {
405
+ ...decision,
406
+ outcome: "approve",
407
+ selectedIds: [...proposal.proposedIds],
408
+ source: "human",
409
+ };
410
+ proposal.decision = effective;
411
+ }
412
+ const scope = authorizedScope(proposal, effective);
380
413
  const action: "starting the selected work" | "remaining stopped" =
381
414
  scope.ids.length > 0 ? "starting the selected work" : "remaining stopped";
382
- const delivery = await this.deps.deliver(scopeDecisionMessage(proposal, decision, action), {
415
+ const delivery = await this.deps.deliver(scopeDecisionMessage(proposal, effective, action), {
383
416
  id: proposal.id,
384
417
  kind: "decision",
385
418
  });
@@ -390,12 +423,53 @@ export class ScopeExpansionController {
390
423
  return { started: false, reason: proposal.stopReason };
391
424
  }
392
425
  proposal.state = "decided";
393
- if (scope.ids.length === 0) {
426
+ // The answer is read again after the delivery: a rejection that
427
+ // arrived while the decision was on its way still prevents the work.
428
+ const latestAfter = this.deps.latestHumanDecision?.(proposal);
429
+ if (latestAfter === "reject" && effective.outcome !== "reject") {
430
+ proposal.state = "stopped";
431
+ proposal.stopReason =
432
+ "the human rejected the proposal after the decision was delivered";
433
+ this.deps.log?.(
434
+ `The scope proposal ${proposal.id} stays unexecuted: ${proposal.stopReason}`,
435
+ );
436
+ return { started: false, reason: proposal.stopReason };
437
+ }
438
+ let finalScope = scope;
439
+ if (latestAfter === "approve" && effective.source !== "human") {
440
+ const approved: ScopeDecision = {
441
+ ...effective,
442
+ outcome: "approve",
443
+ selectedIds: [...proposal.proposedIds],
444
+ source: "human",
445
+ };
446
+ proposal.decision = approved;
447
+ finalScope = authorizedScope(proposal, approved);
448
+ // The delivered message said something else: the human has to
449
+ // know what started. A correction that reaches nobody leaves
450
+ // the work stopped.
451
+ const correction = await this.deps.deliver(
452
+ scopeDecisionMessage(proposal, approved, "starting the selected work"),
453
+ { id: proposal.id, kind: "decision" },
454
+ );
455
+ if (!correction.delivered) {
456
+ proposal.state = "stopped";
457
+ proposal.stopReason = `the correction was not delivered: ${correction.failures.join(", ")}`;
458
+ this.deps.log?.(
459
+ `The scope proposal ${proposal.id} stays unexecuted: ${proposal.stopReason}`,
460
+ );
461
+ return { started: false, reason: proposal.stopReason };
462
+ }
463
+ }
464
+ if (finalScope.ids.length === 0) {
394
465
  proposal.state = "stopped";
395
- proposal.stopReason = scope.reason ?? "the decision authorizes no work";
466
+ proposal.stopReason =
467
+ effective.outcome === "reject"
468
+ ? effective.reasoning
469
+ : (finalScope.reason ?? "the decision authorizes no work");
396
470
  return { started: false, reason: proposal.stopReason };
397
471
  }
398
- this.deps.dispatch(proposal, scope.ids);
472
+ this.deps.dispatch(proposal, finalScope.ids);
399
473
  proposal.state = "dispatched";
400
474
  return { started: true };
401
475
  }
package/index.ts CHANGED
@@ -95,6 +95,25 @@ import {
95
95
  RESUME_SCOPE_RULE,
96
96
  type ResumeWorkState,
97
97
  } from "./harness/resume-scope.ts";
98
+ import {
99
+ buildAutoResumeMessage,
100
+ autoResumeDetails,
101
+ findAutoResumeIndex,
102
+ isAutoResumeMessage,
103
+ neutralizeAutoResume,
104
+ } from "./harness/auto-resume-marker.ts";
105
+ import {
106
+ ScopeExpansionRuntime,
107
+ type HumanScopeOutcome,
108
+ } from "./harness/scope-expansion-runtime.ts";
109
+ import {
110
+ MAX_SCOPE_CANDIDATES,
111
+ SCOPE_EXPANSION_WINDOW_MS,
112
+ scopeProposalMessage,
113
+ type ScopeCandidate,
114
+ type ScopeDecision,
115
+ type ScopeProposal,
116
+ } from "./harness/scope-expansion.ts";
98
117
  import type { ProviderFailure } from "./harness/provider-failure.ts";
99
118
  import {
100
119
  createProviderRecoveryController,
@@ -193,10 +212,23 @@ import { centralInfo, initCentralLogging, redactText } from "./packages/logging/
193
212
  * Get tasks from bd (beads) for Jev decision context.
194
213
  * Returns { completed, remaining } arrays of task descriptions.
195
214
  */
215
+ /**
216
+ * One issue of the backlog, with the exact id.
217
+ *
218
+ * The exact id is what a proposal names. A title is not an identity: two
219
+ * issues can carry the same title, and only the id tells them apart.
220
+ */
221
+ interface BacklogIssue {
222
+ id: string;
223
+ title: string;
224
+ status?: string;
225
+ }
226
+
196
227
  async function getTaskContext(): Promise<{
197
228
  completed: string[];
198
229
  remaining: string[];
199
230
  total: number;
231
+ issues: BacklogIssue[];
200
232
  }> {
201
233
  try {
202
234
  const { execSync } = await import("node:child_process");
@@ -205,10 +237,15 @@ async function getTaskContext(): Promise<{
205
237
  encoding: "utf8",
206
238
  timeout: 5000,
207
239
  });
208
- const tasks = JSON.parse(output) as Array<{ title?: string; status?: string }>;
240
+ const tasks = JSON.parse(output) as Array<{
241
+ id?: string;
242
+ title?: string;
243
+ status?: string;
244
+ }>;
209
245
 
210
246
  const completed: string[] = [];
211
247
  const remaining: string[] = [];
248
+ const issues: BacklogIssue[] = [];
212
249
 
213
250
  for (const task of tasks ?? []) {
214
251
  if (!task.title) continue;
@@ -216,6 +253,11 @@ async function getTaskContext(): Promise<{
216
253
  completed.push(task.title);
217
254
  } else {
218
255
  remaining.push(task.title);
256
+ // An issue without an id cannot be proposed: a proposal
257
+ // names exact ids.
258
+ if (typeof task.id === "string" && task.id) {
259
+ issues.push({ id: task.id, title: task.title, status: task.status });
260
+ }
219
261
  }
220
262
  }
221
263
 
@@ -223,10 +265,11 @@ async function getTaskContext(): Promise<{
223
265
  completed,
224
266
  remaining,
225
267
  total: completed.length + remaining.length,
268
+ issues,
226
269
  };
227
270
  } catch {
228
271
  // bd not available or error - return empty context
229
- return { completed: [], remaining: [], total: 0 };
272
+ return { completed: [], remaining: [], total: 0, issues: [] };
230
273
  }
231
274
  }
232
275
 
@@ -629,6 +672,9 @@ const sharedState = {
629
672
  // The state of the work of the request that is running. The automatic
630
673
  // resume reads it to know whether the work of the request remains.
631
674
  workContext: null as unknown,
675
+ // The runtime of the scope expansion: the backlog that could follow a
676
+ // finished request is proposed, and only the approved issues start.
677
+ scopeRuntime: null as ScopeExpansionRuntime | null,
632
678
  };
633
679
 
634
680
  /**
@@ -639,6 +685,20 @@ const sharedState = {
639
685
  */
640
686
  let suppressedResumeReported = false;
641
687
 
688
+ /** The number of the resumes that the harness queued in this session. */
689
+ let resumeNonceCounter = 0;
690
+
691
+ /**
692
+ * A nonce that tells one resume from another.
693
+ *
694
+ * The nonce is part of the marker of the resume, so a log line names the
695
+ * exact resume that was queued.
696
+ */
697
+ function nextResumeNonce(): string {
698
+ resumeNonceCounter += 1;
699
+ return `${Date.now().toString(36)}-${resumeNonceCounter}`;
700
+ }
701
+
642
702
  /**
643
703
  * Report that an automatic resume was suppressed.
644
704
  *
@@ -739,6 +799,60 @@ function beginHumanRequest(): void {
739
799
  suppressedResumeReported = false;
740
800
  }
741
801
 
802
+ /**
803
+ * Did a notification reach a channel?
804
+ *
805
+ * A skipped channel - a disabled one - is not a delivery: the human was not
806
+ * told, and work that the human was not told about must not start.
807
+ */
808
+ function deliveryOf(results: unknown): { delivered: boolean; failures: string[] } {
809
+ if (!Array.isArray(results)) {
810
+ return { delivered: false, failures: ["the notification returned no result"] };
811
+ }
812
+ const rows = results as Array<{
813
+ success?: boolean;
814
+ channel?: string;
815
+ error?: string;
816
+ skipped?: boolean;
817
+ }>;
818
+ const reached = rows.filter((row) => row.success && !row.skipped);
819
+ const failures = rows
820
+ .filter((row) => !row.success || row.skipped)
821
+ .map((row) => `${row.channel ?? "channel"}: ${row.error ?? "not delivered"}`);
822
+ return { delivered: reached.length > 0, failures };
823
+ }
824
+
825
+ /**
826
+ * Propose the backlog that could follow a finished request.
827
+ *
828
+ * The proposal names exact ids, and the decision of the human - or of Jev,
829
+ * when the five minutes are over without an answer - decides what starts.
830
+ * Nothing of the backlog starts without that decision.
831
+ */
832
+ async function proposeScopeExpansion(): Promise<void> {
833
+ const runtime = sharedState.scopeRuntime;
834
+ if (!runtime) return;
835
+ // One proposal waits for an answer: a second one would ask the same
836
+ // human twice about the same backlog.
837
+ if (runtime.open.length > 0) return;
838
+ const context = await getTaskContext().catch(() => null);
839
+ if (!context || context.issues.length === 0) return;
840
+ const candidates: ScopeCandidate[] = context.issues
841
+ .slice(0, MAX_SCOPE_CANDIDATES)
842
+ .map((issue) => ({ id: issue.id, title: issue.title }));
843
+ const generation = requestScopeTracker.generation;
844
+ await runtime.propose({
845
+ requestId: `request-${generation}`,
846
+ workspace: _piSessionCwd || process.cwd(),
847
+ generation,
848
+ candidates,
849
+ scope: `work on ${candidates.length} issue(s) of the backlog of the session`,
850
+ validation: "the tests of the repository and the closing of every named issue",
851
+ risks: ["the work was not asked for"],
852
+ choices: ["run the named issues", "keep the backlog closed"],
853
+ });
854
+ }
855
+
742
856
  /**
743
857
  * Apply an approval decision from a channel to the pending question.
744
858
  *
@@ -770,6 +884,26 @@ function applyChannelApproval(
770
884
  logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
771
885
  logQuestionTransition(requestId, "answered", `${channel}:${action}`);
772
886
 
887
+ // A question of a scope proposal is not a question of the work of the
888
+ // request: it asks whether the backlog may follow. The answer decides
889
+ // the proposal, and the work of the request stays what it was.
890
+ const scopeProposal = sharedState.scopeRuntime?.proposalForQuestion(requestId);
891
+ if (scopeProposal) {
892
+ const outcome: HumanScopeOutcome = result.resolution === "yes" ? "approve" : "reject";
893
+ void sharedState.scopeRuntime
894
+ ?.answerByQuestion(requestId, outcome, `${channel}:${action}`)
895
+ .then((executed) => {
896
+ logToFile(
897
+ "[scope-expansion]",
898
+ `The proposal ${scopeProposal.id} was answered (${outcome}): started=${executed.started}`,
899
+ );
900
+ })
901
+ .catch((error) => {
902
+ logToFile("[scope-expansion]", "The answer of the proposal failed:", String(error));
903
+ });
904
+ return true;
905
+ }
906
+
773
907
  // The question is answered, so the wait is over. The wait state is only
774
908
  // cleared after a successful resolution.
775
909
  // The controller owns the wait: the answer ends it, and an evaluation
@@ -2884,8 +3018,182 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2884
3018
  let validationLedger: import("./packages/jev-judge/dist/validation-ledger.js").ValidationLedger | null = null;
2885
3019
 
2886
3020
  // Create controller on session_start with proper dispatch callback
3021
+ /**
3022
+ * The runtime of the scope expansion.
3023
+ *
3024
+ * The backlog of the session is not work of the request that just
3025
+ * finished. When the request is done, the runtime proposes the exact
3026
+ * issues that could follow, the human decides - or Jev decides when
3027
+ * the five minutes are over - and only the approved ids start. The
3028
+ * decision is delivered before the work starts, and a decision that
3029
+ * reaches nobody leaves the work stopped.
3030
+ */
3031
+ function createScopeExpansionRuntime(): ScopeExpansionRuntime {
3032
+ return new ScopeExpansionRuntime({
3033
+ now: () => Date.now(),
3034
+ deliver: async (text, meta) => {
3035
+ const center = _nc?.center as NcCenter | undefined;
3036
+ if (!center) {
3037
+ return { delivered: false, failures: ["no notification center"] };
3038
+ }
3039
+ const proposal = sharedState.scopeRuntime?.get(meta.id);
3040
+ try {
3041
+ if (meta.kind === "proposal") {
3042
+ const results = await center.notifyWithApproval(
3043
+ "ScopeProposal" as never,
3044
+ {
3045
+ jobId: meta.id,
3046
+ requirement: text,
3047
+ questionId: meta.questionId,
3048
+ questionKind: "approval",
3049
+ scopeIds: proposal?.proposedIds,
3050
+ scopeDeadline: proposal
3051
+ ? new Date(proposal.deadlineAt).toISOString()
3052
+ : undefined,
3053
+ } as never,
3054
+ { approveLabel: "Run these", rejectLabel: "Keep it closed" },
3055
+ );
3056
+ return deliveryOf(results);
3057
+ }
3058
+ const results = await center.notify("ScopeDecision" as never, {
3059
+ jobId: meta.id,
3060
+ requirement: text,
3061
+ scopeIds: proposal?.proposedIds,
3062
+ } as never);
3063
+ return deliveryOf(results);
3064
+ } catch (error) {
3065
+ return { delivered: false, failures: [String(error)] };
3066
+ }
3067
+ },
3068
+ judge: async (proposal) => {
3069
+ const judge = new mod.AutoContinueJudge({
3070
+ providers: jevProviders,
3071
+ proceedThreshold: 0.7,
3072
+ maxWaitMinutes: 30,
3073
+ });
3074
+ const waitedMinutes = Math.max(
3075
+ 0,
3076
+ Math.round((Date.now() - proposal.createdAt) / 60_000),
3077
+ );
3078
+ const question = scopeProposalMessage(proposal);
3079
+ const decision = await judge.decide({
3080
+ completedTasks: [],
3081
+ remainingTasks: proposal.proposedIds,
3082
+ totalTasks: proposal.proposedIds.length,
3083
+ waitTimeMinutes: waitedMinutes,
3084
+ userResponded: false,
3085
+ sessionStartTime: new Date(proposal.createdAt),
3086
+ questionAskedAt: new Date(proposal.createdAt),
3087
+ context: {
3088
+ question: {
3089
+ requestId: `scope-question-${proposal.id}`,
3090
+ text: question,
3091
+ kind: "approval",
3092
+ askType: "approval",
3093
+ alternatives: proposal.choices,
3094
+ contextText: question,
3095
+ proposedAction: proposal.scope,
3096
+ consequence: "the named issues become work of this session",
3097
+ requiresExplicitAuthorization: false,
3098
+ destructive: false,
3099
+ external: false,
3100
+ reversible: true,
3101
+ },
3102
+ currentTask: proposal.scope,
3103
+ totalTasks: proposal.proposedIds.length,
3104
+ nextTasks: proposal.proposedIds,
3105
+ waitedMinutes,
3106
+ deadlineMinutes: Math.round(SCOPE_EXPANSION_WINDOW_MS / 60_000),
3107
+ },
3108
+ });
3109
+ const outcome: ScopeDecision["outcome"] =
3110
+ decision.outcome === "approve" || decision.outcome === "proceed_with_caution"
3111
+ ? "approve"
3112
+ : decision.outcome === "reject"
3113
+ ? "reject"
3114
+ : "wait";
3115
+ return {
3116
+ outcome,
3117
+ selectedIds: outcome === "approve" ? [...proposal.proposedIds] : [],
3118
+ reasoning: decision.reasoning,
3119
+ source: "jev",
3120
+ failed: decision.evaluationError !== undefined,
3121
+ };
3122
+ },
3123
+ dispatch: (proposal, ids) => {
3124
+ // The approval starts new work: it begins a new scope, so
3125
+ // the todos of the finished request stay its history.
3126
+ beginHumanRequest();
3127
+ const lines = ids.map((id) => `- ${id}`).join("\n");
3128
+ const message = [
3129
+ "The human approved the following issues of the backlog.",
3130
+ "Work on exactly these ids and stop when they are done:",
3131
+ lines,
3132
+ ].join("\n");
3133
+ void (async () => {
3134
+ try {
3135
+ await pi.sendUserMessage(message, { deliverAs: "steer" });
3136
+ } catch (error) {
3137
+ logToFile(
3138
+ "[scope-expansion]",
3139
+ `The dispatch of the proposal ${proposal.id} failed:`,
3140
+ String(error),
3141
+ );
3142
+ }
3143
+ })();
3144
+ },
3145
+ registerQuestion: (proposal) => {
3146
+ const question = pqController.createQuestion({
3147
+ text: scopeProposalMessage(proposal),
3148
+ sessionId: _sessionId,
3149
+ workspacePath: _piSessionCwd || "/",
3150
+ jobId: proposal.id,
3151
+ kind: "approval",
3152
+ askType: "approval",
3153
+ alternatives: proposal.choices,
3154
+ contextText: scopeProposalMessage(proposal),
3155
+ risk: {
3156
+ requiresExplicitAuthorization: false,
3157
+ destructive: false,
3158
+ reversible: true,
3159
+ external: false,
3160
+ },
3161
+ relevance:
3162
+ // The question is asked after the work of the request
3163
+ // is done: it is not obsolete, and it does not wait
3164
+ // for an automatic decision of the request.
3165
+ "final-request",
3166
+ });
3167
+ return question.requestId;
3168
+ },
3169
+ cancelQuestion: (questionId) => {
3170
+ pqController.expireByTimeout?.(questionId, "the proposal was not delivered");
3171
+ },
3172
+ latestHumanDecision: (proposal) => {
3173
+ const questionId = sharedState.scopeRuntime?.questionIdFor(proposal.id);
3174
+ if (!questionId) return undefined;
3175
+ const resolution = pqController.getQuestion(questionId)?.resolution;
3176
+ if (resolution === "yes") return "approve";
3177
+ if (resolution === "no") return "reject";
3178
+ return undefined;
3179
+ },
3180
+ groupFinished: async (_proposal: ScopeProposal, ids) => {
3181
+ const context = await getTaskContext().catch(() => null);
3182
+ if (!context) return false;
3183
+ const open = new Set(context.issues.map((issue) => issue.id));
3184
+ return ids.every((id) => !open.has(id));
3185
+ },
3186
+ log: (message) => logToFile("[scope-expansion]", message),
3187
+ });
3188
+ }
3189
+
2887
3190
  pi.on("session_start", async (_event, ctx) => {
2888
3191
  try {
3192
+ // The runtime of the scope expansion belongs to the session:
3193
+ // a session that starts has no open proposal, and a session
3194
+ // that ends leaves none behind.
3195
+ sharedState.scopeRuntime?.dispose();
3196
+ sharedState.scopeRuntime = createScopeExpansionRuntime();
2889
3197
  const { TodoContinuationController } = await import("./packages/jev-judge/dist/continuation-controller.js");
2890
3198
  const { ValidationLedger } = await import("./packages/jev-judge/dist/validation-ledger.js");
2891
3199
  // The ledger records which validation tier ran. The controller
@@ -2949,6 +3257,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2949
3257
  todoContinuationHandle = null;
2950
3258
  sharedState.todoContinuationController = null;
2951
3259
  sharedState.validationLedger = null;
3260
+ // The proposal of a scope belongs to the session that is ending:
3261
+ // its countdown does not survive it.
3262
+ sharedState.scopeRuntime?.dispose();
3263
+ sharedState.scopeRuntime = null;
2952
3264
  // The scope belongs to the session that is ending.
2953
3265
  requestScopeTracker.reset();
2954
3266
  });
@@ -3155,6 +3467,12 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3155
3467
  // is stale must run before the open question stops the handler.
3156
3468
  await reconcileObsoleteQuestion();
3157
3469
 
3470
+ // The work of an authorized group may have finished: the group
3471
+ // is done when every issue of it is closed. The session stops
3472
+ // again with it: the approval of that group does not authorize
3473
+ // the next one.
3474
+ await sharedState.scopeRuntime?.checkGroupFinished();
3475
+
3158
3476
  // Don't continue if user is waiting for response, and do not
3159
3477
  // continue behind a question that is still open: the work waits
3160
3478
  // for the answer, also when the wait itself is over.
@@ -3264,6 +3582,12 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3264
3582
  jobId: `done-${reason.replace(/\s+/g, "-")}`,
3265
3583
  requirement: message,
3266
3584
  }).catch((e) => logToFile("[Notification]", "ReadyForClient failed:", String(e)));
3585
+
3586
+ // The request of the human is done. The backlog of the
3587
+ // session is not work of it: the exact issues that
3588
+ // could follow are proposed, and only the approved
3589
+ // ids start.
3590
+ await proposeScopeExpansion();
3267
3591
  }
3268
3592
  }
3269
3593
  }
@@ -5909,17 +6233,29 @@ function isOutputLimitResumePromptMessage(message: {
5909
6233
  role?: string;
5910
6234
  content?: unknown;
5911
6235
  }): boolean {
6236
+ // A resume of the harness carries the marker, and the prompt is its
6237
+ // content: it is the same message as before.
6238
+ if (isAutoResumeMessage(message)) {
6239
+ return isOutputLimitResumePromptText(message.content);
6240
+ }
5912
6241
  if (message.role !== "user") {
5913
6242
  return false;
5914
6243
  }
5915
- if (typeof message.content === "string") {
5916
- return message.content === OUTPUT_LIMIT_RESUME_PROMPT;
6244
+ return isOutputLimitResumePromptText(message.content);
6245
+ }
6246
+
6247
+ /**
6248
+ * Does this content carry the prompt of the output limit?
6249
+ */
6250
+ function isOutputLimitResumePromptText(content: unknown): boolean {
6251
+ if (typeof content === "string") {
6252
+ return content === OUTPUT_LIMIT_RESUME_PROMPT;
5917
6253
  }
5918
- if (!Array.isArray(message.content)) {
6254
+ if (!Array.isArray(content)) {
5919
6255
  return false;
5920
6256
  }
5921
6257
  return (
5922
- message.content
6258
+ content
5923
6259
  .filter(
5924
6260
  (part): part is { type: "text"; text: string } =>
5925
6261
  part &&
@@ -7015,6 +7351,44 @@ issue is not authorized work of the current request).
7015
7351
  providerFailureAttemptsInRun = 0;
7016
7352
  });
7017
7353
 
7354
+ /**
7355
+ * The guard of a resume that is consumed too late.
7356
+ *
7357
+ * A resume is queued while the request runs. Pi drains the queue one
7358
+ * message at a time, so a resume can be consumed after the request
7359
+ * finished - and a resume of a request that is complete would send the
7360
+ * agent to the backlog, which is not work of that request.
7361
+ *
7362
+ * The public boundary of Pi is the "context" event: it runs before the
7363
+ * provider is called, and the handler may replace the messages. The
7364
+ * marker of the resume is still there at that point - Pi removes it
7365
+ * later, when it converts the messages for the provider.
7366
+ *
7367
+ * The run is not aborted: other work of the session must go on. Only
7368
+ * the resume itself is neutralized.
7369
+ */
7370
+ pi.on("context", async (event) => {
7371
+ const index = findAutoResumeIndex(event.messages);
7372
+ const details =
7373
+ index === -1 ? undefined : autoResumeDetails(event.messages[index]);
7374
+ // A resume of a cut turn continues a turn that was cut off: it is
7375
+ // unfinished by definition and the guard does not apply.
7376
+ if (index === -1 || details?.scope === "turn") {
7377
+ return { messages: event.messages };
7378
+ }
7379
+ const decision = decideResumeScope({
7380
+ work: await currentRequestWorkState(),
7381
+ reason: details?.reason ?? "auto-resume",
7382
+ });
7383
+ if (decision.action !== "suppress") {
7384
+ return { messages: event.messages };
7385
+ }
7386
+ logToFile("[resume-scope]", `Resume neutralized: ${decision.reason}`);
7387
+ return {
7388
+ messages: neutralizeAutoResume(event.messages, index) as typeof event.messages,
7389
+ };
7390
+ });
7391
+
7018
7392
  pi.on("message_end", async (event, ctx) => {
7019
7393
  // The context of the running extension: the resume checks it before
7020
7394
  // it dispatches, so it does not compete with the user.
@@ -8686,6 +9060,10 @@ issue is not authorized work of the current request).
8686
9060
  "post-compact-output-limit",
8687
9061
  OUTPUT_LIMIT_RESUME_PROMPT,
8688
9062
  event.willRetry ? "steer" : "followUp",
9063
+ // The output limit cut the turn off, so the turn is
9064
+ // unfinished: the guard of a completed request does not
9065
+ // apply to it.
9066
+ { scope: "turn" },
8689
9067
  );
8690
9068
  return;
8691
9069
  }
@@ -8787,7 +9165,18 @@ issue is not authorized work of the current request).
8787
9165
  return;
8788
9166
  }
8789
9167
  }
8790
- pi.sendUserMessage(content, { deliverAs });
9168
+ // The resume is a message of the harness, not a message of the
9169
+ // human: it carries a marker, so the guard can recognize it when
9170
+ // it is consumed after the request finished.
9171
+ pi.sendMessage(
9172
+ buildAutoResumeMessage({
9173
+ content,
9174
+ reason,
9175
+ scope: options.scope ?? "request",
9176
+ nonce: nextResumeNonce(),
9177
+ }),
9178
+ { deliverAs },
9179
+ );
8791
9180
  await nc("ResumeScheduled", {
8792
9181
  requirement: "Session auto-resume",
8793
9182
  // A resume trigger is not a failure. It renders as
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-harness-runtime",
3
- "version": "1.1.507",
3
+ "version": "1.1.508",
4
4
  "description": "[BETA] Codex-style /usage status + autonomous coding harness for pi. Not production ready — expect breaking changes.",
5
5
  "type": "module",
6
6
  "scripts": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/agent-policy",
3
- "version": "1.1.507",
3
+ "version": "1.1.508",
4
4
  "description": "Agent policy runtime for pi-harness - enforces mandatory rule delivery and mutation gating",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/auth",
3
- "version": "1.1.507",
3
+ "version": "1.1.508",
4
4
  "description": "pi-harness-runtime — auth",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/autonomous-runtime",
3
- "version": "1.1.507",
3
+ "version": "1.1.508",
4
4
  "description": "Autonomous Operations Runtime — task inbox, lease management, and worker lifecycle (RFC-0101)",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",