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
package/index.ts CHANGED
@@ -95,6 +95,26 @@ 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
+ NEUTRALIZED_STALE_RESUME_TEXT,
105
+ } from "./harness/auto-resume-marker.ts";
106
+ import {
107
+ ScopeExpansionRuntime,
108
+ type HumanScopeOutcome,
109
+ } from "./harness/scope-expansion-runtime.ts";
110
+ import {
111
+ MAX_SCOPE_CANDIDATES,
112
+ SCOPE_EXPANSION_WINDOW_MS,
113
+ scopeProposalMessage,
114
+ type ScopeCandidate,
115
+ type ScopeDecision,
116
+ type ScopeProposal,
117
+ } from "./harness/scope-expansion.ts";
98
118
  import type { ProviderFailure } from "./harness/provider-failure.ts";
99
119
  import {
100
120
  createProviderRecoveryController,
@@ -193,10 +213,23 @@ import { centralInfo, initCentralLogging, redactText } from "./packages/logging/
193
213
  * Get tasks from bd (beads) for Jev decision context.
194
214
  * Returns { completed, remaining } arrays of task descriptions.
195
215
  */
216
+ /**
217
+ * One issue of the backlog, with the exact id.
218
+ *
219
+ * The exact id is what a proposal names. A title is not an identity: two
220
+ * issues can carry the same title, and only the id tells them apart.
221
+ */
222
+ interface BacklogIssue {
223
+ id: string;
224
+ title: string;
225
+ status?: string;
226
+ }
227
+
196
228
  async function getTaskContext(): Promise<{
197
229
  completed: string[];
198
230
  remaining: string[];
199
231
  total: number;
232
+ issues: BacklogIssue[];
200
233
  }> {
201
234
  try {
202
235
  const { execSync } = await import("node:child_process");
@@ -205,10 +238,15 @@ async function getTaskContext(): Promise<{
205
238
  encoding: "utf8",
206
239
  timeout: 5000,
207
240
  });
208
- const tasks = JSON.parse(output) as Array<{ title?: string; status?: string }>;
241
+ const tasks = JSON.parse(output) as Array<{
242
+ id?: string;
243
+ title?: string;
244
+ status?: string;
245
+ }>;
209
246
 
210
247
  const completed: string[] = [];
211
248
  const remaining: string[] = [];
249
+ const issues: BacklogIssue[] = [];
212
250
 
213
251
  for (const task of tasks ?? []) {
214
252
  if (!task.title) continue;
@@ -216,6 +254,11 @@ async function getTaskContext(): Promise<{
216
254
  completed.push(task.title);
217
255
  } else {
218
256
  remaining.push(task.title);
257
+ // An issue without an id cannot be proposed: a proposal
258
+ // names exact ids.
259
+ if (typeof task.id === "string" && task.id) {
260
+ issues.push({ id: task.id, title: task.title, status: task.status });
261
+ }
219
262
  }
220
263
  }
221
264
 
@@ -223,10 +266,11 @@ async function getTaskContext(): Promise<{
223
266
  completed,
224
267
  remaining,
225
268
  total: completed.length + remaining.length,
269
+ issues,
226
270
  };
227
271
  } catch {
228
272
  // bd not available or error - return empty context
229
- return { completed: [], remaining: [], total: 0 };
273
+ return { completed: [], remaining: [], total: 0, issues: [] };
230
274
  }
231
275
  }
232
276
 
@@ -629,6 +673,17 @@ const sharedState = {
629
673
  // The state of the work of the request that is running. The automatic
630
674
  // resume reads it to know whether the work of the request remains.
631
675
  workContext: null as unknown,
676
+ // The runtime of the scope expansion: the backlog that could follow a
677
+ // finished request is proposed, and only the approved issues start.
678
+ scopeRuntime: null as ScopeExpansionRuntime | null,
679
+ /**
680
+ * The request the backlog was proposed for.
681
+ *
682
+ * The proposal of a request happens once: the generation of the request
683
+ * is its identity, and a second proposal of the same request would ask
684
+ * the human twice about the same backlog.
685
+ */
686
+ scopeProposedFor: null as number | null,
632
687
  };
633
688
 
