pi-harness-runtime 1.1.508 → 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 (61) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/harness/auto-resume-marker.ts +55 -13
  3. package/harness/scope-expansion-runtime.ts +142 -15
  4. package/harness/scope-expansion.ts +150 -35
  5. package/index.ts +130 -42
  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/notification-center.d.ts +8 -4
  28. package/packages/notification/dist/notification-center.d.ts.map +1 -1
  29. package/packages/notification/dist/notification-center.js +18 -9
  30. package/packages/notification/dist/notification-center.js.map +1 -1
  31. package/packages/notification/dist/notification-policy.d.ts.map +1 -1
  32. package/packages/notification/dist/notification-policy.js +3 -0
  33. package/packages/notification/dist/notification-policy.js.map +1 -1
  34. package/packages/notification/dist/pending-question.d.ts +20 -1
  35. package/packages/notification/dist/pending-question.d.ts.map +1 -1
  36. package/packages/notification/dist/pending-question.js +9 -3
  37. package/packages/notification/dist/pending-question.js.map +1 -1
  38. package/packages/notification/package.json +1 -1
  39. package/packages/notification/src/notification-center.ts +18 -9
  40. package/packages/notification/src/notification-policy.ts +3 -0
  41. package/packages/notification/src/pending-question.ts +28 -2
  42. package/packages/paperclip-integration/package.json +1 -1
  43. package/packages/performance-optimizer/package.json +1 -1
  44. package/packages/privilege-broker/package.json +1 -1
  45. package/packages/prompt-compiler/package.json +1 -1
  46. package/packages/providers/package.json +1 -1
  47. package/packages/qdrant-skills/package.json +1 -1
  48. package/packages/quota-manager/package.json +1 -1
  49. package/packages/relay/package.json +1 -1
  50. package/packages/skill-mcp-client/package.json +1 -1
  51. package/packages/skills/package.json +1 -1
  52. package/packages/todo-bd-sync/package.json +1 -1
  53. package/packages/token-estimation/package.json +1 -1
  54. package/packages/tooling-preference/package.json +1 -1
  55. package/packages/trajectory/package.json +1 -1
  56. package/packages/tui/package.json +1 -1
  57. package/packages/two-phase-review/package.json +1 -1
  58. package/packages/types/package.json +1 -1
  59. package/packages/webmcp-tester/package.json +1 -1
  60. package/packages/wiki/package.json +1 -1
  61. package/packages/write-review/package.json +1 -1
@@ -105,6 +105,8 @@ export interface CreateScopeProposalInput {
105
105
  scope: string;
106
106
  validation: string;
107
107
  risks?: string[];
108
+ /** The choices the human has. */
109
+ choices?: string[];
108
110
  now: number;
109
111
  }
110
112
 
