gestalt-mobile 0.55.5 → 0.55.6

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.
@@ -398,6 +398,122 @@ describe('production composition', () => {
398
398
  const policyCatalog = {
399
399
  data: [{ id: 'gpt-6.1-sol', supportedReasoningEfforts: [{ reasoningEffort: 'medium' }] }],
400
400
  };
401
+ it('reconciles the existing second executor through health while root and attention are active', async () => {
402
+ const f = await createProductionAutopilotFixture({ autopilotSchedule: () => () => { } }, versionedText());
403
+ onTestFinished(() => f.app.close());
404
+ const { app, sessionId } = f;
405
+ const started = await app.inject({
406
+ method: 'POST',
407
+ url: `/api/sessions/${sessionId}/turns`,
408
+ payload: { text: 'Synthetic supervised handoff fixture' },
409
+ });
410
+ expect(started.statusCode).toBe(202);
411
+ const session = (await app.inject(`/api/sessions/${sessionId}`)).json();
412
+ const rootId = session.threadId;
413
+ const handle = f.handles.find((candidate) => candidate.requests.some((call) => call.method === 'turn/start'));
414
+ let handedOff = false;
415
+ let changeDuringRead = false;
416
+ const row = (id, task, active) => ({
417
+ id,
418
+ status: { type: active ? 'active' : 'idle' },
419
+ parentThreadId: rootId,
420
+ source: { subAgent: { thread_spawn: { agent_path: `/root/${task}` } } },
421
+ agentRole: 'default',
422
+ model: 'gpt-6.1-sol',
423
+ reasoningEffort: 'medium',
424
+ });
425
+ handle.respond = (method, params) => {
426
+ if (method === 'model/list')
427
+ return policyCatalog;
428
+ if (method === 'thread/list' && changeDuringRead) {
429
+ changeDuringRead = false;
430
+ handle.notify({
431
+ method: 'turn/completed',
432
+ params: { threadId: rootId, turn: { id: session.activeTurnId, status: 'completed' } },
433
+ });
434
+ }
435
+ if (method === 'thread/list')
436
+ return {
437
+ data: handedOff
438
+ ? [row('first-writer', 'l1', false), row('second-writer', 'l2', true)]
439
+ : [row('first-writer', 'l1', true)],
440
+ };
441
+ if (method === 'thread/read') {
442
+ const id = params.threadId;
443
+ return {
444
+ thread: id === rootId
445
+ ? { id, status: { type: 'active' } }
446
+ : row(id, id === 'first-writer' ? 'l1' : 'l2', !handedOff || id === 'second-writer'),
447
+ };
448
+ }
449
+ return undefined;
450
+ };
451
+ const health = async (id) => {
452
+ const response = (await handle.request({
453
+ id,
454
+ method: 'item/tool/call',
455
+ params: {
456
+ threadId: rootId,
457
+ turnId: session.activeTurnId,
458
+ tool: 'gestalt_org_plan_health',
459
+ arguments: {},
460
+ },
461
+ }));
462
+ expect(response.success).toBe(true);
463
+ return JSON.parse(response.contentItems[0].text);
464
+ };
465
+ expect(await health(9960)).toMatchObject({
466
+ executorBinding: { status: 'ready' },
467
+ modelPolicy: { child: { threadId: 'first-writer' } },
468
+ });
469
+ const completed = versionedText('DONE')
470
+ .replace('* WIP [#A] Parent', '* DONE [#A] Parent')
471
+ .replace(':REVIEW_STATUS: UNREVIEWED', ':REVIEW_STATUS: REVIEWED');
472
+ const next = versionedText()
473
+ .slice(versionedText().indexOf('* WIP'))
474
+ .replace(':ID: parent', ':ID: second')
475
+ .replace(':ID: child', ':ID: second-child')
476
+ .replace('** TODO', '** WIP');
477
+ // A synthetic accepted-review projection, followed by the real composition's binding reconciliation.
478
+ await writeFile(join(f.workspacePath, 'autopilot.org'), completed + next);
479
+ await app.inject(`/api/sessions/${sessionId}/plan`);
480
+ await expect(handle.request(attentionCall(9961))).resolves.toEqual(toOrgPlanAttentionAcknowledgement());
481
+ const before = (await app.inject(`/api/sessions/${sessionId}`)).json();
482
+ const startsBefore = f.handles
483
+ .flatMap((candidate) => candidate.requests)
484
+ .filter((call) => ['turn/start', 'turn/steer', 'thread/resume'].includes(call.method)).length;
485
+ const processesBefore = f.handles.length;
486
+ handedOff = true;
487
+ changeDuringRead = true;
488
+ expect(await health(9964)).toMatchObject({
489
+ executorBinding: { status: 'unavailable', code: 'CONTEXT_CHANGED' },
490
+ });
491
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json().agentActivity.root.state).toBe('awaitingHuman');
492
+ const reconciled = await health(9962);
493
+ expect(reconciled).toMatchObject({
494
+ executionAdmission: { allowed: true },
495
+ executorBinding: { status: 'ready', canonicalPosition: 'L2', authorizesExecution: false },
496
+ executorLaunch: { validated: true },
497
+ modelPolicy: {
498
+ configuration: 'match',
499
+ child: { threadId: 'second-writer', continuationCount: 0 },
500
+ },
501
+ });
502
+ expect(JSON.stringify(reconciled)).not.toContain('CONTROLLER_BINDING_INVALID');
503
+ const after = (await app.inject(`/api/sessions/${sessionId}`)).json();
504
+ expect(after.autopilot.enabled).toBe(before.autopilot.enabled);
505
+ expect(after.pendingInteractions).toMatchObject([
506
+ { kind: 'orgPlanAttention', requestId: '9961' },
507
+ ]);
508
+ expect(f.handles.length).toBe(processesBefore);
509
+ expect(f.handles
510
+ .flatMap((candidate) => candidate.requests)
511
+ .filter((call) => ['turn/start', 'turn/steer', 'thread/resume'].includes(call.method))).toHaveLength(startsBefore);
512
+ expect(await health(9963)).toMatchObject({
513
+ executorBinding: { status: 'ready', code: 'BINDING_MATCH' },
514
+ modelPolicy: { child: { threadId: 'second-writer' } },
515
+ });
516
+ });
401
517
  it('activates existing v1, validates catalog, dispatches launch instructions and records a report checkpoint', async () => {
402
518
  const timers = [];
403
519
  const fixture = await createProductionAutopilotFixture({
@@ -467,6 +583,8 @@ describe('production composition', () => {
467
583
  },
468
584
  });
469
585
  expect(handle.requests.slice(requestsBeforeHealth).map((call) => call.method)).toEqual([
586
+ 'thread/read',
587
+ 'thread/list',
470
588
  'model/list',
471
589
  ]);
472
590
  // Synthetic executor report: real composition validates the authoritative plan boundary.
@@ -541,7 +659,7 @@ describe('production composition', () => {
541
659
  });
542
660
  const beforeHealth = f.handles
543
661
  .flatMap((candidate) => candidate.requests)
544
- .filter((call) => ['turn/start', 'thread/read', 'thread/resume'].includes(call.method));
662
+ .filter((call) => ['turn/start', 'thread/resume'].includes(call.method));
545
663
  const response = (await handle.request({
546
664
  id: 9902,
547
665
  method: 'item/tool/call',
@@ -569,7 +687,7 @@ describe('production composition', () => {
569
687
  expect(health).toMatchObject({ enabled: false, reason: 'manualDisabled' });
570
688
  expect(f.handles
571
689
  .flatMap((candidate) => candidate.requests)
572
- .filter((call) => ['turn/start', 'thread/read', 'thread/resume'].includes(call.method))).toEqual(beforeHealth);
690
+ .filter((call) => ['turn/start', 'thread/resume'].includes(call.method))).toEqual(beforeHealth);
573
691
  });
574
692
  it('keeps explicit strict v1 blocked at production activation without scheduling', async () => {
575
693
  const timers = [];
@@ -604,12 +722,13 @@ describe('production composition', () => {
604
722
  'off-on-during-recovery',
605
723
  ])('guards configured executor dispatch in production: %s', async (scenario) => {
606
724
  const timers = [];
725
+ let observedRootThreadId = '';
607
726
  const f = await createProductionAutopilotFixture({
608
727
  autopilotActivity: (sessionId) => {
609
728
  const observedAt = new Date().toISOString();
610
729
  return {
611
730
  sessionId,
612
- rootThreadId: 'thread-1',
731
+ rootThreadId: observedRootThreadId,
613
732
  root: {
614
733
  state: 'idle',
615
734
  reason: 'turnCompleted',
@@ -647,6 +766,7 @@ describe('production composition', () => {
647
766
  onTestFinished(() => f.app.close());
648
767
  const actualRootThreadId = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json()
649
768
  .threadId;
769
+ observedRootThreadId = actualRootThreadId;
650
770
  const pendingRead = Promise.withResolvers();
651
771
  const pendingRecovery = Promise.withResolvers();
652
772
  const resumeOperation = vi.spyOn(CodexSessionRuntime.prototype, 'startExecutorTurn');
@@ -689,8 +809,16 @@ describe('production composition', () => {
689
809
  }
690
810
  return undefined;
691
811
  };
692
- timers.find((timer) => !timer.cancelled).callback();
693
- await vi.waitFor(() => expect(sawRead).toBe(true));
812
+ const delivered = new Set();
813
+ await vi.waitFor(() => {
814
+ for (const timer of timers) {
815
+ if (!timer.cancelled && !delivered.has(timer)) {
816
+ delivered.add(timer);
817
+ timer.callback();
818
+ }
819
+ }
820
+ expect(sawRead).toBe(true);
821
+ });
694
822
  if (scenario === 'off-during-read' || scenario === 'off-on-during-recovery') {
695
823
  if (scenario === 'off-on-during-recovery')
696
824
  await vi.waitFor(() => expect(sawRecovery).toBe(true));
@@ -916,6 +916,50 @@ export async function composeRelayApp(options) {
916
916
  if (!session)
917
917
  return false;
918
918
  if (isOrgPlanHealthCall(request)) {
919
+ const observedPlan = supervisedPlans.find(sessionId);
920
+ let executorBinding = observedPlan?.modelPolicyVersion === 1
921
+ ? autopilot.reconcileExecutorBinding(sessionId)
922
+ : null;
923
+ if (executorBinding &&
924
+ [
925
+ 'ROSTER_UNAVAILABLE',
926
+ 'ROOT_BINDING_MISMATCH',
927
+ 'EXECUTOR_NOT_OBSERVED',
928
+ 'EXECUTOR_UNAVAILABLE',
929
+ 'EXECUTOR_IDENTITY_INVALID',
930
+ 'EXECUTOR_AMBIGUOUS',
931
+ 'REPLACEMENT_NOT_AUTHORIZED',
932
+ 'PREVIOUS_WRITER_ACTIVE',
933
+ 'AUTHORIZED_REPLACEMENT_PENDING',
934
+ ].includes(executorBinding.code) &&
935
+ runtime) {
936
+ const topologyRevision = activity.observationRevision(sessionId);
937
+ const topology = await runtime.readExecutorTopology(session);
938
+ if (topology.kind === 'observed' &&
939
+ activity.observationRevision(sessionId) === topologyRevision &&
940
+ sessions.find(sessionId)?.threadId === topology.rootThreadId) {
941
+ // Seed identity only. A topology read must not overwrite newer root turn activity.
942
+ if (!activity.snapshot(sessionId, topology.observedAt).rootThreadId)
943
+ activity.observe({
944
+ sessionId,
945
+ kind: 'threadStarted',
946
+ threadId: topology.rootThreadId,
947
+ occurredAt: topology.observedAt,
948
+ });
949
+ activity.childrenReconciled(sessionId, topology.observedAt, topology.children);
950
+ executorBinding = autopilot.reconcileExecutorBinding(sessionId);
951
+ }
952
+ else {
953
+ executorBinding = autopilot.reconcileExecutorBinding(sessionId);
954
+ if (executorBinding.status !== 'ready')
955
+ executorBinding = {
956
+ ...executorBinding,
957
+ status: 'unavailable',
958
+ code: topology.kind === 'unavailable' ? topology.code : 'CONTEXT_CHANGED',
959
+ action: 'Current topology could not be verified. Keep the existing writer paused and retry a bounded health read after runtime evidence changes; do not replace it to repair a projection.',
960
+ };
961
+ }
962
+ }
919
963
  const modelPolicy = await executorModelEvidence.read(sessionId);
920
964
  const executorLaunch = await executorLaunchValidation.read(sessionId);
921
965
  const snapshot = autopilot.snapshot(sessionId);
@@ -934,6 +978,7 @@ export async function composeRelayApp(options) {
934
978
  : {}),
935
979
  ...(modelPolicy ? { modelPolicy } : {}),
936
980
  ...(executorLaunch ? { executorLaunch } : {}),
981
+ ...(executorBinding ? { executorBinding } : {}),
937
982
  }),
938
983
  },
939
984
  ],
@@ -192,8 +192,11 @@ function applyStatus(root, status) {
192
192
  function childOutcome(status, action, previous) {
193
193
  if (status === 'error' || status === 'failed' || status === 'systemError' || status === 'errored')
194
194
  return 'failed';
195
- if (status === 'interrupted' || status === 'shutdown' || action === 'close_agent')
195
+ if (status === 'shutdown' || action === 'close_agent')
196
196
  return 'cancelled';
197
+ // Interrupt ends the current turn; unlike close_agent it leaves this writer resumable.
198
+ if (status === 'interrupted')
199
+ return 'partial';
197
200
  if (status === 'completed' || status === 'idle')
198
201
  return 'partial';
199
202
  // A follow-up reopens the same physical child. Do not keep presenting its
@@ -11,12 +11,17 @@ export class AgentActivityRegistry {
11
11
  #snapshots = new Map();
12
12
  #timers = new Map();
13
13
  #generation = new Map();
14
+ #acceptedRosters = new Map();
14
15
  #inFlight = new Map();
15
16
  #disposed = new Set();
16
17
  constructor(publish, options = {}) {
17
18
  this.publish = publish;
18
19
  this.options = options;
19
20
  }
21
+ /** Fences asynchronous observations against newer runtime facts. */
22
+ observationRevision(sessionId) {
23
+ return (this.#generation.get(sessionId) ?? 0) + (this.#acceptedRosters.get(sessionId) ?? 0);
24
+ }
20
25
  snapshot(sessionId, now) {
21
26
  return this.#snapshots.get(sessionId) ?? createAgentActivitySnapshot(sessionId, now);
22
27
  }
@@ -84,6 +89,7 @@ export class AgentActivityRegistry {
84
89
  childrenReconciled(sessionId, occurredAt, children) {
85
90
  if (this.#disposed.has(sessionId))
86
91
  return this.snapshot(sessionId, occurredAt);
92
+ this.#acceptedRosters.set(sessionId, (this.#acceptedRosters.get(sessionId) ?? 0) + 1);
87
93
  let next = this.snapshot(sessionId, occurredAt);
88
94
  const seen = new Set(children.map((child) => child.id));
89
95
  for (const child of children)
@@ -3,6 +3,7 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { parseOrgPlanAgentIdentity } from '../../../../shared/org-plan-position.js';
6
7
  import { assessModelPolicyAdmission } from '../../plans/domain/model-policy-admission.js';
7
8
  import { requirePlanFingerprint } from '../domain/plan-fingerprint.js';
8
9
  import { AutopilotStateError } from '../domain/persisted-state-error.js';
@@ -35,6 +36,154 @@ export class AutopilotCoordinator {
35
36
  constructor(deps) {
36
37
  this.deps = deps;
37
38
  }
39
+ /** Observe ownership independently of execution permission. Never dispatches or clears attention. */
40
+ reconcileExecutorBinding(sessionId) {
41
+ const state = this.deps.store.find(sessionId);
42
+ const retained = this.deps.plan(sessionId);
43
+ const index = retained ? currentExecutableL1Index(retained.plan) : -1;
44
+ const position = index < 0 ? null : `L${index + 1}`;
45
+ const result = (status, code, action) => ({
46
+ status,
47
+ code,
48
+ canonicalPosition: position,
49
+ action,
50
+ authorizesExecution: false,
51
+ });
52
+ if (!state || !retained || index < 0 || retained.plan.executionComplete === true)
53
+ return result('pending', 'NO_EXECUTABLE_BINDING', 'No current supervised executor is expected.');
54
+ if (!this.modelPolicyAdmission(sessionId).allowed)
55
+ return result('unavailable', 'EXECUTION_POLICY_UNAVAILABLE', 'Resolve the separate executionAdmission denial; do not invent ownership.');
56
+ if (state.planIdentity !== retained.identity)
57
+ return result('conflict', 'PLAN_IDENTITY_MISMATCH', 'Reconcile the retained plan identity before adopting any executor.');
58
+ const activity = this.deps.activity(sessionId);
59
+ const root = this.deps.session(sessionId)?.threadId;
60
+ if (!activity || activity.confidence !== 'fresh')
61
+ return result('unavailable', 'ROSTER_UNAVAILABLE', 'Refresh the owning runtime roster once; do not replace or resume a writer from stale evidence.');
62
+ if (activity.sessionId !== sessionId || !root || activity.rootThreadId !== root)
63
+ return result('unavailable', 'ROOT_BINDING_MISMATCH', 'Read topology from the current owning root/session.');
64
+ const plan = retained.plan;
65
+ if (plan.steps
66
+ .slice(0, index)
67
+ .some((step) => step.state !== 'DONE' ||
68
+ step.reviewStatus !== 'REVIEWED' ||
69
+ step.children.some((child) => child.state !== 'DONE')))
70
+ return result('conflict', 'PREVIOUS_MILESTONE_UNREVIEWED', 'Complete the preceding milestone review gates before handing off ownership.');
71
+ const live = (child) => ['working', 'awaitingAgent', 'awaitingHuman'].includes(child.state) ||
72
+ child.ownedProcesses?.some((process) => process.state === 'running' || process.state === 'detached-active');
73
+ if (activity.subagents.some((child) => child.canonicalPosition && child.canonicalPosition !== position && live(child)))
74
+ return result('conflict', 'PREVIOUS_WRITER_ACTIVE', 'Stop the previous milestone writer through the normal lifecycle, then refresh ownership; do not start another writer.');
75
+ const taskName = `l${index + 1}`;
76
+ const samePosition = state.executor?.canonicalPosition === position;
77
+ const assigned = samePosition && state.executor
78
+ ? (state.executor.assignment ?? executorAssignment(state.executor))
79
+ : undefined;
80
+ const replacement = samePosition &&
81
+ state.executor?.replacement &&
82
+ this.validReplacement(sessionId, state.executor.replacement)
83
+ ? state.executor.replacement
84
+ : undefined;
85
+ const candidates = activity.subagents.filter((child) => child.canonicalPosition === position ||
86
+ (child.taskPath &&
87
+ parseOrgPlanAgentIdentity(child.taskPath)?.canonicalPosition === position));
88
+ let eligible = candidates.filter((child) => {
89
+ const generation = child.continuationGeneration ?? 1;
90
+ return !(assigned && generation < assigned.generation && !live(child));
91
+ });
92
+ if (!eligible.length)
93
+ return result('pending', 'EXECUTOR_NOT_OBSERVED', 'The current executor is not yet observed. Refresh topology; do not replace an existing writer to repair a projection.');
94
+ if (eligible.length > 1) {
95
+ const replacementChildren = replacement
96
+ ? eligible.filter((child) => child.taskPath?.split('/').at(-1) === replacement.taskName &&
97
+ (child.continuationGeneration ?? 1) === replacement.generation)
98
+ : [];
99
+ const predecessor = (child) => assigned &&
100
+ (child.threadId ?? child.id) === assigned.threadId &&
101
+ child.taskPath === assigned.taskPath &&
102
+ (child.continuationGeneration ?? 1) === assigned.generation;
103
+ if (replacementChildren.length === 1 &&
104
+ eligible.every((child) => child === replacementChildren[0] || predecessor(child))) {
105
+ const replacementChild = replacementChildren[0];
106
+ if (eligible.some((child) => child !== replacementChild && live(child)))
107
+ return result('pending', 'AUTHORIZED_REPLACEMENT_PENDING', 'The already-authorized replacement handoff must settle before work resumes.');
108
+ eligible = [replacementChild];
109
+ }
110
+ else
111
+ return result('conflict', 'EXECUTOR_AMBIGUOUS', 'Multiple physical executors occupy this canonical position. Preserve the assigned owner; never choose a winner by recency.');
112
+ }
113
+ const child = eligible[0];
114
+ const identity = child.taskPath ? parseOrgPlanAgentIdentity(child.taskPath) : null;
115
+ if (!identity ||
116
+ child.canonicalTaskName !== taskName ||
117
+ child.canonicalPosition !== position ||
118
+ identity.canonicalTaskName !== taskName ||
119
+ identity.generation !== (child.continuationGeneration ?? 1) ||
120
+ (child.threadId ?? child.id) === root)
121
+ return result('conflict', 'EXECUTOR_IDENTITY_INVALID', 'Repair contradictory runtime topology; do not guess executor identity.');
122
+ const exactAssigned = assigned &&
123
+ assigned.threadId === (child.threadId ?? child.id) &&
124
+ assigned.taskPath === child.taskPath &&
125
+ assigned.generation === identity.generation;
126
+ const exactReplacement = replacement &&
127
+ replacement.generation === identity.generation &&
128
+ replacement.taskName === child.taskPath?.split('/').at(-1);
129
+ if ((assigned && !exactAssigned && !exactReplacement) ||
130
+ (!assigned && identity.generation !== 1 && !exactReplacement))
131
+ return result('conflict', 'REPLACEMENT_NOT_AUTHORIZED', 'Resume the assigned physical executor or obtain the existing typed replacement authorization; observation alone cannot authorize replacement.');
132
+ if (exactAssigned && assigned.state !== 'resumable')
133
+ return result('conflict', 'ASSIGNMENT_CLOSED', 'A closed/unavailable assignment cannot be silently reopened. Use the normal lifecycle.');
134
+ if (child.outcome === 'cancelled' || child.state === 'disconnected')
135
+ return result('pending', 'EXECUTOR_UNAVAILABLE', 'The physical executor is unavailable. Preserve its identity and diagnose before replacement.');
136
+ let executor = this.currentExecutor(sessionId, plan, 0, samePosition ? state.executor : undefined, activity);
137
+ if (!executor)
138
+ return result('pending', 'EXECUTOR_NOT_OBSERVED', 'Refresh the existing executor topology before continuing.');
139
+ // Preserve retired command evidence, but no predecessor retry/replacement state can authorize this slot.
140
+ const changedWriter = !samePosition ||
141
+ state.executor?.threadId !== executor.threadId ||
142
+ state.executor?.taskPath !== executor.taskPath;
143
+ if (changedWriter)
144
+ executor = { ...executor, continuationCount: 0 };
145
+ if (changedWriter && state.executor?.commands?.length)
146
+ executor = {
147
+ ...executor,
148
+ commands: state.executor.commands.map((command) => ['scheduled', 'issued'].includes(command.status)
149
+ ? {
150
+ ...command,
151
+ status: 'superseded',
152
+ ...(command.status === 'scheduled' ? { supersededBeforeIssue: true } : {}),
153
+ updatedAt: this.deps.now(),
154
+ }
155
+ : command),
156
+ };
157
+ const bindingState = (value) => value
158
+ ? JSON.stringify({
159
+ ...value,
160
+ lastActivityAt: undefined,
161
+ resumeFailures: value.resumeFailures || undefined,
162
+ ownedProcesses: value.ownedProcesses.map((process) => ({
163
+ ...process,
164
+ observedAt: undefined,
165
+ elapsedMs: undefined,
166
+ cpuPercent: undefined,
167
+ rssBytes: undefined,
168
+ })),
169
+ })
170
+ : null;
171
+ const changed = bindingState(state.executor) !== bindingState(executor);
172
+ if (changed)
173
+ this.persist({ ...state, executor, updatedAt: this.deps.now() }, undefined, [
174
+ {
175
+ sessionId,
176
+ type: 'autopilot.executor-binding-reconciled',
177
+ occurredAt: this.deps.now(),
178
+ payload: {
179
+ canonicalPosition: position,
180
+ previousThreadId: state.executor?.threadId ?? null,
181
+ threadId: executor.threadId,
182
+ },
183
+ },
184
+ ]);
185
+ return result('ready', changed ? 'BINDING_RECONCILED' : 'BINDING_MATCH', 'Current canonical executor ownership is reconciled. Respect admission, Manual Off, attention and observed settings before resuming the same writer.');
186
+ }
38
187
  snapshot(sessionId) {
39
188
  let state;
40
189
  try {
@@ -429,7 +578,7 @@ export class AutopilotCoordinator {
429
578
  providerFailure: undefined,
430
579
  providerFailureTurnId: undefined,
431
580
  providerRetry: undefined,
432
- executor: !replacing && prior.state === 'attentionRequired' ? prior.executor : undefined,
581
+ executor: !replacing ? prior.executor : undefined,
433
582
  blocking: undefined,
434
583
  supervision: recoverSafetyPause(consumeObsoleteWait(replacing || prior.supervision?.outcome === 'attentionRequired'
435
584
  ? startSupervisionProtocol(this.progressKey(sessionId))
@@ -560,6 +709,7 @@ export class AutopilotCoordinator {
560
709
  this.parkedSubscriptions.delete(sessionId);
561
710
  }
562
711
  evaluate(sessionId) {
712
+ const binding = this.reconcileExecutorBinding(sessionId);
563
713
  const prior = this.deps.store.find(sessionId);
564
714
  if (!prior)
565
715
  return this.snapshot(sessionId);
@@ -598,6 +748,9 @@ export class AutopilotCoordinator {
598
748
  plan &&
599
749
  !this.requiresRootBoundary(prior, plan) &&
600
750
  !this.executorDiagnosisRequired(prior) &&
751
+ (plan.modelPolicyVersion !== 1 ||
752
+ binding.status === 'ready' ||
753
+ binding.code === 'AUTHORIZED_REPLACEMENT_PENDING') &&
601
754
  this.currentExecutor(sessionId, plan, prior.consecutiveNoProgress, prior.executor)) {
602
755
  this.enqueue(sessionId, async () => {
603
756
  await this.enforceSupervisedLifecycle(sessionId, 'stateChanged');
@@ -1095,6 +1248,7 @@ export class AutopilotCoordinator {
1095
1248
  }
1096
1249
  /** Handles only plan lifecycle safety; ordinary plan mutations are ignored. */
1097
1250
  planStatusChanged(sessionId) {
1251
+ this.reconcileExecutorBinding(sessionId);
1098
1252
  const prior = this.deps.store.find(sessionId);
1099
1253
  if (!prior)
1100
1254
  return;
@@ -1237,7 +1391,7 @@ export class AutopilotCoordinator {
1237
1391
  nextEvaluationAt: null,
1238
1392
  ...(cancelled ? { lastControlId: null } : {}),
1239
1393
  stopReason: null,
1240
- executor: undefined,
1394
+ executor: replacing ? undefined : prior.executor,
1241
1395
  blocking: undefined,
1242
1396
  supervision: recoverSafetyPause(consumeObsoleteWait(replacing
1243
1397
  ? startSupervisionProtocol(this.progressKey(sessionId))
@@ -1252,9 +1406,15 @@ export class AutopilotCoordinator {
1252
1406
  }
1253
1407
  /** Reacts only to fresh actor status; plan mutations are not scheduling signals. */
1254
1408
  activityChanged(sessionId) {
1409
+ this.reconcileExecutorBinding(sessionId);
1255
1410
  let prior = this.deps.store.find(sessionId);
1256
1411
  if (!prior?.requestedEnabled)
1257
1412
  return;
1413
+ if (this.deps.pendingInteraction(sessionId)) {
1414
+ if (prior.state !== 'attentionRequired')
1415
+ this.evaluate(sessionId);
1416
+ return;
1417
+ }
1258
1418
  const activity = this.deps.activity(sessionId);
1259
1419
  // A stale or absent activity projection is itself a mandatory wake input.
1260
1420
  // Do not require a probe lease to restore the authoritative topology.
@@ -1502,6 +1662,7 @@ export class AutopilotCoordinator {
1502
1662
  }
1503
1663
  async fire(sessionId, generation) {
1504
1664
  this.timers.delete(sessionId);
1665
+ const binding = this.reconcileExecutorBinding(sessionId);
1505
1666
  const current = this.deps.store.find(sessionId);
1506
1667
  if (!current || current.generation !== generation || !current.requestedEnabled)
1507
1668
  return;
@@ -1561,6 +1722,9 @@ export class AutopilotCoordinator {
1561
1722
  !current.executor?.replacement &&
1562
1723
  !this.requiresRootBoundary(current, retained.plan) &&
1563
1724
  !this.executorDiagnosisRequired(current) &&
1725
+ (retained.plan.modelPolicyVersion !== 1 ||
1726
+ binding.status === 'ready' ||
1727
+ binding.code === 'AUTHORIZED_REPLACEMENT_PENDING') &&
1564
1728
  this.currentExecutor(sessionId, retained.plan, current.consecutiveNoProgress, current.executor)) {
1565
1729
  const now = this.deps.now();
1566
1730
  const cancelled = this.cancelScheduledControl(current, now);
@@ -1733,6 +1897,11 @@ export class AutopilotCoordinator {
1733
1897
  async enforceSupervisedLifecycle(sessionId, event) {
1734
1898
  if (this.rejectModelPolicyExecution(sessionId))
1735
1899
  return true;
1900
+ const binding = this.reconcileExecutorBinding(sessionId);
1901
+ if (this.deps.plan(sessionId)?.plan.modelPolicyVersion === 1 &&
1902
+ binding.status !== 'ready' &&
1903
+ binding.code !== 'AUTHORIZED_REPLACEMENT_PENDING')
1904
+ return false;
1736
1905
  const controller = this.deps.executorController;
1737
1906
  const retained = this.deps.plan(sessionId);
1738
1907
  const state = this.deps.store.find(sessionId);
@@ -502,6 +502,62 @@ export class CodexSessionRuntime {
502
502
  this.historyReads.delete(session.id);
503
503
  }
504
504
  }
505
+ /** Read-only ownership observation: no detached reader, model turn, resume or interruption. */
506
+ async readExecutorTopology(session) {
507
+ const resource = this.sessions.get(session.id);
508
+ if (!resource?.active || !session.threadId || resource.threadId !== session.threadId)
509
+ return { kind: 'unavailable', code: 'ROOT_BINDING_MISMATCH' };
510
+ const rootThreadId = session.threadId;
511
+ let timer;
512
+ let expired = false;
513
+ const current = () => !expired &&
514
+ this.sessions.get(session.id) === resource &&
515
+ resource.active &&
516
+ resource.threadId === rootThreadId;
517
+ try {
518
+ const observation = await Promise.race([
519
+ (async () => {
520
+ const result = await resource.process.rpc.request('thread/read', {
521
+ threadId: rootThreadId,
522
+ includeTurns: false,
523
+ });
524
+ const value = asRecord(asRecord(result)?.thread);
525
+ const status = asRecord(value?.status)?.type;
526
+ if (!current() ||
527
+ value?.id !== rootThreadId ||
528
+ !['active', 'idle'].includes(String(status)))
529
+ throw new Error('EXECUTOR_TOPOLOGY_UNAVAILABLE');
530
+ const children = await this.listDirectChildrenFromProcess(resource.process, rootThreadId, current);
531
+ if (children.some((child) => child.qualified === false))
532
+ throw new Error('EXECUTOR_TOPOLOGY_INCOMPLETE');
533
+ return { children, rootActive: status === 'active' };
534
+ })(),
535
+ new Promise((_, reject) => {
536
+ timer = setTimeout(() => {
537
+ expired = true;
538
+ reject(new Error('EXECUTOR_TOPOLOGY_TIMEOUT'));
539
+ }, 5_000);
540
+ }),
541
+ ]);
542
+ if (this.sessions.get(session.id) !== resource ||
543
+ !resource.active ||
544
+ resource.threadId !== rootThreadId)
545
+ return { kind: 'unavailable', code: 'CONTEXT_CHANGED' };
546
+ return {
547
+ kind: 'observed',
548
+ ...observation,
549
+ observedAt: new Date().toISOString(),
550
+ rootThreadId,
551
+ };
552
+ }
553
+ catch {
554
+ return { kind: 'unavailable', code: 'ROSTER_UNAVAILABLE' };
555
+ }
556
+ finally {
557
+ if (timer)
558
+ clearTimeout(timer);
559
+ }
560
+ }
505
561
  /** Bounded reconciliation port for direct spawned children only. */
506
562
  async listDirectChildren(session) {
507
563
  if (!session.threadId)
@@ -545,19 +601,58 @@ export class CodexSessionRuntime {
545
601
  process.close();
546
602
  }
547
603
  }
548
- async listDirectChildrenFromProcess(process, parentThreadId) {
604
+ async listDirectChildrenFromProcess(process, parentThreadId, current) {
549
605
  const children = [];
550
606
  const childIds = new Set();
551
607
  const cursors = new Set();
552
608
  let cursor;
553
609
  for (let page = 0; page < 4 && childIds.size < 64; page += 1) {
610
+ if (current && !current())
611
+ throw new Error('EXECUTOR_TOPOLOGY_CHANGED');
554
612
  const result = await process.rpc.request('thread/list', {
555
613
  parentThreadId,
556
614
  ...(cursor ? { cursor } : {}),
557
615
  });
558
616
  const response = result && typeof result === 'object' ? result : null;
559
617
  const data = response && Array.isArray(response.data) ? response.data : [];
560
- children.push(...data.flatMap((candidate) => {
618
+ // The parent filter is a query, not proof of ownership. In the binding
619
+ // recovery path verify provenance before allowing a row into the registry.
620
+ const verified = [];
621
+ for (const candidate of data) {
622
+ if (!current) {
623
+ verified.push(candidate);
624
+ continue;
625
+ }
626
+ if (!current())
627
+ throw new Error('EXECUTOR_TOPOLOGY_CHANGED');
628
+ const row = asRecord(candidate);
629
+ if (typeof row?.id !== 'string')
630
+ continue;
631
+ let parent = row.parentThreadId;
632
+ if (typeof parent !== 'string') {
633
+ if (!decodeAgentTaskPath(row.source))
634
+ throw new Error('CHILD_PARENT_UNVERIFIED');
635
+ const response = await process.rpc.request('thread/read', {
636
+ threadId: row.id,
637
+ includeTurns: false,
638
+ });
639
+ const thread = asRecord(asRecord(response)?.thread);
640
+ if (!current() || thread?.id !== row.id)
641
+ throw new Error('EXECUTOR_TOPOLOGY_CHANGED');
642
+ parent = thread.parentThreadId;
643
+ if (typeof parent !== 'string')
644
+ throw new Error('CHILD_PARENT_UNVERIFIED');
645
+ if (parent === parentThreadId &&
646
+ decodeAgentTaskPath(thread.source) !== decodeAgentTaskPath(row.source))
647
+ throw new Error('CHILD_IDENTITY_CHANGED');
648
+ }
649
+ if (parent === parentThreadId) {
650
+ if (!decodeAgentTaskPath(row.source))
651
+ throw new Error('CHILD_IDENTITY_UNVERIFIED');
652
+ verified.push(candidate);
653
+ }
654
+ }
655
+ children.push(...verified.flatMap((candidate) => {
561
656
  if (!candidate || typeof candidate !== 'object')
562
657
  return [];
563
658
  const value = candidate;
@@ -6,7 +6,7 @@
6
6
  export const gestaltOrgPlanHealthDynamicTool = {
7
7
  type: 'function',
8
8
  name: 'gestalt_org_plan_health',
9
- description: 'Read current Org execution health. executorLaunch validates requested model/effort against the owning runtime catalog before a child exists; modelPolicy describes child-only settings and may remain unknown. Read-only; does not enable, resume, checkpoint, or change the Org Plan.',
9
+ description: 'Read Org health and reconcile observed canonical executor ownership. executorBinding repairs safe handoffs even during attention or Manual Off, without starting, resuming, replacing or interrupting agents or clearing attention. executorLaunch validates requested model/effort before a child exists; modelPolicy retains unknown child settings. Never enables Autopilot or changes the Org Plan.',
10
10
  inputSchema: { type: 'object', additionalProperties: false, properties: {} },
11
11
  };
12
12
  export function isOrgPlanHealthCall(input) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.55.5",
3
+ "version": "0.55.6",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",