634
689
  /**
@@ -639,6 +694,20 @@ const sharedState = {
639
694
  */
640
695
  let suppressedResumeReported = false;
641
696
 
697
+ /** The number of the resumes that the harness queued in this session. */
698
+ let resumeNonceCounter = 0;
699
+
700
+ /**
701
+ * A nonce that tells one resume from another.
702
+ *
703
+ * The nonce is part of the marker of the resume, so a log line names the
704
+ * exact resume that was queued.
705
+ */
706
+ function nextResumeNonce(): string {
707
+ resumeNonceCounter += 1;
708
+ return `${Date.now().toString(36)}-${resumeNonceCounter}`;
709
+ }
710
+
642
711
  /**
643
712
  * Report that an automatic resume was suppressed.
644
713
  *
@@ -739,6 +808,75 @@ function beginHumanRequest(): void {
739
808
  suppressedResumeReported = false;
740
809
  }
741
810
 
811
+ /**
812
+ * Did a notification reach a channel?
813
+ *
814
+ * A skipped channel - a disabled one - is not a delivery: the human was not
815
+ * told, and work that the human was not told about must not start.
816
+ */
817
+ function deliveryOf(results: unknown): { delivered: boolean; failures: string[] } {
818
+ if (!Array.isArray(results)) {
819
+ return { delivered: false, failures: ["the notification returned no result"] };
820
+ }
821
+ const rows = results as Array<{
822
+ success?: boolean;
823
+ channel?: string;
824
+ error?: string;
825
+ skipped?: boolean;
826
+ }>;
827
+ const reached = rows.filter((row) => row.success && !row.skipped);
828
+ const failures = rows
829
+ .filter((row) => !row.success || row.skipped)
830
+ .map((row) =>
831
+ row.skipped
832
+ ? `${row.channel ?? "channel"}: skipped`
833
+ : `${row.channel ?? "channel"}: ${row.error ?? "not delivered"}`,
834
+ );
835
+ if (reached.length === 0 && failures.length === 0) {
836
+ // No channel was reached and no channel reported why: the result
837
+ // names no channel, and the log has to say so.
838
+ failures.push("no channel was reached");
839
+ }
840
+ return { delivered: reached.length > 0, failures };
841
+ }
842
+
843
+ /**
844
+ * Propose the backlog that could follow a finished request.
845
+ *
846
+ * The proposal names exact ids, and the decision of the human - or of Jev,
847
+ * when the five minutes are over without an answer - decides what starts.
848
+ * Nothing of the backlog starts without that decision.
849
+ */
850
+ async function proposeScopeExpansion(): Promise<void> {
851
+ const runtime = sharedState.scopeRuntime;
852
+ if (!runtime) return;
853
+ // One proposal waits for an answer: a second one would ask the same
854
+ // human twice about the same backlog.
855
+ if (runtime.open.length > 0) return;
856
+ const generation = requestScopeTracker.generation;
857
+ // The proposal of a request happens once. The generation of the request
858
+ // is its identity: a request that finished twice does not ask twice.
859
+ if (sharedState.scopeProposedFor === generation) return;
860
+ const context = await getTaskContext().catch(() => null);
861
+ if (!context || context.issues.length === 0) return;
862
+ const candidates: ScopeCandidate[] = context.issues
863
+ .slice(0, MAX_SCOPE_CANDIDATES)
864
+ .map((issue) => ({ id: issue.id, title: issue.title }));
865
+ const proposal = await runtime.propose({
866
+ requestId: `request-${generation}`,
867
+ workspace: _piSessionCwd || process.cwd(),
868
+ generation,
869
+ candidates,
870
+ scope: `work on ${candidates.length} issue(s) of the backlog of the session`,
871
+ validation: "the tests of the repository and the closing of every named issue",
872
+ risks: ["the work was not asked for"],
873
+ choices: ["run the named issues", "keep the backlog closed"],
874
+ });
875
+ if (proposal) {
876
+ sharedState.scopeProposedFor = generation;
877
+ }
878
+ }
879
+
742
880
  /**
743
881
  * Apply an approval decision from a channel to the pending question.
744
882
  *
@@ -758,6 +896,42 @@ function applyChannelApproval(
758
896
  return false;
759
897
  }
760
898
 
899
+ // A question of a scope proposal is not a question of the work of the
900
+ // request: it asks whether the backlog may follow. The answer decides
901
+ // the proposal, and the work of the request stays what it was.
902
+ //
903
+ // The proposal is recognized before the shared question is resolved: an
904
+ // answer of a proposal must not clear the wait of the request and must
905
+ // not steer an answer into the conversation.
906
+ const scopeProposal = sharedState.scopeRuntime?.proposalForQuestion(requestId);
907
+ if (scopeProposal) {
908
+ const outcome: HumanScopeOutcome = action === "approve" ? "approve" : "reject";
909
+ const scopeResult = controller.applyApproval(action, requestId, channel, {
910
+ notifyUser: false,
911
+ });
912
+ if (!scopeResult?.applied) {
913
+ logToFile(
914
+ "[Approval]",
915
+ `Stale or duplicate ${channel} click for ${requestId}: ${scopeResult?.reason ?? "ignored"}`,
916
+ );
917
+ return false;
918
+ }
919
+ logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
920
+ logQuestionTransition(requestId, "answered", `${channel}:${action}`);
921
+ void sharedState.scopeRuntime
922
+ ?.answerByQuestion(requestId, outcome, `${channel}:${action}`)
923
+ .then((executed) => {
924
+ logToFile(
925
+ "[scope-expansion]",
926
+ `The proposal ${scopeProposal.id} was answered (${outcome}): started=${executed.started}`,
927
+ );
928
+ })
929
+ .catch((error) => {
930
+ logToFile("[scope-expansion]", "The answer of the proposal failed:", String(error));
931
+ });
932
+ return true;
933
+ }
934
+
761
935
  const result = controller.applyApproval(action, requestId, channel);
762
936
  if (!result?.applied) {
763
937
  logToFile(
@@ -2884,8 +3058,196 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2884
3058
  let validationLedger: import("./packages/jev-judge/dist/validation-ledger.js").ValidationLedger | null = null;
2885
3059
 
2886
3060
  // Create controller on session_start with proper dispatch callback
3061
+ /**
3062
+ * The runtime of the scope expansion.
3063
+ *
3064
+ * The backlog of the session is not work of the request that just
3065
+ * finished. When the request is done, the runtime proposes the exact
3066
+ * issues that could follow, the human decides - or Jev decides when
3067
+ * the five minutes are over - and only the approved ids start. The
3068
+ * decision is delivered before the work starts, and a decision that
3069
+ * reaches nobody leaves the work stopped.
3070
+ */
3071
+ function createScopeExpansionRuntime(): ScopeExpansionRuntime {
3072
+ // The runtime owns its proposals: a decision that is in flight
3073
+ // when the session ends must not start work in another session.
3074
+ let runtime: ScopeExpansionRuntime | undefined;
3075
+ runtime = new ScopeExpansionRuntime({
3076
+ now: () => Date.now(),
3077
+ deliver: async (text, meta) => {
3078
+ const center = _nc?.center as NcCenter | undefined;
3079
+ if (!center) {
3080
+ return { delivered: false, failures: ["no notification center"] };
3081
+ }
3082
+ const proposal = runtime?.get(meta.id);
3083
+ try {
3084
+ if (meta.kind === "proposal") {
3085
+ const results = await center.notifyWithApproval(
3086
+ "ScopeProposal" as never,
3087
+ {
3088
+ jobId: meta.id,
3089
+ requirement: text,
3090
+ questionId: meta.questionId,
3091
+ questionKind: "approval",
3092
+ scopeIds: proposal?.proposedIds,
3093
+ scopeDeadline: proposal
3094
+ ? new Date(proposal.deadlineAt).toISOString()
3095
+ : undefined,
3096
+ } as never,
3097
+ { approveLabel: "Run these", rejectLabel: "Keep it closed" },
3098
+ );
3099
+ return deliveryOf(results);
3100
+ }
3101
+ const results = await center.notify("ScopeDecision" as never, {
3102
+ jobId: meta.id,
3103
+ requirement: text,
3104
+ scopeIds: proposal?.proposedIds,
3105
+ } as never);
3106
+ return deliveryOf(results);
3107
+ } catch (error) {
3108
+ return { delivered: false, failures: [String(error)] };
3109
+ }
3110
+ },
3111
+ judge: async (proposal) => {
3112
+ const judge = new mod.AutoContinueJudge({
3113
+ providers: jevProviders,
3114
+ proceedThreshold: 0.7,
3115
+ maxWaitMinutes: 30,
3116
+ });
3117
+ const waitedMinutes = Math.max(
3118
+ 0,
3119
+ Math.round((Date.now() - proposal.createdAt) / 60_000),
3120
+ );
3121
+ const question = scopeProposalMessage(proposal);
3122
+ const decision = await judge.decide({
3123
+ completedTasks: [],
3124
+ remainingTasks: proposal.proposedIds,
3125
+ totalTasks: proposal.proposedIds.length,
3126
+ waitTimeMinutes: waitedMinutes,
3127
+ userResponded: false,
3128
+ sessionStartTime: new Date(proposal.createdAt),
3129
+ questionAskedAt: new Date(proposal.createdAt),
3130
+ context: {
3131
+ question: {
3132
+ requestId: `scope-question-${proposal.id}`,
3133
+ text: question,
3134
+ kind: "approval",
3135
+ askType: "approval",
3136
+ alternatives: proposal.choices,
3137
+ contextText: question,
3138
+ proposedAction: proposal.scope,
3139
+ consequence: "the named issues become work of this session",
3140
+ requiresExplicitAuthorization: false,
3141
+ destructive: false,
3142
+ external: false,
3143
+ reversible: true,
3144
+ },
3145
+ currentTask: proposal.scope,
3146
+ totalTasks: proposal.proposedIds.length,
3147
+ nextTasks: proposal.proposedIds,
3148
+ waitedMinutes,
3149
+ deadlineMinutes: Math.round(SCOPE_EXPANSION_WINDOW_MS / 60_000),
3150
+ },
3151
+ });
3152
+ const outcome: ScopeDecision["outcome"] =
3153
+ decision.outcome === "approve" || decision.outcome === "proceed_with_caution"
3154
+ ? "approve"
3155
+ : decision.outcome === "reject"
3156
+ ? "reject"
3157
+ : "wait";
3158
+ return {
3159
+ outcome,
3160
+ selectedIds: outcome === "approve" ? [...proposal.proposedIds] : [],
3161
+ reasoning: decision.reasoning,
3162
+ source: "jev",
3163
+ failed: decision.evaluationError !== undefined,
3164
+ };
3165
+ },
3166
+ dispatch: (proposal, ids) => {
3167
+ // The session owns the decision: a decision that is still
3168
+ // in flight when the session ends must not start the
3169
+ // work of the backlog in another session.
3170
+ if (sharedState.scopeRuntime !== runtime) {
3171
+ logToFile(
3172
+ "[scope-expansion]",
3173
+ `The proposal ${proposal.id} is not dispatched: the session changed.`,
3174
+ );
3175
+ return;
3176
+ }
3177
+ // The approval starts new work: it begins a new scope, so
3178
+ // the todos of the finished request stay its history.
3179
+ beginHumanRequest();
3180
+ const lines = ids.map((id) => `- ${id}`).join("\n");
3181
+ const message = [
3182
+ "The human approved the following issues of the backlog.",
3183
+ "Work on exactly these ids and stop when they are done:",
3184
+ lines,
3185
+ ].join("\n");
3186
+ void (async () => {
3187
+ try {
3188
+ await pi.sendUserMessage(message, { deliverAs: "steer" });
3189
+ } catch (error) {
3190
+ logToFile(
3191
+ "[scope-expansion]",
3192
+ `The dispatch of the proposal ${proposal.id} failed:`,
3193
+ String(error),
3194
+ );
3195
+ }
3196
+ })();
3197
+ },
3198
+ registerQuestion: (proposal) => {
3199
+ const question = pqController.createQuestion({
3200
+ text: scopeProposalMessage(proposal),
3201
+ sessionId: _sessionId,
3202
+ workspacePath: _piSessionCwd || "/",
3203
+ jobId: proposal.id,
3204
+ kind: "approval",
3205
+ askType: "approval",
3206
+ alternatives: proposal.choices,
3207
+ contextText: scopeProposalMessage(proposal),
3208
+ risk: {
3209
+ requiresExplicitAuthorization: false,
3210
+ destructive: false,
3211
+ reversible: true,
3212
+ external: false,
3213
+ },
3214
+ relevance:
3215
+ // The question is asked after the work of the request
3216
+ // is done: it is not obsolete, and it does not wait
3217
+ // for an automatic decision of the request.
3218
+ "final-request",
3219
+ });
3220
+ return question.requestId;
3221
+ },
3222
+ cancelQuestion: (questionId) => {
3223
+ pqController.expireByTimeout?.(questionId, "the proposal was not delivered");
3224
+ },
3225
+ latestHumanDecision: (proposal) => {
3226
+ const questionId = sharedState.scopeRuntime?.questionIdFor(proposal.id);
3227
+ if (!questionId) return undefined;
3228
+ const resolution = pqController.getQuestion(questionId)?.resolution;
3229
+ if (resolution === "yes") return "approve";
3230
+ if (resolution === "no") return "reject";
3231
+ return undefined;
3232
+ },
3233
+ groupFinished: async (_proposal: ScopeProposal, ids) => {
3234
+ const context = await getTaskContext().catch(() => null);
3235
+ if (!context) return false;
3236
+ const open = new Set(context.issues.map((issue) => issue.id));
3237
+ return ids.every((id) => !open.has(id));
3238
+ },
3239
+ log: (message) => logToFile("[scope-expansion]", message),
3240
+ });
3241
+ return runtime;
3242
+ }
3243
+
2887
3244
  pi.on("session_start", async (_event, ctx) => {
2888
3245
  try {
3246
+ // The runtime of the scope expansion belongs to the session:
3247
+ // a session that starts has no open proposal, and a session
3248
+ // that ends leaves none behind.
3249
+ sharedState.scopeRuntime?.dispose();
3250
+ sharedState.scopeRuntime = createScopeExpansionRuntime();
2889
3251
  const { TodoContinuationController } = await import("./packages/jev-judge/dist/continuation-controller.js");
2890
3252
  const { ValidationLedger } = await import("./packages/jev-judge/dist/validation-ledger.js");
2891
3253
  // The ledger records which validation tier ran. The controller
@@ -2949,6 +3311,10 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
2949
3311
  todoContinuationHandle = null;
2950
3312
  sharedState.todoContinuationController = null;
2951
3313
  sharedState.validationLedger = null;
3314
+ // The proposal of a scope belongs to the session that is ending:
3315
+ // its countdown does not survive it.
3316
+ sharedState.scopeRuntime?.dispose();
3317
+ sharedState.scopeRuntime = null;
2952
3318
  // The scope belongs to the session that is ending.
2953
3319
  requestScopeTracker.reset();
2954
3320
  });
@@ -3155,6 +3521,12 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3155
3521
  // is stale must run before the open question stops the handler.
3156
3522
  await reconcileObsoleteQuestion();
3157
3523
 
3524
+ // The work of an authorized group may have finished: the group
3525
+ // is done when every issue of it is closed. The session stops
3526
+ // again with it: the approval of that group does not authorize
3527
+ // the next one.
3528
+ await sharedState.scopeRuntime?.checkGroupFinished();
3529
+
3158
3530
  // Don't continue if user is waiting for response, and do not
3159
3531
  // continue behind a question that is still open: the work waits
3160
3532
  // for the answer, also when the wait itself is over.
@@ -3244,26 +3616,36 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3244
3616
  // Deduplication: only notify once per work generation
3245
3617
  // Use a static flag for this session's settled cycle
3246
3618
  const completionKey = `done-${reason}`;
3247
- if (_completedNotifiedFor === completionKey) {
3619
+ const alreadyNotified = _completedNotifiedFor === completionKey;
3620
+ if (alreadyNotified) {
3248
3621
  logToFile("[auto-continue]", "Completion already notified for:", reason);
3249
- return;
3622
+ } else {
3623
+ _completedNotifiedFor = completionKey;
3624
+
3625
+ // Get full todo list for notification
3626
+ const todoList = snapshot.items
3627
+ .map((item) => {
3628
+ const status = item.status === "completed" ? "[DONE]" : "[PENDING]";
3629
+ const subject = item.subject.length > 50 ? item.subject.slice(0, 47) + "..." : item.subject;
3630
+ return `${status} ${subject}`;
3631
+ })
3632
+ .join("\n");
3633
+ const message = todoList || "All tasks completed";
3634
+ // Notify user that all work is complete with todo list
3635
+ _nc?.notify("ReadyForClient", {
3636
+ jobId: `done-${reason.replace(/\s+/g, "-")}`,
3637
+ requirement: message,
3638
+ }).catch((e) => logToFile("[Notification]", "ReadyForClient failed:", String(e)));
3250
3639
  }
3251
- _completedNotifiedFor = completionKey;
3252
-
3253
- // Get full todo list for notification
3254
- const todoList = snapshot.items
3255
- .map((item) => {
3256
- const status = item.status === "completed" ? "[DONE]" : "[PENDING]";
3257
- const subject = item.subject.length > 50 ? item.subject.slice(0, 47) + "..." : item.subject;
3258
- return `${status} ${subject}`;
3259
- })
3260
- .join("\n");
3261
- const message = todoList || "All tasks completed";
3262
- // Notify user that all work is complete with todo list
3263
- _nc?.notify("ReadyForClient", {
3264
- jobId: `done-${reason.replace(/\s+/g, "-")}`,
3265
- requirement: message,
3266
- }).catch((e) => logToFile("[Notification]", "ReadyForClient failed:", String(e)));
3640
+
3641
+ // The request of the human is done. The backlog of the
3642
+ // session is not work of it: the exact issues that
3643
+ // could follow are proposed, and only the approved
3644
+ // ids start. The proposal does not ride on the
3645
+ // notification of the completion: a request that
3646
+ // finished again is a new request, and it proposes
3647
+ // its own backlog.
3648
+ await proposeScopeExpansion();
3267
3649
  }
3268
3650
  }
