gestalt-mobile 0.54.0 → 0.54.2

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.
@@ -16,7 +16,7 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-DhQ2D-7J.js"></script>
19
+ <script type="module" crossorigin src="/assets/index-CRxjJEwq.js"></script>
20
20
  <link rel="stylesheet" crossorigin href="/assets/index-BRDqtTQi.css">
21
21
  </head>
22
22
  <body>
@@ -808,6 +808,76 @@ describe('production composition', () => {
808
808
  expect(JSON.stringify(await app.inject('/api/sessions'))).not.toContain('Inspect the active supervised Org Plan');
809
809
  await app.close();
810
810
  });
811
+ it('production correlates overload recovery with a settled root turn and cancels it on Off', async () => {
812
+ const timers = [];
813
+ const fixture = await createProductionAutopilotFixture({
814
+ autopilotSchedule: (callback, delay) => {
815
+ const timer = { callback, delay, cancelled: false };
816
+ timers.push(timer);
817
+ return () => {
818
+ timer.cancelled = true;
819
+ };
820
+ },
821
+ });
822
+ onTestFinished(() => fixture.app.close());
823
+ timers.find((timer) => !timer.cancelled).callback();
824
+ await vi.waitFor(() => expect(fixture.handles.some((handle) => handle.calls.includes('turn/start'))).toBe(true));
825
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
826
+ const handle = fixture.handles.find((candidate) => candidate.calls.includes('turn/start'));
827
+ const error = { codexErrorInfo: 'serverOverloaded', message: 'private overload body' };
828
+ handle.notify({
829
+ method: 'error',
830
+ params: {
831
+ threadId: session.threadId,
832
+ turnId: session.activeTurnId,
833
+ error,
834
+ willRetry: false,
835
+ },
836
+ });
837
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot
838
+ .providerRetry).toMatchObject({ turnId: session.activeTurnId, attempt: 1, pending: true, settled: false });
839
+ handle.notify({
840
+ method: 'turn/completed',
841
+ params: {
842
+ threadId: session.threadId,
843
+ turn: { id: session.activeTurnId, status: 'failed', error },
844
+ },
845
+ });
846
+ const completed = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
847
+ expect(completed.activeTurnId).toBeNull();
848
+ expect(completed.autopilot.providerRetry).toMatchObject({
849
+ attempt: 1,
850
+ pending: true,
851
+ settled: true,
852
+ });
853
+ const retry = timers.find((timer) => timer.delay === 30_000 && !timer.cancelled);
854
+ expect(retry).toBeDefined();
855
+ await fixture.app.inject({
856
+ method: 'PUT',
857
+ url: `/api/sessions/${fixture.sessionId}/autopilot`,
858
+ payload: { enabled: false },
859
+ });
860
+ expect(retry.cancelled).toBe(true);
861
+ retry.callback();
862
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().autopilot).toMatchObject({ enabled: false, state: 'disabled' });
863
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
864
+ try {
865
+ const rows = database
866
+ .prepare("SELECT payload_json FROM session_events WHERE session_id=? AND type='autopilot.provider-failed'")
867
+ .all(fixture.sessionId);
868
+ expect(rows).toHaveLength(1);
869
+ expect(JSON.parse(rows[0].payload_json)).toMatchObject({
870
+ actor: 'root',
871
+ turnId: session.activeTurnId,
872
+ requestedEnabled: true,
873
+ providerFailure: { code: 'serverOverloaded' },
874
+ });
875
+ expect(JSON.stringify(rows)).not.toContain('private overload body');
876
+ }
877
+ finally {
878
+ database.close();
879
+ }
880
+ });
811
881
  it.each([
812
882
  'usageLimitExceeded',
813
883
  'contextWindowExceeded',
@@ -907,8 +977,12 @@ describe('production composition', () => {
907
977
  expect(result.activeTurnId).toBeNull();
908
978
  expect(result.autopilot).toMatchObject({
909
979
  enabled: false,
910
- state: 'safetyPaused',
911
- reason: code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
980
+ state: code === 'unauthorized' ? 'disabled' : 'safetyPaused',
981
+ reason: code === 'unauthorized'
982
+ ? 'manualDisabled'
983
+ : code === 'usageLimitExceeded'
984
+ ? 'usageLimitExceeded'
985
+ : 'providerError',
912
986
  providerFailure: failure,
913
987
  health: { nextExpectedAction: expect.stringContaining(code) },
914
988
  });
@@ -1512,7 +1586,7 @@ describe('production composition', () => {
1512
1586
  expect(checkpoint.count).toBe(1);
1513
1587
  await fixture.app.close();
1514
1588
  });
1515
- it('refreshes the published L2 boundary before selecting among multiple DONE children', async () => {
1589
+ it.each(['l2:second-child:DONE', 'measure:finish:second-child'])('refreshes the published L2 boundary %s before selecting among multiple DONE children', async (reason) => {
1516
1590
  const timers = [];
1517
1591
  const fixture = await createProductionAutopilotFixture({
1518
1592
  autopilotSchedule: (callback) => {
@@ -1541,7 +1615,7 @@ describe('production composition', () => {
1541
1615
  await writeFile(planStatusFilePath(planStatusDirectoryPath(fixture.workspacePath, fixture.sessionId), planPath), JSON.stringify({
1542
1616
  schemaVersion: 1,
1543
1617
  planPath,
1544
- reason: 'l2:second-child:DONE',
1618
+ reason,
1545
1619
  updatedAt: new Date().toISOString(),
1546
1620
  }));
1547
1621
  // No watcher wait or GET /plan refresh: the checkpoint itself is the barrier.
@@ -1567,6 +1641,115 @@ describe('production composition', () => {
1567
1641
  db.close();
1568
1642
  await fixture.app.close();
1569
1643
  });
1644
+ it('records the final measured L1 among six reviewed milestones without observing the review publication', async () => {
1645
+ const timers = [];
1646
+ const fixture = await createProductionAutopilotFixture({
1647
+ autopilotSchedule: (callback) => {
1648
+ const timer = { callback, cancelled: false };
1649
+ timers.push(timer);
1650
+ return () => {
1651
+ timer.cancelled = true;
1652
+ };
1653
+ },
1654
+ });
1655
+ try {
1656
+ // Establish the retained checkpoint protocol, as in a resumed supervised plan.
1657
+ const prior = await holdCheckpointRequest(fixture, timers, 817, true, true);
1658
+ prior.handle.responseSettled({ id: 817, outcome: 'resultWritten' });
1659
+ await expect(prior.response).resolves.toEqual(toOrgPlanCheckpointToolResponse('recorded'));
1660
+ prior.handle.deferResponseSettlement = false;
1661
+ const priorTimerCount = timers.length;
1662
+ prior.handle.notify({
1663
+ method: 'turn/completed',
1664
+ params: { threadId: prior.threadId, turn: { id: prior.turnId } },
1665
+ });
1666
+ await vi.waitFor(() => expect(timers.length).toBeGreaterThan(priorTimerCount));
1667
+ for (let attempt = 0; attempt < 3; attempt += 1) {
1668
+ const timer = timers.at(-1);
1669
+ timer.callback();
1670
+ await vi.waitFor(() => expect(fixture.handles
1671
+ .flatMap((candidate) => candidate.requests)
1672
+ .filter((request) => request.method === 'turn/start').length > 1 ||
1673
+ timers.at(-1) !== timer).toBe(true));
1674
+ if (fixture.handles
1675
+ .flatMap((candidate) => candidate.requests)
1676
+ .filter((request) => request.method === 'turn/start').length > 1)
1677
+ break;
1678
+ }
1679
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
1680
+ const handle = fixture.handles.find((candidate) => candidate.requests.some((request) => request.method === 'turn/start'));
1681
+ const planPath = join(fixture.workspacePath, 'autopilot.org');
1682
+ await writeFile(planPath, '#+TITLE: Completed plan\n' +
1683
+ Array.from({ length: 6 }, (_, index) => completedAutopilotPlanText()
1684
+ .replace(/^#\+TITLE:.*\n/, '')
1685
+ .replace(':ID: parent', `:ID: ${index === 5 ? 'end-to-end-acceptance' : `parent-${index}`}`)
1686
+ .replace(':ID: child', `:ID: child-${index}`)).join('\n'));
1687
+ // The watcher may coalesce review and measurement writes. Only the durable final
1688
+ // publication is available, just as after a relay restart.
1689
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(fixture.workspacePath, fixture.sessionId), planPath), JSON.stringify({
1690
+ schemaVersion: 1,
1691
+ planPath,
1692
+ reason: 'measure:finish:end-to-end-acceptance',
1693
+ updatedAt: new Date().toISOString(),
1694
+ }));
1695
+ const checkpointCall = (id) => ({
1696
+ id,
1697
+ method: 'item/tool/call',
1698
+ params: {
1699
+ threadId: session.threadId,
1700
+ turnId: session.activeTurnId,
1701
+ tool: 'gestalt_org_plan_checkpoint',
1702
+ arguments: { kind: 'l1Accepted' },
1703
+ },
1704
+ });
1705
+ await expect(handle.request(checkpointCall(819))).resolves.toEqual(toOrgPlanCheckpointToolResponse('recorded'));
1706
+ await expect(handle.request(checkpointCall(820))).resolves.toEqual(toOrgPlanCheckpointToolResponse('alreadyRecorded'));
1707
+ const db = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
1708
+ try {
1709
+ const rows = db
1710
+ .prepare("SELECT payload_json FROM session_events WHERE session_id = ? AND type = 'org-plan.milestone-checkpointed'")
1711
+ .all(fixture.sessionId);
1712
+ expect(rows).toHaveLength(1);
1713
+ expect(JSON.parse(rows[0].payload_json)).toMatchObject({
1714
+ l1Id: 'end-to-end-acceptance',
1715
+ position: 'L6',
1716
+ });
1717
+ // The accepted final milestone must release a new root turn for independent
1718
+ // terminal review, rather than treating implementation completion as final.
1719
+ const timerCount = timers.length;
1720
+ handle.notify({
1721
+ method: 'turn/completed',
1722
+ params: {
1723
+ threadId: session.threadId,
1724
+ turn: { id: session.activeTurnId },
1725
+ },
1726
+ });
1727
+ await vi.waitFor(() => expect(timers.length).toBeGreaterThan(timerCount));
1728
+ const startedTurns = () => fixture.handles
1729
+ .flatMap((candidate) => candidate.requests)
1730
+ .filter((request) => request.method === 'turn/start').length;
1731
+ for (let attempt = 0; attempt < 3 && startedTurns() === 2; attempt += 1) {
1732
+ const timer = timers.at(-1);
1733
+ timer.callback();
1734
+ await vi.waitFor(() => expect(startedTurns() > 2 || timers.at(-1) !== timer).toBe(true));
1735
+ }
1736
+ await vi.waitFor(() => expect(startedTurns()).toBe(3));
1737
+ const lifecycle = db
1738
+ .prepare('SELECT lifecycle_json FROM autopilot_sessions WHERE session_id = ?')
1739
+ .get(fixture.sessionId);
1740
+ expect(JSON.parse(lifecycle.lifecycle_json).checkpoints).toMatchObject({
1741
+ reportedL1Ids: ['end-to-end-acceptance'],
1742
+ terminalReviewAccepted: false,
1743
+ });
1744
+ }
1745
+ finally {
1746
+ db.close();
1747
+ }
1748
+ }
1749
+ finally {
1750
+ await fixture.app.close();
1751
+ }
1752
+ });
1570
1753
  it('records and idempotently replays accepted L1 after REVIEWED advances to the next TODO L1', async () => {
1571
1754
  const timers = [];
1572
1755
  const fixture = await createProductionAutopilotFixture({
@@ -794,7 +794,14 @@ export async function composeRelayApp(options) {
794
794
  // Unknown threads must not stop an unrelated session on the shared server.
795
795
  const providerFailure = decodeCodexFailure(notification);
796
796
  if (resolvedOrigin.kind !== 'unknown' && providerFailure)
797
- autopilot.providerFailed(sessionId, providerFailure);
797
+ autopilot.providerFailed(sessionId, providerFailure, {
798
+ actor: resolvedOrigin.kind === 'root' ? 'root' : 'child',
799
+ turnId: completionTurnId ??
800
+ (typeof notification.params?.turnId === 'string'
801
+ ? notification.params.turnId
802
+ : undefined),
803
+ settled: notification.method === 'turn/completed',
804
+ });
798
805
  const rootCommandId = resolvedOrigin.kind === 'root' ? completedCommandId(notification) : null;
799
806
  if (rootCommandId)
800
807
  autopilot.rootProcessCompleted(sessionId, rootCommandId);
@@ -16,6 +16,7 @@ import { classifyAgentActivity, decideAutopilot, executionComplete, } from './po
16
16
  import { consumeCheckpointBoundary, consumeObsoleteWait, consumeObservableWake, consumeWaitDeadline, recordAutomaticContinuation, recoverSafetyPause, registerProactiveWait as registerProtocolWait, reportProbe, semanticProgressKey, startSupervisionProtocol, } from '../domain/supervision-protocol.js';
17
17
  export class AutopilotCoordinator {
18
18
  deps;
19
+ providerTimers = new Map();
19
20
  timers = new Map();
20
21
  completionTimers = new Map();
21
22
  executorTimers = new Map();
@@ -79,6 +80,16 @@ export class AutopilotCoordinator {
79
80
  throw error;
80
81
  return; // snapshot exposes controllerUnavailable; only explicit Off repairs it.
81
82
  }
83
+ if (state?.providerRetry?.pending) {
84
+ // A restart loses the live reconciliation context. Retain the used budget
85
+ // and require explicit recovery instead of manufacturing fresh authority.
86
+ this.persist({
87
+ ...state,
88
+ providerRetry: { ...state.providerRetry, pending: false },
89
+ nextEvaluationAt: null,
90
+ updatedAt: this.deps.now(),
91
+ });
92
+ }
82
93
  const session = this.deps.session(sessionId);
83
94
  if (!state ||
84
95
  !session ||
@@ -370,10 +381,11 @@ export class AutopilotCoordinator {
370
381
  const currentPlan = this.deps.plan(sessionId);
371
382
  if (!currentPlan)
372
383
  return { code: 'AUTOPILOT_PLAN_REQUIRED' };
373
- if (executionComplete(currentPlan.plan))
374
- return { code: 'AUTOPILOT_PLAN_COMPLETE' };
375
384
  const now = this.deps.now();
376
385
  const prior = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
386
+ if (executionComplete(currentPlan.plan) &&
387
+ !this.terminalReviewPending(prior, currentPlan.identity))
388
+ return { code: 'AUTOPILOT_PLAN_COMPLETE' };
377
389
  const nextFingerprint = fingerprint(currentPlan.plan);
378
390
  const replacing = Boolean(prior.planIdentity && prior.planIdentity !== currentPlan.identity);
379
391
  if (replacing) {
@@ -395,6 +407,8 @@ export class AutopilotCoordinator {
395
407
  nextEvaluationAt: null,
396
408
  stopReason: null,
397
409
  providerFailure: undefined,
410
+ providerFailureTurnId: undefined,
411
+ providerRetry: undefined,
398
412
  executor: !replacing && prior.state === 'attentionRequired' ? prior.executor : undefined,
399
413
  blocking: undefined,
400
414
  supervision: recoverSafetyPause(consumeObsoleteWait(replacing || prior.supervision?.outcome === 'attentionRequired'
@@ -478,6 +492,7 @@ export class AutopilotCoordinator {
478
492
  prior.state === 'disabled' &&
479
493
  !cancelled &&
480
494
  !prior.supervision?.waitLease &&
495
+ !prior.providerFailure &&
481
496
  (!currentPlan || prior.planIdentity === currentPlan.identity))
482
497
  return this.snapshot(sessionId);
483
498
  const next = {
@@ -489,6 +504,9 @@ export class AutopilotCoordinator {
489
504
  nextEvaluationAt: null,
490
505
  ...(cancelled ? { lastControlId: null } : {}),
491
506
  stopReason: 'manualDisabled',
507
+ providerFailure: undefined,
508
+ providerFailureTurnId: undefined,
509
+ providerRetry: undefined,
492
510
  blocking: undefined,
493
511
  supervision: consumeObsoleteWait(prior.supervision ?? startSupervisionProtocol(this.progressKey(sessionId)), this.progressKey(sessionId)),
494
512
  updatedAt: now,
@@ -684,35 +702,161 @@ export class AutopilotCoordinator {
684
702
  }
685
703
  return this.snapshot(sessionId);
686
704
  }
687
- /** Terminal provider failures are retained even when automatic supervision is off. */
688
- providerFailed(sessionId, failure) {
705
+ /** Retain structured failures without turning manual Off into an automatic pause. */
706
+ providerFailed(sessionId, failure, origin) {
689
707
  const now = this.deps.now();
690
708
  const state = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
691
- if (state.state === 'safetyPaused' &&
709
+ const retry = state.providerRetry;
710
+ if (retry &&
711
+ !retry.pending &&
712
+ retry.turnId === origin?.turnId &&
713
+ failure.code === 'serverOverloaded')
714
+ return false;
715
+ if (retry && retry.turnId === origin?.turnId && state.providerFailure?.code === failure.code) {
716
+ if (origin?.settled && !retry.settled)
717
+ this.persist({ ...state, providerRetry: { ...retry, settled: true }, updatedAt: now });
718
+ return false;
719
+ }
720
+ if (!state.requestedEnabled &&
721
+ !retry?.pending &&
722
+ state.providerFailureTurnId === origin?.turnId &&
692
723
  state.providerFailure?.code === failure.code &&
693
724
  state.providerFailure.httpStatusCode === failure.httpStatusCode)
694
725
  return false;
726
+ const enabled = state.requestedEnabled || Boolean(retry?.pending);
727
+ const attempt = (retry?.attempt ?? 0) + 1;
728
+ const recoverable = enabled &&
729
+ failure.code === 'serverOverloaded' &&
730
+ origin?.actor === 'root' &&
731
+ Boolean(origin.turnId) &&
732
+ origin.turnId === this.deps.session(sessionId)?.activeTurnId &&
733
+ attempt <= 2;
734
+ const event = {
735
+ sessionId,
736
+ type: 'autopilot.provider-failed',
737
+ occurredAt: now,
738
+ payload: {
739
+ providerFailure: failure,
740
+ requestedEnabled: enabled,
741
+ actor: origin?.actor ?? 'unknown',
742
+ turnId: origin?.turnId ?? null,
743
+ retryAttempt: recoverable ? attempt : null,
744
+ },
745
+ };
746
+ if (!enabled) {
747
+ this.persist({
748
+ ...state,
749
+ providerFailure: failure,
750
+ providerFailureTurnId: origin?.turnId,
751
+ updatedAt: now,
752
+ }, undefined, [event]);
753
+ return true;
754
+ }
695
755
  const cancelled = this.cancelScheduledControl(state, now);
696
756
  this.cancelTimer(sessionId);
697
757
  this.cancelWaitTimer(sessionId);
698
- this.persist({
699
- // Timer cancellation also persists cancelled executor commands.
758
+ const next = {
700
759
  ...(this.deps.store.find(sessionId) ?? state),
701
760
  state: 'safetyPaused',
702
761
  requestedEnabled: false,
703
762
  generation: state.generation + 1,
704
- nextEvaluationAt: null,
763
+ nextEvaluationAt: recoverable
764
+ ? new Date(Date.parse(now) + 30_000 * attempt).toISOString()
765
+ : null,
705
766
  ...(cancelled ? { lastControlId: null } : {}),
706
767
  stopReason: failure.code === 'usageLimitExceeded' ? 'usageLimitExceeded' : 'providerError',
707
768
  providerFailure: failure,
769
+ providerFailureTurnId: origin?.turnId,
770
+ providerRetry: recoverable
771
+ ? {
772
+ turnId: origin.turnId,
773
+ attempt,
774
+ notBefore: new Date(Date.parse(now) + 30_000 * attempt).toISOString(),
775
+ settled: origin.settled,
776
+ pending: true,
777
+ resumeRoot: false,
778
+ }
779
+ : retry
780
+ ? { ...retry, pending: false, resumeRoot: false }
781
+ : undefined,
708
782
  supervision: undefined,
709
783
  updatedAt: now,
710
- }, cancelled);
784
+ };
785
+ this.persist(next, cancelled, [event]);
786
+ if (recoverable)
787
+ this.providerTimers.set(sessionId, this.deps.schedule(() => {
788
+ this.providerTimers.delete(sessionId);
789
+ this.enqueue(sessionId, () => this.retryProvider(sessionId, next.generation));
790
+ }, 30_000 * attempt));
711
791
  return true;
712
792
  }
793
+ async retryProvider(sessionId, generation) {
794
+ const initial = this.deps.store.find(sessionId);
795
+ if (!initial?.providerRetry?.pending || initial.generation !== generation)
796
+ return;
797
+ let compatible = false;
798
+ try {
799
+ compatible = (await this.deps.reconcile(sessionId)).compatible;
800
+ }
801
+ catch {
802
+ /* fail closed */
803
+ }
804
+ const current = this.deps.store.find(sessionId), session = this.deps.session(sessionId), activity = this.deps.activity(sessionId), retained = this.deps.plan(sessionId);
805
+ if (!current?.providerRetry?.pending || current.generation !== generation)
806
+ return;
807
+ const safe = Date.parse(this.deps.now()) >= Date.parse(current.providerRetry.notBefore) &&
808
+ compatible &&
809
+ current.providerRetry.settled &&
810
+ session?.state === 'ready' &&
811
+ !session.activeTurnId &&
812
+ activity?.confidence === 'fresh' &&
813
+ activity.root.state === 'idle' &&
814
+ Date.parse(this.deps.now()) - Date.parse(activity.root.observedAt) <=
815
+ this.deps.policy.staleAfterMs &&
816
+ activity.subagents.every((agent) => agent.state === 'idle' &&
817
+ !agent.ownedProcesses?.some((process) => ['running', 'detached-active'].includes(process.state))) &&
818
+ !this.deps.pendingInteraction(sessionId) &&
819
+ retained?.identity === current.planIdentity &&
820
+ fingerprint(retained.plan) === current.planFingerprint &&
821
+ (!executionComplete(retained.plan) || this.terminalReviewPending(current, retained.identity));
822
+ const now = this.deps.now();
823
+ this.persist({
824
+ ...current,
825
+ providerRetry: { ...current.providerRetry, pending: false, resumeRoot: safe },
826
+ nextEvaluationAt: null,
827
+ ...(safe
828
+ ? {
829
+ state: 'monitoring',
830
+ requestedEnabled: true,
831
+ stopReason: null,
832
+ providerFailure: undefined,
833
+ providerFailureTurnId: undefined,
834
+ supervision: startSupervisionProtocol(this.progressKey(sessionId)),
835
+ }
836
+ : {}),
837
+ updatedAt: now,
838
+ }, undefined, [
839
+ {
840
+ sessionId,
841
+ type: safe ? 'autopilot.provider-retry-ready' : 'autopilot.provider-retry-abandoned',
842
+ occurredAt: now,
843
+ payload: {
844
+ turnId: current.providerRetry.turnId,
845
+ retryAttempt: current.providerRetry.attempt,
846
+ reason: safe ? 'settledRoot' : 'unsafeOrUnconfirmed',
847
+ },
848
+ },
849
+ ]);
850
+ if (safe)
851
+ this.evaluate(sessionId);
852
+ }
713
853
  /** Returns whether an incomplete supervised plan may be treated as terminal by the relay. */
714
854
  turnCompleted(sessionId, turnId) {
715
- const state = this.deps.store.find(sessionId);
855
+ let state = this.deps.store.find(sessionId);
856
+ if (state?.providerRetry?.resumeRoot && turnId && turnId !== state.providerRetry.turnId) {
857
+ state = { ...state, providerRetry: { ...state.providerRetry, resumeRoot: false } };
858
+ this.persist(state);
859
+ }
716
860
  if (turnId && state?.checkpoints?.pendingTurnId && state.checkpoints.pendingTurnId !== turnId)
717
861
  return false;
718
862
  const plan = this.deps.plan(sessionId)?.plan;
@@ -1036,10 +1180,11 @@ export class AutopilotCoordinator {
1036
1180
  const currentPlan = this.deps.plan(sessionId);
1037
1181
  if (!currentPlan)
1038
1182
  return { code: 'AUTOPILOT_PLAN_REQUIRED' };
1039
- if (executionComplete(currentPlan.plan))
1040
- return { code: 'AUTOPILOT_PLAN_COMPLETE' };
1041
1183
  const now = this.deps.now();
1042
1184
  const prior = this.deps.store.find(sessionId) ?? disabledAutopilot(sessionId, now);
1185
+ if (executionComplete(currentPlan.plan) &&
1186
+ !this.terminalReviewPending(prior, currentPlan.identity))
1187
+ return { code: 'AUTOPILOT_PLAN_COMPLETE' };
1043
1188
  if (prior.planIdentity === currentPlan.identity &&
1044
1189
  !prior.requestedEnabled &&
1045
1190
  prior.stopReason === 'manualDisabled')
@@ -1181,6 +1326,14 @@ export class AutopilotCoordinator {
1181
1326
  this.cancelWaitTimer(sessionId);
1182
1327
  this.parkedSubscriptions.delete(sessionId);
1183
1328
  const prior = this.deps.store.find(sessionId);
1329
+ if (prior?.providerRetry?.pending)
1330
+ this.persist({
1331
+ ...prior,
1332
+ providerRetry: { ...prior.providerRetry, pending: false },
1333
+ nextEvaluationAt: null,
1334
+ generation: prior.generation + 1,
1335
+ updatedAt: this.deps.now(),
1336
+ });
1184
1337
  if (!prior || !prior.requestedEnabled)
1185
1338
  return;
1186
1339
  const now = this.deps.now();
@@ -1448,6 +1601,8 @@ export class AutopilotCoordinator {
1448
1601
  }
1449
1602
  }
1450
1603
  cancelTimer(sessionId) {
1604
+ this.providerTimers.get(sessionId)?.();
1605
+ this.providerTimers.delete(sessionId);
1451
1606
  this.timers.get(sessionId)?.();
1452
1607
  this.timers.delete(sessionId);
1453
1608
  this.completionTimers.get(sessionId)?.();
@@ -1629,7 +1784,19 @@ export class AutopilotCoordinator {
1629
1784
  }
1630
1785
  }
1631
1786
  }
1787
+ terminalReviewPending(state, planIdentity) {
1788
+ return Boolean(state.planIdentity === planIdentity &&
1789
+ state.checkpoints?.planIdentity === planIdentity &&
1790
+ state.checkpoints.protocolVersion === 1 &&
1791
+ !state.checkpoints.terminalReviewAccepted);
1792
+ }
1632
1793
  requiresRootBoundary(state, plan) {
1794
+ if (state.providerRetry?.resumeRoot)
1795
+ return true;
1796
+ // Completed milestone reports do not complete terminal review or its fixes.
1797
+ // Keep their continuation at root; a settled last executor cannot own it.
1798
+ if (executionComplete(plan) && this.terminalReviewPending(state, state.planIdentity ?? ''))
1799
+ return true;
1633
1800
  if (state.checkpoints?.rootContinuationFromTurnId)
1634
1801
  return true;
1635
1802
  const reportedL2 = new Set(state.checkpoints?.reportedL2Ids ?? []);
@@ -71,8 +71,7 @@ export function autopilotSnapshot(state, retryLimit, facts = {
71
71
  : healthy && rootWorking
72
72
  ? 'rootWorking'
73
73
  : 'degraded';
74
- const nextExpectedAction = state.providerFailure &&
75
- ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
74
+ const nextExpectedAction = state.providerFailure
76
75
  ? describeProviderFailure(state.providerFailure)
77
76
  : state.stopReason === 'usageLimitExceeded'
78
77
  ? 'Codex usage limit reached. Restore available usage or wait for the limit to reset, then resume Autopilot.'
@@ -142,10 +141,8 @@ export function autopilotSnapshot(state, retryLimit, facts = {
142
141
  ...(state.nextEvaluationAt ? { nextEvaluationAt: state.nextEvaluationAt } : {}),
143
142
  ...(state.executor ? { executor: state.executor } : {}),
144
143
  ...(state.blocking ? { blocking: state.blocking } : {}),
145
- ...(state.providerFailure &&
146
- ['providerError', 'usageLimitExceeded'].includes(state.stopReason ?? '')
147
- ? { providerFailure: state.providerFailure }
148
- : {}),
144
+ ...(state.providerFailure ? { providerFailure: state.providerFailure } : {}),
145
+ ...(state.providerRetry ? { providerRetry: state.providerRetry } : {}),
149
146
  updatedAt: state.updatedAt,
150
147
  };
151
148
  }
@@ -31,6 +31,8 @@ const diagnosticFields = new Set([
31
31
  'code',
32
32
  'rpcCode',
33
33
  'providerFailure',
34
+ 'actor',
35
+ 'retryAttempt',
34
36
  'httpStatusCode',
35
37
  'enabled',
36
38
  'requestedEnabled',
@@ -19,10 +19,16 @@ export function resolveOrgPlanCheckpointSignal(kind, plan, planIdentity, publica
19
19
  verdict: 'ACCEPT',
20
20
  };
21
21
  const pending = pendingTarget ? JSON.parse(pendingTarget) : undefined;
22
+ // Finishing measurement can replace the review/DONE publication before the
23
+ // watcher reads it. Recover its target from the durable reason, but require
24
+ // the same authoritative DONE/REVIEWED state below; measurement is not acceptance.
25
+ const measuredId = publicationReason?.match(/^measure:finish:([A-Za-z0-9._-]{1,128})$/)?.[1];
22
26
  const reviewedId = (pending?.[0] === 'l1' ? pending[1] : undefined) ??
23
- publicationReason?.match(/^review:([^:]{1,128}):REVIEWED$/)?.[1];
27
+ publicationReason?.match(/^review:([^:]{1,128}):REVIEWED$/)?.[1] ??
28
+ measuredId;
24
29
  const completedId = (pending?.[0] === 'l2' ? pending[2] : undefined) ??
25
- publicationReason?.match(/^l2:([^:]{1,128}):DONE$/)?.[1];
30
+ publicationReason?.match(/^l2:([^:]{1,128}):DONE$/)?.[1] ??
31
+ measuredId;
26
32
  // Publication identifies the actual transition, regardless of list order.
27
33
  // Without it, expand only an unambiguous boundary; never guess the last row.
28
34
  const allReviewed = plan.steps.filter((step) => step.state === 'DONE' && step.reviewStatus === 'REVIEWED');
@@ -6,7 +6,7 @@
6
6
  import { disabledAutopilot, } from '../../features/autopilot/domain/autopilot-session.js';
7
7
  import { AutopilotStateError } from '../../features/autopilot/domain/persisted-state-error.js';
8
8
  import { parsePersistedSupervisedLifecycle } from '../../features/autopilot/domain/supervised-lifecycle.js';
9
- import { parseProviderFailure } from '../../../shared/contracts/provider-failure.js';
9
+ import { parseProviderFailure, parseProviderRetry, } from '../../../shared/contracts/provider-failure.js';
10
10
  import { MAX_AUTOPILOT_RECORD_BYTES, parsePlanFingerprint, } from '../../features/autopilot/domain/plan-fingerprint.js';
11
11
  export class SqliteAutopilotStore {
12
12
  db;
@@ -80,6 +80,8 @@ export class SqliteAutopilotStore {
80
80
  state.supervision,
81
81
  state.checkpoints,
82
82
  state.providerFailure,
83
+ state.providerRetry,
84
+ state.providerFailureTurnId,
83
85
  ].some((value) => value !== undefined)
84
86
  ? JSON.stringify({
85
87
  executor: state.executor,
@@ -87,6 +89,8 @@ export class SqliteAutopilotStore {
87
89
  supervision: state.supervision,
88
90
  checkpoints: state.checkpoints,
89
91
  providerFailure: state.providerFailure,
92
+ providerRetry: state.providerRetry,
93
+ providerFailureTurnId: state.providerFailureTurnId,
90
94
  })
91
95
  : null;
92
96
  // Use the reader's exact contract before any write (including transaction/outbox writes).
@@ -254,7 +258,21 @@ function parseLifecycle(value) {
254
258
  const providerFailure = parseProviderFailure(parsed.providerFailure);
255
259
  if (parsed.providerFailure !== undefined && !providerFailure)
256
260
  return null;
257
- return { ...lifecycle, ...(providerFailure ? { providerFailure } : {}) };
261
+ const providerFailureTurnId = parsed.providerFailureTurnId;
262
+ if (providerFailureTurnId !== undefined &&
263
+ (typeof providerFailureTurnId !== 'string' ||
264
+ !providerFailureTurnId ||
265
+ providerFailureTurnId.length > 256))
266
+ return null;
267
+ const providerRetry = parseProviderRetry(parsed.providerRetry);
268
+ if (parsed.providerRetry !== undefined && !providerRetry)
269
+ return null;
270
+ return {
271
+ ...lifecycle,
272
+ ...(providerFailureTurnId ? { providerFailureTurnId } : {}),
273
+ ...(providerFailure ? { providerFailure } : {}),
274
+ ...(providerRetry ? { providerRetry } : {}),
275
+ };
258
276
  }
259
277
  catch {
260
278
  return null;
@@ -16,5 +16,6 @@ export function isPlanSignalReason(value) {
16
16
  return (typeof value === 'string' &&
17
17
  (planSignalReasons.includes(value) ||
18
18
  /^review:[A-Za-z0-9._-]{1,128}:REVIEWED$/.test(value) ||
19
+ /^measure:(start|checkpoint|finish):[A-Za-z0-9._-]{1,128}$/.test(value) ||
19
20
  /^l2:[A-Za-z0-9._-]{1,128}:(WIP|DONE)$/.test(value)));
20
21
  }