@@ -113,16 +115,22 @@ export interface CreateScopeProposalInput {
113
115
  *
114
116
  * The proposal names a bounded subset of the candidates: a candidate that
115
117
  * is not named is not proposed, and an id that is not a candidate is
116
- * refused. The deadline is absolute, so every reader measures the same
117
- * moment.
118
+ * refused. The bound applies to the proposed ids, and an id is checked
119
+ * against the whole list of the candidates: a bound that drops a known id
120
+ * would refuse a proposal of ids that the caller knew.
121
+ *
122
+ * The deadline is absolute, so every reader measures the same moment.
118
123
  */
119
124
  export function createScopeProposal(input: CreateScopeProposalInput): ScopeProposal {
120
- const candidates = input.candidates.slice(0, MAX_SCOPE_CANDIDATES);
121
- const known = new Set(candidates.map((candidate) => candidate.id));
122
- const proposedIds = input.proposedIds.filter((id) => known.has(id));
125
+ const known = new Set(input.candidates.map((candidate) => candidate.id));
126
+ const proposedIds = input.proposedIds
127
+ .filter((id) => known.has(id))
128
+ .slice(0, MAX_SCOPE_CANDIDATES);
123
129
  if (proposedIds.length === 0) {
124
130
  throw new Error("a scope proposal needs at least one candidate id");
125
131
  }
132
+ const proposed = new Set(proposedIds);
133
+ const candidates = input.candidates.filter((candidate) => proposed.has(candidate.id));
126
134
  return {
127
135
  id: input.id,
128
136
  sessionId: input.sessionId,
@@ -134,7 +142,10 @@ export function createScopeProposal(input: CreateScopeProposalInput): ScopePropo
134
142
  scope: input.scope,
135
143
  validation: input.validation,
136
144
  risks: input.risks ?? [],
137
- choices: ["approve the proposed subset", "decline", "revise the proposal"],
145
+ choices:
146
+ input.choices && input.choices.length > 0
147
+ ? input.choices
148
+ : ["approve the proposed subset", "decline", "revise the proposal"],
138
149
  createdAt: input.now,
139
150
  deadlineAt: input.now + SCOPE_EXPANSION_WINDOW_MS,
140
151
  state: "proposed",
@@ -162,7 +173,7 @@ export function scopeProposalMessage(proposal: ScopeProposal): string {
162
173
  lines.push(
163
174
  `Choices: ${proposal.choices.join(" / ")}.`,
164
175
  `Deadline: ${new Date(proposal.deadlineAt).toISOString()}.`,
165
- `If unanswered for 5 minutes, Jev may decide this proposal under your policy.`,
176
+ `If unanswered for ${Math.round(SCOPE_EXPANSION_WINDOW_MS / 60_000)} minutes, Jev may decide this proposal under your policy.`,
166
177
  );
167
178
  return lines.join("\n");
168
179
  }
@@ -170,18 +181,22 @@ export function scopeProposalMessage(proposal: ScopeProposal): string {
170
181
  /**
171
182
  * The message of the decision.
172
183
  *
173
- * The decision names what was decided, what it means, and whether the work
174
- * starts or the session stays stopped.
184
+ * The decision names the proposal, what was decided, the scope that is
185
+ * really authorized, and whether the work starts or the session stays
186
+ * stopped.
175
187
  */
176
188
  export function scopeDecisionMessage(
177
189
  proposal: ScopeProposal,
178
190
  decision: ScopeDecision,
179
191
  action: "starting the selected work" | "remaining stopped",
192
+ authorizedIds?: readonly string[],
180
193
  ): string {
181
- const who = decision.source === "jev" ? "Jev decision after 5 minutes" : "Your decision";
194
+ const who = decision.source === "jev" ? "Jev decision after the window" : "Your decision";
195
+ const ids = authorizedIds ?? decision.selectedIds;
182
196
  return [
183
197
  `${who}: ${decision.outcome}.`,
184
- `Scope: ${decision.selectedIds.length > 0 ? decision.selectedIds.join(", ") : "none"}.`,
198
+ `Proposal: ${proposal.id}.`,
199
+ `Scope: ${ids.length > 0 ? ids.join(", ") : "none"}.`,
185
200
  `Reason: ${decision.reasoning}`,
186
201
  `Action: ${action}.`,
187
202
  `Proposed: ${proposal.scope}`,
@@ -256,7 +271,16 @@ export class ScopeExpansionController {
256
271
  private generationCounter = 0;
257
272
  private answered = new Set<string>();
258
273
  private evaluated = new Set<string>();
259
- private closedGeneration: number | null = null;
274
+ /** The proposals whose decision is being applied right now. */
275
+ private applying = new Set<string>();
276
+ /**
277
+ * The generations that are closed.
278
+ *
279
+ * Every closed generation is remembered: the approval of one group is
280
+ * not the approval of the next one, and that holds for every group
281
+ * that finished, not only for the last one.
282
+ */
283
+ private closedGenerations = new Set<number>();
260
284
 
261
285
  constructor(deps: ScopeExpansionDeps) {
262
286
  this.deps = deps;
@@ -287,7 +311,7 @@ export class ScopeExpansionController {
287
311
  * approval of one group is not the approval of the next one.
288
312
  */
289
313
  register(proposal: ScopeProposal): boolean {
290
- if (this.closedGeneration === proposal.generation) {
314
+ if (this.closedGenerations.has(proposal.generation)) {
291
315
  this.deps.log?.(
292
316
  `The scope proposal ${proposal.id} is refused: the generation ${proposal.generation} is closed.`,
293
317
  );
@@ -361,6 +385,20 @@ export class ScopeExpansionController {
361
385
  failed: true,
362
386
  };
363
387
  }
388
+ // A failed evaluation is not a decision: it authorizes nothing, and
389
+ // it is a wait that ends the attempts for this proposal.
390
+ if (decision.failed === true) {
391
+ decision = {
392
+ outcome: "wait",
393
+ selectedIds: [],
394
+ reasoning:
395
+ decision.reasoning.length > 0
396
+ ? decision.reasoning
397
+ : "the evaluation failed",
398
+ source: "jev",
399
+ failed: true,
400
+ };
401
+ }
364
402
  // The human answered while the evaluation was running: the answer
365
403
  // wins.
366
404
  if (this.answered.has(id)) {
@@ -381,6 +419,32 @@ export class ScopeExpansionController {
381
419
  * that the human was informed and start anyway.
382
420
  */
383
421
  async applyDecision(id: string): Promise<{ started: boolean; reason?: string }> {
422
+ // The decision of a proposal is applied once. The answer of the
423
+ // human that arrives while the decision is on its way starts a
424
+ // second application of the same proposal, and the group must not
425
+ // start twice.
426
+ if (this.applying.has(id)) {
427
+ return {
428
+ started: false,
429
+ reason: "the decision of the proposal is being applied",
430
+ };
431
+ }
432
+ this.applying.add(id);
433
+ try {
434
+ return await this.applyDecisionOnce(id);
435
+ } finally {
436
+ this.applying.delete(id);
437
+ }
438
+ }
439
+
440
+ /**
441
+ * Apply the decision of a proposal.
442
+ *
443
+ * The decision is applied once: the caller holds the lock.
444
+ */
445
+ private async applyDecisionOnce(
446
+ id: string,
447
+ ): Promise<{ started: boolean; reason?: string }> {
384
448
  const proposal = this.proposals.get(id);
385
449
  if (!proposal) return { started: false, reason: "unknown proposal" };
386
450
  const decision = proposal.decision;
@@ -391,8 +455,14 @@ export class ScopeExpansionController {
391
455
  // The human decides. The answer is read before the delivery, so the
392
456
  // delivered message and the executed work agree.
393
457
  let effective = decision;
458
+ const recorded = this.humanDecision(proposal);
394
459
  const latestBefore = this.deps.latestHumanDecision?.(proposal);
395
- if (latestBefore === "reject") {
460
+ if (recorded) {
461
+ // The first answer of the human wins: the answer that the
462
+ // controller recorded is stronger than a store that reports the
463
+ // last click.
464
+ effective = recorded;
465
+ } else if (latestBefore === "reject") {
396
466
  effective = {
397
467
  outcome: "reject",
398
468
  selectedIds: [],
@@ -412,10 +482,13 @@ export class ScopeExpansionController {
412
482
  const scope = authorizedScope(proposal, effective);
413
483
  const action: "starting the selected work" | "remaining stopped" =
414
484
  scope.ids.length > 0 ? "starting the selected work" : "remaining stopped";
415
- const delivery = await this.deps.deliver(scopeDecisionMessage(proposal, effective, action), {
416
- id: proposal.id,
417
- kind: "decision",
418
- });
485
+ const delivery = await this.deps.deliver(
486
+ scopeDecisionMessage(proposal, effective, action, scope.ids),
487
+ {
488
+ id: proposal.id,
489
+ kind: "decision",
490
+ },
491
+ );
419
492
  if (!delivery.delivered) {
420
493
  proposal.state = "stopped";
421
494
  proposal.stopReason = `the decision was not delivered: ${delivery.failures.join(", ")}`;
@@ -424,32 +497,61 @@ export class ScopeExpansionController {
424
497
  }
425
498
  proposal.state = "decided";
426
499
  // The answer is read again after the delivery: a rejection that
427
- // arrived while the decision was on its way still prevents the work.
500
+ // arrived while the decision was on its way still prevents the work,
501
+ // and the answer of the controller is stronger than the store.
502
+ const after = this.humanDecision(proposal);
428
503
  const latestAfter = this.deps.latestHumanDecision?.(proposal);
429
- if (latestAfter === "reject" && effective.outcome !== "reject") {
504
+ let finalDecision = effective;
505
+ if (after) {
506
+ finalDecision = after;
507
+ } else if (latestAfter === "reject") {
508
+ finalDecision = {
509
+ outcome: "reject",
510
+ selectedIds: [],
511
+ reasoning: "the human rejected the proposal",
512
+ source: "human",
513
+ };
514
+ } else if (latestAfter === "approve" && effective.source !== "human") {
515
+ finalDecision = {
516
+ ...effective,
517
+ outcome: "approve",
518
+ selectedIds: [...proposal.proposedIds],
519
+ source: "human",
520
+ };
521
+ }
522
+ if (finalDecision.outcome === "reject" && effective.outcome !== "reject") {
430
523
  proposal.state = "stopped";
431
524
  proposal.stopReason =
432
525
  "the human rejected the proposal after the decision was delivered";
526
+ // The delivered message said something else: the human has to
527
+ // know that the work stays stopped. A correction that reaches
528
+ // nobody does not change the outcome: the work stays stopped
529
+ // either way.
530
+ const correction = await this.deps.deliver(
531
+ scopeDecisionMessage(proposal, finalDecision, "remaining stopped", []),
532
+ { id: proposal.id, kind: "decision" },
533
+ );
534
+ if (!correction.delivered) {
535
+ proposal.stopReason = `${proposal.stopReason}; the correction was not delivered: ${correction.failures.join(", ")}`;
536
+ }
433
537
  this.deps.log?.(
434
538
  `The scope proposal ${proposal.id} stays unexecuted: ${proposal.stopReason}`,
435
539
  );
436
540
  return { started: false, reason: proposal.stopReason };
437
541
  }
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);
542
+ let finalScope = authorizedScope(proposal, finalDecision);
543
+ if (finalDecision !== effective) {
544
+ proposal.decision = finalDecision;
448
545
  // The delivered message said something else: the human has to
449
- // know what started. A correction that reaches nobody leaves
546
+ // know what starts. A correction that reaches nobody leaves
450
547
  // the work stopped.
451
548
  const correction = await this.deps.deliver(
452
- scopeDecisionMessage(proposal, approved, "starting the selected work"),
549
+ scopeDecisionMessage(
550
+ proposal,
551
+ finalDecision,
552
+ finalScope.ids.length > 0 ? "starting the selected work" : "remaining stopped",
553
+ finalScope.ids,
554
+ ),
453
555
  { id: proposal.id, kind: "decision" },
454
556
  );
455
557
  if (!correction.delivered) {
@@ -464,8 +566,8 @@ export class ScopeExpansionController {
464
566
  if (finalScope.ids.length === 0) {
465
567
  proposal.state = "stopped";
466
568
  proposal.stopReason =
467
- effective.outcome === "reject"
468
- ? effective.reasoning
569
+ finalDecision.outcome === "reject"
570
+ ? finalDecision.reasoning
469
571
  : (finalScope.reason ?? "the decision authorizes no work");
470
572
  return { started: false, reason: proposal.stopReason };
471
573
  }
@@ -474,6 +576,19 @@ export class ScopeExpansionController {
474
576
  return { started: true };
475
577
  }
476
578
 
579
+ /**
580
+ * The answer of the human, when the controller recorded one.
581
+ *
582
+ * The first answer wins: a second answer - a stale button of a
583
+ * notification that was already delivered - does not replace it.
584
+ */
585
+ private humanDecision(proposal: ScopeProposal): ScopeDecision | undefined {
586
+ if (!this.answered.has(proposal.id)) return undefined;
587
+ const decision = proposal.decision;
588
+ if (!decision || decision.source !== "human") return undefined;
589
+ return decision;
590
+ }
591
+
477
592
  /**
478
593
  * The authorized group finished.
479
594
  *
@@ -484,7 +599,7 @@ export class ScopeExpansionController {
484
599
  const proposal = this.proposals.get(id);
485
600
  if (!proposal) return;
486
601
  proposal.state = "finished";
487
- this.closedGeneration = proposal.generation;
602
+ this.closedGenerations.add(proposal.generation);
488
603
  this.deps.log?.(
489
604
  `The scope proposal ${proposal.id} is finished: the session stops again.`,
490
605
  );
package/index.ts CHANGED
@@ -101,6 +101,7 @@ import {
101
101
  findAutoResumeIndex,
102
102
  isAutoResumeMessage,
103
103
  neutralizeAutoResume,
104
+ NEUTRALIZED_STALE_RESUME_TEXT,
104
105
  } from "./harness/auto-resume-marker.ts";
105
106
  import {
106
107
  ScopeExpansionRuntime,
@@ -675,6 +676,14 @@ const sharedState = {
675
676
  // The runtime of the scope expansion: the backlog that could follow a
676
677
  // finished request is proposed, and only the approved issues start.
677
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,
678
687
  };
679
688
 
680
689
  /**
@@ -818,7 +827,16 @@ function deliveryOf(results: unknown): { delivered: boolean; failures: string[]
818
827
  const reached = rows.filter((row) => row.success && !row.skipped);
819
828
  const failures = rows
820
829
  .filter((row) => !row.success || row.skipped)
821
- .map((row) => `${row.channel ?? "channel"}: ${row.error ?? "not delivered"}`);
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
+ }
822
840
  return { delivered: reached.length > 0, failures };
823
841
  }
824
842
 
@@ -835,13 +853,16 @@ async function proposeScopeExpansion(): Promise<void> {
835
853
  // One proposal waits for an answer: a second one would ask the same
836
854
  // human twice about the same backlog.
837
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;
838
860
  const context = await getTaskContext().catch(() => null);
839
861
  if (!context || context.issues.length === 0) return;
840
862
  const candidates: ScopeCandidate[] = context.issues
841
863
  .slice(0, MAX_SCOPE_CANDIDATES)
842
864
  .map((issue) => ({ id: issue.id, title: issue.title }));
843
- const generation = requestScopeTracker.generation;
844
- await runtime.propose({
865
+ const proposal = await runtime.propose({
845
866
  requestId: `request-${generation}`,
846
867
  workspace: _piSessionCwd || process.cwd(),
847
868
  generation,
@@ -851,6 +872,9 @@ async function proposeScopeExpansion(): Promise<void> {
851
872
  risks: ["the work was not asked for"],
852
873
  choices: ["run the named issues", "keep the backlog closed"],
853
874
  });
875
+ if (proposal) {
876
+ sharedState.scopeProposedFor = generation;
877
+ }
854
878
  }
855
879
 
856
880
  /**
@@ -872,24 +896,28 @@ function applyChannelApproval(
872
896
  return false;
873
897
  }
874
898
 
875
- const result = controller.applyApproval(action, requestId, channel);
876
- if (!result?.applied) {
877
- logToFile(
878
- "[Approval]",
879
- `Stale or duplicate ${channel} click for ${requestId}: ${result?.reason ?? "ignored"}`,
880
- );
881
- return false;
882
- }
883
-
884
- logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
885
- logQuestionTransition(requestId, "answered", `${channel}:${action}`);
886
-
887
899
  // A question of a scope proposal is not a question of the work of the
888
900
  // request: it asks whether the backlog may follow. The answer decides
889
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.
890
906
  const scopeProposal = sharedState.scopeRuntime?.proposalForQuestion(requestId);
891
907
  if (scopeProposal) {
892
- const outcome: HumanScopeOutcome = result.resolution === "yes" ? "approve" : "reject";
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}`);
893
921
  void sharedState.scopeRuntime
894
922
  ?.answerByQuestion(requestId, outcome, `${channel}:${action}`)
895
923
  .then((executed) => {
@@ -904,6 +932,18 @@ function applyChannelApproval(
904
932
  return true;
905
933
  }
906
934
 
935
+ const result = controller.applyApproval(action, requestId, channel);
936
+ if (!result?.applied) {
937
+ logToFile(
938
+ "[Approval]",
939
+ `Stale or duplicate ${channel} click for ${requestId}: ${result?.reason ?? "ignored"}`,
940
+ );
941
+ return false;
942
+ }
943
+
944
+ logToFile("[Approval]", `${channel} decision '${action}' applied to ${requestId}`);
945
+ logQuestionTransition(requestId, "answered", `${channel}:${action}`);
946
+
907
947
  // The question is answered, so the wait is over. The wait state is only
908
948
  // cleared after a successful resolution.
909
949
  // The controller owns the wait: the answer ends it, and an evaluation
@@ -3029,14 +3069,17 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3029
3069
  * reaches nobody leaves the work stopped.
3030
3070
  */
3031
3071
  function createScopeExpansionRuntime(): ScopeExpansionRuntime {
3032
- return new 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({
3033
3076
  now: () => Date.now(),
3034
3077
  deliver: async (text, meta) => {
3035
3078
  const center = _nc?.center as NcCenter | undefined;
3036
3079
  if (!center) {
3037
3080
  return { delivered: false, failures: ["no notification center"] };
3038
3081
  }
3039
- const proposal = sharedState.scopeRuntime?.get(meta.id);
3082
+ const proposal = runtime?.get(meta.id);
3040
3083
  try {
3041
3084
  if (meta.kind === "proposal") {
3042
3085
  const results = await center.notifyWithApproval(
@@ -3121,6 +3164,16 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3121
3164
  };
3122
3165
  },
3123
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
+ }
3124
3177
  // The approval starts new work: it begins a new scope, so
3125
3178
  // the todos of the finished request stay its history.
3126
3179
  beginHumanRequest();
@@ -3185,6 +3238,7 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3185
3238
  },
3186
3239
  log: (message) => logToFile("[scope-expansion]", message),
3187
3240
  });
3241
+ return runtime;
3188
3242
  }
3189
3243
 
3190
3244
  pi.on("session_start", async (_event, ctx) => {
@@ -3562,31 +3616,35 @@ async function initAutoContinue(pi: ExtensionAPI): Promise<void> {
3562
3616
  // Deduplication: only notify once per work generation
3563
3617
  // Use a static flag for this session's settled cycle
3564
3618
  const completionKey = `done-${reason}`;
3565
- if (_completedNotifiedFor === completionKey) {
3619
+ const alreadyNotified = _completedNotifiedFor === completionKey;
3620
+ if (alreadyNotified) {
3566
3621
  logToFile("[auto-continue]", "Completion already notified for:", reason);
3567
- 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)));
3568
3639
  }
3569
- _completedNotifiedFor = completionKey;
3570
-
3571
- // Get full todo list for notification
3572
- const todoList = snapshot.items
3573
- .map((item) => {
3574
- const status = item.status === "completed" ? "[DONE]" : "[PENDING]";
3575
- const subject = item.subject.length > 50 ? item.subject.slice(0, 47) + "..." : item.subject;
3576
- return `${status} ${subject}`;
3577
- })
3578
- .join("\n");
3579
- const message = todoList || "All tasks completed";
3580
- // Notify user that all work is complete with todo list
3581
- _nc?.notify("ReadyForClient", {
3582
- jobId: `done-${reason.replace(/\s+/g, "-")}`,
3583
- requirement: message,
3584
- }).catch((e) => logToFile("[Notification]", "ReadyForClient failed:", String(e)));
3585
3640
 
3586
3641
  // The request of the human is done. The backlog of the
3587
3642
  // session is not work of it: the exact issues that
3588
3643
  // could follow are proposed, and only the approved
3589
- // ids start.
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.
3590
3648
  await proposeScopeExpansion();
3591
3649
  }
3592
3650
  }
@@ -7372,10 +7430,31 @@ issue is not authorized work of the current request).
7372
7430
  const details =
7373
7431
  index === -1 ? undefined : autoResumeDetails(event.messages[index]);
7374
7432
  // 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") {
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") {
7377
7437
  return { messages: event.messages };
7378
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
+ }
7379
7458
  const decision = decideResumeScope({
7380
7459
  work: await currentRequestWorkState(),
7381
7460
  reason: details?.reason ?? "auto-resume",
@@ -7383,7 +7462,11 @@ issue is not authorized work of the current request).
7383
7462
  if (decision.action !== "suppress") {
7384
7463
  return { messages: event.messages };
7385
7464
  }
7386
- logToFile("[resume-scope]", `Resume neutralized: ${decision.reason}`);
7465
+ logToFile(
7466
+ "[resume-scope]",
7467
+ `Resume neutralized: ${decision.reason} (${details?.nonce || "no nonce"})`,
7468
+ );
7469
+ reportSuppressedResume(decision.report);
7387
7470
  return {
7388
7471
  messages: neutralizeAutoResume(event.messages, index) as typeof event.messages,
7389
7472
  };
@@ -9167,15 +9250,20 @@ issue is not authorized work of the current request).
9167
9250
  }
9168
9251
  // The resume is a message of the harness, not a message of the
9169
9252
  // human: it carries a marker, so the guard can recognize it when
9170
- // it is consumed after the request finished.
9253
+ // it is consumed after the request finished. The marker names the
9254
+ // request the resume belongs to.
9171
9255
  pi.sendMessage(
9172
9256
  buildAutoResumeMessage({
9173
9257
  content,
9174
9258
  reason,
9175
9259
  scope: options.scope ?? "request",
9176
9260
  nonce: nextResumeNonce(),
9261
+ requestGeneration: requestScopeTracker.generation,
9177
9262
  }),
9178
- { deliverAs },
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 },
9179
9267
  );
9180
9268
  await nc("ResumeScheduled", {
9181
9269
  requirement: "Session auto-resume",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-harness-runtime",
3
- "version": "1.1.508",
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.508",
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.508",
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.508",
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",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/checkpoint",
3
- "version": "1.1.508",
3
+ "version": "1.1.509",
4
4
  "description": "Enhanced checkpoint system with incremental snapshots, diff-based storage, and recovery strategies",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi/clipboard",
3
- "version": "1.1.508",
3
+ "version": "1.1.509",
4
4
  "type": "module",
5
5
  "main": "src/index.ts",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-harness/codex-watcher",
3
- "version": "1.1.508",
3
+ "version": "1.1.509",
4
4
  "description": "Watches Codex CLI sessions and emits visible messages for PING-PONG monitoring",
5
5
  "type": "module",
6
6
  "main": "./dist/src/index.js",