3269
3651
  }
@@ -5909,17 +6291,29 @@ function isOutputLimitResumePromptMessage(message: {
5909
6291
  role?: string;
5910
6292
  content?: unknown;
5911
6293
  }): boolean {
6294
+ // A resume of the harness carries the marker, and the prompt is its
6295
+ // content: it is the same message as before.
6296
+ if (isAutoResumeMessage(message)) {
6297
+ return isOutputLimitResumePromptText(message.content);
6298
+ }
5912
6299
  if (message.role !== "user") {
5913
6300
  return false;
5914
6301
  }
5915
- if (typeof message.content === "string") {
5916
- return message.content === OUTPUT_LIMIT_RESUME_PROMPT;
6302
+ return isOutputLimitResumePromptText(message.content);
6303
+ }
6304
+
6305
+ /**
6306
+ * Does this content carry the prompt of the output limit?
6307
+ */
6308
+ function isOutputLimitResumePromptText(content: unknown): boolean {
6309
+ if (typeof content === "string") {
6310
+ return content === OUTPUT_LIMIT_RESUME_PROMPT;
5917
6311
  }
5918
- if (!Array.isArray(message.content)) {
6312
+ if (!Array.isArray(content)) {
5919
6313
  return false;
5920
6314
  }
5921
6315
  return (
5922
- message.content
6316
+ content
5923
6317
  .filter(
5924
6318
  (part): part is { type: "text"; text: string } =>
5925
6319
  part &&
@@ -7015,6 +7409,69 @@ issue is not authorized work of the current request).
7015
7409
  providerFailureAttemptsInRun = 0;
7016
7410
  });
7017
7411
 
7412
+ /**
7413
+ * The guard of a resume that is consumed too late.
7414
+ *
7415
+ * A resume is queued while the request runs. Pi drains the queue one
7416
+ * message at a time, so a resume can be consumed after the request
7417
+ * finished - and a resume of a request that is complete would send the
7418
+ * agent to the backlog, which is not work of that request.
7419
+ *
7420
+ * The public boundary of Pi is the "context" event: it runs before the
7421
+ * provider is called, and the handler may replace the messages. The
7422
+ * marker of the resume is still there at that point - Pi removes it
7423
+ * later, when it converts the messages for the provider.
7424
+ *
7425
+ * The run is not aborted: other work of the session must go on. Only
7426
+ * the resume itself is neutralized.
7427
+ */
7428
+ pi.on("context", async (event) => {
7429
+ const index = findAutoResumeIndex(event.messages);
7430
+ const details =
7431
+ index === -1 ? undefined : autoResumeDetails(event.messages[index]);
7432
+ // A resume of a cut turn continues a turn that was cut off: it is
7433
+ // unfinished by definition and the guard does not apply. A resume
7434
+ // whose scope cannot be read is not known to be a resume of the
7435
+ // request, and the guard does not apply either.
7436
+ if (index === -1 || details?.scope !== "request") {
7437
+ return { messages: event.messages };
7438
+ }
7439
+ // The resume belongs to a request. When the human replaced that
7440
+ // request, the resume is stale: it must not continue the old work
7441
+ // inside the new request.
7442
+ const generation = requestScopeTracker.generation;
7443
+ if (
7444
+ details?.requestGeneration !== undefined &&
7445
+ details.requestGeneration !== generation
7446
+ ) {
7447
+ const report = `The automatic resume of the request ${details.requestGeneration} was replaced by a newer request.`;
7448
+ logToFile("[resume-scope]", report);
7449
+ reportSuppressedResume(report);
7450
+ return {
7451
+ messages: neutralizeAutoResume(
7452
+ event.messages,
7453
+ index,
7454
+ NEUTRALIZED_STALE_RESUME_TEXT,
7455
+ ) as typeof event.messages,
7456
+ };
7457
+ }
7458
+ const decision = decideResumeScope({
7459
+ work: await currentRequestWorkState(),
7460
+ reason: details?.reason ?? "auto-resume",
7461
+ });
7462
+ if (decision.action !== "suppress") {
7463
+ return { messages: event.messages };
7464
+ }
7465
+ logToFile(
7466
+ "[resume-scope]",
7467
+ `Resume neutralized: ${decision.reason} (${details?.nonce || "no nonce"})`,
7468
+ );
7469
+ reportSuppressedResume(decision.report);
7470
+ return {
7471
+ messages: neutralizeAutoResume(event.messages, index) as typeof event.messages,
7472
+ };
7473
+ });
7474
+
7018
7475
  pi.on("message_end", async (event, ctx) => {
7019
7476
  // The context of the running extension: the resume checks it before
7020
7477
  // it dispatches, so it does not compete with the user.
@@ -8686,6 +9143,10 @@ issue is not authorized work of the current request).
8686
9143
  "post-compact-output-limit",
8687
9144
  OUTPUT_LIMIT_RESUME_PROMPT,
8688
9145
  event.willRetry ? "steer" : "followUp",
9146
+ // The output limit cut the turn off, so the turn is
9147
+ // unfinished: the guard of a completed request does not
9148
+ // apply to it.
9149
+ { scope: "turn" },
8689
9150
  );
8690
9151
  return;
8691
9152
  }
@@ -8787,7 +9248,23 @@ issue is not authorized work of the current request).
8787
9248
  return;
8788
9249
  }
8789
9250
  }
8790
- pi.sendUserMessage(content, { deliverAs });
9251
+ // The resume is a message of the harness, not a message of the
9252
+ // human: it carries a marker, so the guard can recognize it when
9253
+ // it is consumed after the request finished. The marker names the
9254
+ // request the resume belongs to.
9255
+ pi.sendMessage(
9256
+ buildAutoResumeMessage({
9257
+ content,
9258
+ reason,
9259
+ scope: options.scope ?? "request",
9260
+ nonce: nextResumeNonce(),
9261
+ requestGeneration: requestScopeTracker.generation,
9262
+ }),
9263
+ // The resume continues the work on its own: without a turn of
9264
+ // its own the message would wait for the next prompt of the
9265
+ // human, and the recovery would never happen.
9266
+ { deliverAs, triggerTurn: true },
9267
+ );
8791
9268
  await nc("ResumeScheduled", {
8792
9269
  requirement: "Session auto-resume",
8793
9270
  // 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.509",
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.509",
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.509",
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.509",
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",