gestalt-mobile 0.55.4 → 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.
package/README.md CHANGED
@@ -119,7 +119,14 @@ provide that capability. Manual Off is independently respected. Legacy plans
119
119
  without model policy keep their existing behavior.
120
120
 
121
121
  `gestalt_org_plan_health` reports `executionAdmission.allowed`, configured
122
- assurance and `runtimeEnforcement:false`. Its `modelPolicy` evidence separately
122
+ assurance and `executorLaunch`, which checks the requested L1 model/effort using
123
+ the owning runtime's `model/list` before any executor exists. `CATALOG_MATCH`
124
+ includes a normalized-content fingerprint and observation time, never a fabricated
125
+ server revision. Child `modelPolicy.catalogRevision:null` does not mean the
126
+ prelaunch catalog is unavailable. `CHILD_NOT_LAUNCHED` is expected before dispatch.
127
+ Actual missing/incompatible catalogs retain explicit failure codes.
128
+
129
+ Health retains `runtimeEnforcement:false`. Its `modelPolicy` evidence separately
123
130
  reports `admissionScope: runtime-attestation`, `admitted:false`, `attested:false`,
124
131
  requested values and observed configured thread settings. Unknown values remain
125
132
  null, never copied from requests. A configured match is not runtime attestation.
@@ -129,7 +136,8 @@ Native collaboration spawn/followup calls remain cooperatively root-supervised;
129
136
  Mobile does not intercept them or guarantee universal pre-spawn enforcement.
130
137
  One writer per L1, independent review, evidence gates, checkpoint continuation
131
138
  and terminal whole-branch review remain required. See
132
- [update and rollback guidance](docs/org-plan-policy-compatibility.md).
139
+ [update and rollback guidance](docs/org-plan-policy-compatibility.md) and
140
+ [prelaunch catalog recovery](docs/org-plan-prelaunch-catalog.md).
133
141
 
134
142
  ## Skill profiles
135
143
 
@@ -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({
@@ -434,6 +550,43 @@ describe('production composition', () => {
434
550
  });
435
551
  expect(JSON.stringify(start.params)).not.toContain('reasoning_effort high');
436
552
  const session = (await app.inject(`/api/sessions/${sessionId}`)).json();
553
+ const requestsBeforeHealth = handle.requests.length;
554
+ const healthResponse = (await handle.request({
555
+ id: 9900,
556
+ method: 'item/tool/call',
557
+ params: {
558
+ threadId: session.threadId,
559
+ turnId: session.activeTurnId,
560
+ tool: 'gestalt_org_plan_health',
561
+ arguments: {},
562
+ },
563
+ }));
564
+ expect(healthResponse.success).toBe(true);
565
+ expect(JSON.parse(healthResponse.contentItems[0].text)).toMatchObject({
566
+ executionAdmission: { allowed: true, assurance: 'configured' },
567
+ executorLaunch: {
568
+ scope: 'prelaunch-catalog',
569
+ validated: true,
570
+ code: 'CATALOG_MATCH',
571
+ requested: { model: 'gpt-6.1-sol', reasoningEffort: 'medium' },
572
+ catalog: {
573
+ source: 'runtime-model-list',
574
+ fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/),
575
+ revisionSource: 'normalized-content-digest',
576
+ },
577
+ },
578
+ modelPolicy: {
579
+ code: 'CHILD_NOT_LAUNCHED',
580
+ catalogRevision: null,
581
+ effective: { model: null, reasoningEffort: null },
582
+ attested: false,
583
+ },
584
+ });
585
+ expect(handle.requests.slice(requestsBeforeHealth).map((call) => call.method)).toEqual([
586
+ 'thread/read',
587
+ 'thread/list',
588
+ 'model/list',
589
+ ]);
437
590
  // Synthetic executor report: real composition validates the authoritative plan boundary.
438
591
  await writeFile(join(workspacePath, 'autopilot.org'), versionedText('DONE'));
439
592
  const result = await handle.request({
@@ -469,6 +622,73 @@ describe('production composition', () => {
469
622
  });
470
623
  expect(handles.flatMap((handle) => handle.requests).filter((call) => call.method === 'turn/start')).toHaveLength(1);
471
624
  });
625
+ it.each(['missing', 'model', 'effort', 'manual-off'])('exposes prechild catalog evidence without changing admission or Manual Off: %s', async (scenario) => {
626
+ const f = await createProductionAutopilotFixture({ autopilotSchedule: () => () => { } }, versionedText());
627
+ onTestFinished(() => f.app.close());
628
+ const session = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json();
629
+ const handle = f.handles.find((candidate) => candidate.request);
630
+ for (const candidate of f.handles)
631
+ candidate.respond = (method) => method !== 'model/list'
632
+ ? undefined
633
+ : scenario === 'missing'
634
+ ? {}
635
+ : scenario === 'model'
636
+ ? {
637
+ data: [
638
+ {
639
+ id: 'gpt-6-sol',
640
+ supportedReasoningEfforts: [{ reasoningEffort: 'medium' }],
641
+ },
642
+ ],
643
+ }
644
+ : scenario === 'effort'
645
+ ? {
646
+ data: [
647
+ {
648
+ id: 'gpt-6.1-sol',
649
+ supportedReasoningEfforts: [{ reasoningEffort: 'low' }],
650
+ },
651
+ ],
652
+ }
653
+ : policyCatalog;
654
+ if (scenario === 'manual-off')
655
+ await f.app.inject({
656
+ method: 'PUT',
657
+ url: `/api/sessions/${f.sessionId}/autopilot`,
658
+ payload: { enabled: false },
659
+ });
660
+ const beforeHealth = f.handles
661
+ .flatMap((candidate) => candidate.requests)
662
+ .filter((call) => ['turn/start', 'thread/resume'].includes(call.method));
663
+ const response = (await handle.request({
664
+ id: 9902,
665
+ method: 'item/tool/call',
666
+ params: {
667
+ threadId: session.threadId,
668
+ tool: 'gestalt_org_plan_health',
669
+ arguments: {},
670
+ },
671
+ }));
672
+ const health = JSON.parse(response.contentItems[0].text);
673
+ expect(health).toMatchObject({
674
+ executionAdmission: { allowed: true },
675
+ executorLaunch: {
676
+ validated: scenario === 'manual-off',
677
+ code: scenario === 'missing'
678
+ ? 'CATALOG_UNAVAILABLE'
679
+ : scenario === 'model'
680
+ ? 'MODEL_UNAVAILABLE'
681
+ : scenario === 'effort'
682
+ ? 'EFFORT_UNSUPPORTED'
683
+ : 'CATALOG_MATCH',
684
+ },
685
+ });
686
+ if (scenario === 'manual-off')
687
+ expect(health).toMatchObject({ enabled: false, reason: 'manualDisabled' });
688
+ expect(f.handles
689
+ .flatMap((candidate) => candidate.requests)
690
+ .filter((call) => ['turn/start', 'thread/resume'].includes(call.method))).toEqual(beforeHealth);
691
+ });
472
692
  it('keeps explicit strict v1 blocked at production activation without scheduling', async () => {
473
693
  const timers = [];
474
694
  const f = await createProductionAutopilotFixture({
@@ -502,12 +722,13 @@ describe('production composition', () => {
502
722
  'off-on-during-recovery',
503
723
  ])('guards configured executor dispatch in production: %s', async (scenario) => {
504
724
  const timers = [];
725
+ let observedRootThreadId = '';
505
726
  const f = await createProductionAutopilotFixture({
506
727
  autopilotActivity: (sessionId) => {
507
728
  const observedAt = new Date().toISOString();
508
729
  return {
509
730
  sessionId,
510
- rootThreadId: 'thread-1',
731
+ rootThreadId: observedRootThreadId,
511
732
  root: {
512
733
  state: 'idle',
513
734
  reason: 'turnCompleted',
@@ -545,6 +766,7 @@ describe('production composition', () => {
545
766
  onTestFinished(() => f.app.close());
546
767
  const actualRootThreadId = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json()
547
768
  .threadId;
769
+ observedRootThreadId = actualRootThreadId;
548
770
  const pendingRead = Promise.withResolvers();
549
771
  const pendingRecovery = Promise.withResolvers();
550
772
  const resumeOperation = vi.spyOn(CodexSessionRuntime.prototype, 'startExecutorTurn');
@@ -587,8 +809,16 @@ describe('production composition', () => {
587
809
  }
588
810
  return undefined;
589
811
  };
590
- timers.find((timer) => !timer.cancelled).callback();
591
- 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
+ });
592
822
  if (scenario === 'off-during-read' || scenario === 'off-on-during-recovery') {
593
823
  if (scenario === 'off-on-during-recovery')
594
824
  await vi.waitFor(() => expect(sawRecovery).toBe(true));
@@ -87,6 +87,7 @@ import { autopilotWaitLeaseToolResponse, } from '../shared/contracts/autopilot-w
87
87
  import { agentCapacityRecoveryToolResponse } from '../shared/contracts/agent-capacity-recovery.js';
88
88
  import { isOrgPlanHealthCall } from '../shared/contracts/org-plan-health.js';
89
89
  import { ExecutorModelEvidenceReader } from './features/plans/application/executor-model-evidence.js';
90
+ import { ExecutorLaunchValidationReader } from './features/plans/application/executor-launch-validation.js';
90
91
  import { requireModelPolicyAdmission } from './features/plans/domain/model-policy-admission.js';
91
92
  import { currentExecutableL1Index } from './features/plans/domain/supervised-plan.js';
92
93
  import { pwaIconUrl } from './features/pwa/register-routes.js';
@@ -712,7 +713,7 @@ export async function composeRelayApp(options) {
712
713
  let closing = false;
713
714
  let runtime = null;
714
715
  let kimiRuntime = null;
715
- const executorModelEvidence = new ExecutorModelEvidenceReader((sessionId) => {
716
+ const executorPolicyContext = (sessionId) => {
716
717
  const session = sessions.find(sessionId);
717
718
  const plan = supervisedPlans.find(sessionId);
718
719
  if (!session || session.provider !== 'codex' || plan?.modelPolicyVersion !== 1)
@@ -722,13 +723,19 @@ export async function composeRelayApp(options) {
722
723
  provider: session.provider,
723
724
  rootThreadId: session.threadId ?? null,
724
725
  planIdentity: supervisedPlans.identity(sessionId),
726
+ modelPolicyStatus: supervisedPlans.modelPolicyStatus(sessionId),
725
727
  plan,
726
728
  executor: autopilotStore.find(sessionId)?.executor ?? null,
727
729
  };
728
- }, {
730
+ };
731
+ const executorModelEvidence = new ExecutorModelEvidenceReader(executorPolicyContext, {
729
732
  read: (input) => runtime?.readExecutorConfiguration(input) ??
730
733
  Promise.resolve({ kind: 'unavailable', code: 'RUNTIME_UNAVAILABLE' }),
731
734
  });
735
+ const executorLaunchValidation = new ExecutorLaunchValidationReader(executorPolicyContext, {
736
+ read: (input) => runtime?.readExecutorPolicyCatalog(input) ??
737
+ Promise.resolve({ kind: 'unavailable', code: 'RUNTIME_UNAVAILABLE' }),
738
+ });
732
739
  /**
733
740
  * Shared acceptance path for a provider-neutral pending interaction: it
734
741
  * enters the durable store, requests human attention, and notifies autopilot.
@@ -909,8 +916,53 @@ export async function composeRelayApp(options) {
909
916
  if (!session)
910
917
  return false;
911
918
  if (isOrgPlanHealthCall(request)) {
912
- const snapshot = autopilot.snapshot(sessionId);
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
+ }
913
963
  const modelPolicy = await executorModelEvidence.read(sessionId);
964
+ const executorLaunch = await executorLaunchValidation.read(sessionId);
965
+ const snapshot = autopilot.snapshot(sessionId);
914
966
  return (runtime?.resolveServerRequest(sessionId, String(request.id), {
915
967
  success: true,
916
968
  contentItems: [
@@ -925,6 +977,8 @@ export async function composeRelayApp(options) {
925
977
  ? { executionAdmission: snapshot.executionAdmission }
926
978
  : {}),
927
979
  ...(modelPolicy ? { modelPolicy } : {}),
980
+ ...(executorLaunch ? { executorLaunch } : {}),
981
+ ...(executorBinding ? { executorBinding } : {}),
928
982
  }),
929
983
  },
930
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);
@@ -0,0 +1,91 @@
1
+ /*
2
+ * Copyright (C) 2026 Dyne.org foundation
3
+ * Designed by Denis Roio <jaromil@dyne.org>
4
+ * SPDX-License-Identifier: AGPL-3.0-or-later
5
+ */
6
+ import { assessModelPolicyAdmission, } from '../domain/model-policy-admission.js';
7
+ import { currentExecutableL1Index } from '../domain/supervised-plan.js';
8
+ import { executionPolicyDigest, } from './executor-model-evidence.js';
9
+ /** Read-only selection evidence, never an enduring dispatch authorization or receipt. */
10
+ export class ExecutorLaunchValidationReader {
11
+ context;
12
+ runtime;
13
+ constructor(context, runtime) {
14
+ this.context = context;
15
+ this.runtime = runtime;
16
+ }
17
+ async read(sessionId) {
18
+ const context = this.context(sessionId);
19
+ if (!context ||
20
+ context.sessionId !== sessionId ||
21
+ context.provider !== 'codex' ||
22
+ context.plan?.modelPolicyVersion !== 1)
23
+ return null;
24
+ const index = currentExecutableL1Index(context.plan);
25
+ const step = context.plan.steps[index];
26
+ const policy = step?.modelPolicy;
27
+ if (!policy)
28
+ return null;
29
+ const admission = assessModelPolicyAdmission(context.plan, context.modelPolicyStatus);
30
+ const l1Id = Buffer.byteLength(JSON.stringify(step.id), 'utf8') <= 96 ? step.id : null;
31
+ const report = {
32
+ scope: 'prelaunch-catalog',
33
+ assurance: context.plan.modelPolicyAssurance ?? 'configured',
34
+ l1: { id: l1Id, position: index + 1 },
35
+ policyDigest: executionPolicyDigest(policy),
36
+ requested: { model: policy.model, reasoningEffort: policy.reasoningEffort },
37
+ validated: false,
38
+ code: 'CATALOG_UNAVAILABLE',
39
+ catalog: null,
40
+ runtimeEnforcement: false,
41
+ action: 'Read the active runtime catalog through health; child catalogRevision is not a prelaunch prerequisite.',
42
+ };
43
+ const finish = (code, action) => ({ ...report, code, action });
44
+ if (!admission.allowed)
45
+ return finish(admission.reason, admission.action);
46
+ if (!context.rootThreadId || !context.planIdentity || !l1Id)
47
+ return finish('ROOT_BINDING_MISMATCH', 'Restore the owning root/session binding before validating launch settings.');
48
+ const before = launchFence(context);
49
+ let result;
50
+ try {
51
+ result = await this.runtime.read({ sessionId, rootThreadId: context.rootThreadId });
52
+ }
53
+ catch {
54
+ return finish('CATALOG_UNAVAILABLE', 'The active runtime model/list read failed; inspect its capability without inventing catalog evidence.');
55
+ }
56
+ if (launchFence(this.context(sessionId)) !== before)
57
+ return finish('CONTEXT_CHANGED', 'Plan, policy or root ownership changed during the read; refresh health once before launch.');
58
+ if (result.kind !== 'observed')
59
+ return finish(result.code, 'The owning runtime catalog is unavailable; inspect the returned capability/binding code. No child receipt is required.');
60
+ report.catalog = {
61
+ source: result.source,
62
+ fingerprint: result.catalog.revision,
63
+ revisionSource: 'normalized-content-digest',
64
+ observedAt: result.observedAt,
65
+ };
66
+ const available = result.catalog.models.find((model) => model.id === policy.model);
67
+ if (!available)
68
+ return finish('MODEL_UNAVAILABLE', 'The runtime catalog does not support the requested exact model. Do not substitute a fallback silently.');
69
+ if (!available.reasoningEfforts.includes(policy.reasoningEffort))
70
+ return finish('EFFORT_UNSUPPORTED', 'The runtime catalog does not support the requested effort. Do not change effort silently.');
71
+ report.validated = true;
72
+ return finish('CATALOG_MATCH', 'Requested model/effort are supported by the owning runtime catalog. Proceed with the validated launch recipe within current controller authority; child settings remain unknown until observed.');
73
+ }
74
+ }
75
+ function launchFence(context) {
76
+ const index = context?.plan ? currentExecutableL1Index(context.plan) : -1;
77
+ const step = context?.plan?.steps[index];
78
+ return JSON.stringify([
79
+ context?.sessionId,
80
+ context?.provider,
81
+ context?.rootThreadId,
82
+ context?.planIdentity,
83
+ context?.plan?.modelPolicyVersion,
84
+ context?.modelPolicyStatus,
85
+ context?.plan?.modelPolicyAssurance ?? 'configured',
86
+ index,
87
+ step?.id,
88
+ step?.state,
89
+ step?.modelPolicy ? executionPolicyDigest(step.modelPolicy) : null,
90
+ ]);
91
+ }
@@ -79,6 +79,7 @@ export class ExecutorModelEvidenceReader {
79
79
  runtimeEnforcement: false,
80
80
  assurance: context.plan.modelPolicyAssurance ?? 'configured',
81
81
  code: 'CHILD_BINDING_UNKNOWN',
82
+ action: 'Child-only evidence. Use executorLaunch for prelaunch catalog validation; this report is not launch admission.',
82
83
  unknown: [],
83
84
  };
84
85
  const finish = (code) => {
@@ -94,8 +95,9 @@ export class ExecutorModelEvidenceReader {
94
95
  ];
95
96
  return report;
96
97
  };
97
- if (!executor ||
98
- !identity ||
98
+ if (!executor)
99
+ return finish('CHILD_NOT_LAUNCHED');
100
+ if (!identity ||
99
101
  !context.rootThreadId ||
100
102
  !context.planIdentity ||
101
103
  !child.threadId ||
@@ -321,11 +321,13 @@ export class CodexSessionRuntime {
321
321
  resource.turnThreads.set(result, childThreadId);
322
322
  return result;
323
323
  }
324
- /** Uses the active writer's catalog; never upgrades requested settings to observations. */
325
- async validateExecutorPolicy(sessionId, policy) {
326
- const resource = this.sessions.get(sessionId);
327
- if (!resource)
328
- throw new Error('EXECUTOR_CATALOG_UNAVAILABLE');
324
+ /** The same session-owned catalog source for health and pre-dispatch validation. */
325
+ async readExecutorPolicyCatalog(input) {
326
+ const resource = this.sessions.get(input.sessionId);
327
+ if (!resource?.active)
328
+ return { kind: 'unavailable', code: 'RUNTIME_UNAVAILABLE' };
329
+ if (!input.rootThreadId || resource.threadId !== input.rootThreadId)
330
+ return { kind: 'unavailable', code: 'ROOT_BINDING_MISMATCH' };
329
331
  let timer;
330
332
  let catalog;
331
333
  try {
@@ -336,12 +338,36 @@ export class CodexSessionRuntime {
336
338
  }),
337
339
  ]));
338
340
  }
341
+ catch {
342
+ return { kind: 'unavailable', code: 'CATALOG_UNAVAILABLE' };
343
+ }
339
344
  finally {
340
345
  if (timer)
341
346
  clearTimeout(timer);
342
347
  }
343
- if (!catalog || this.sessions.get(sessionId) !== resource || !resource.active)
348
+ if (this.sessions.get(input.sessionId) !== resource ||
349
+ !resource.active ||
350
+ resource.threadId !== input.rootThreadId)
351
+ return { kind: 'unavailable', code: 'CONTEXT_CHANGED' };
352
+ if (!catalog)
353
+ return { kind: 'unavailable', code: 'CATALOG_UNAVAILABLE' };
354
+ return {
355
+ kind: 'observed',
356
+ source: 'runtime-model-list',
357
+ observedAt: new Date().toISOString(),
358
+ catalog,
359
+ };
360
+ }
361
+ /** Uses the active writer's catalog; never upgrades requested settings to observations. */
362
+ async validateExecutorPolicy(sessionId, policy) {
363
+ const resource = this.sessions.get(sessionId);
364
+ const result = await this.readExecutorPolicyCatalog({
365
+ sessionId,
366
+ rootThreadId: resource?.threadId ?? '',
367
+ });
368
+ if (result.kind !== 'observed')
344
369
  throw new Error('EXECUTOR_CATALOG_UNAVAILABLE');
370
+ const catalog = result.catalog;
345
371
  const model = catalog.models.find((entry) => entry.id === policy.model);
346
372
  if (!model)
347
373
  throw new Error('EXECUTOR_MODEL_UNAVAILABLE');
@@ -476,6 +502,62 @@ export class CodexSessionRuntime {
476
502
  this.historyReads.delete(session.id);
477
503
  }
478
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
+ }
479
561
  /** Bounded reconciliation port for direct spawned children only. */
480
562
  async listDirectChildren(session) {
481
563
  if (!session.threadId)
@@ -519,19 +601,58 @@ export class CodexSessionRuntime {
519
601
  process.close();
520
602
  }
521
603
  }
522
- async listDirectChildrenFromProcess(process, parentThreadId) {
604
+ async listDirectChildrenFromProcess(process, parentThreadId, current) {
523
605
  const children = [];
524
606
  const childIds = new Set();
525
607
  const cursors = new Set();
526
608
  let cursor;
527
609
  for (let page = 0; page < 4 && childIds.size < 64; page += 1) {
610
+ if (current && !current())
611
+ throw new Error('EXECUTOR_TOPOLOGY_CHANGED');
528
612
  const result = await process.rpc.request('thread/list', {
529
613
  parentThreadId,
530
614
  ...(cursor ? { cursor } : {}),
531
615
  });
532
616
  const response = result && typeof result === 'object' ? result : null;
533
617
  const data = response && Array.isArray(response.data) ? response.data : [];
534
- 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) => {
535
656
  if (!candidate || typeof candidate !== 'object')
536
657
  return [];
537
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 the current session’s authoritative Org execution health, using the same controller state as Mobile. 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.4",
3
+ "version": "0.55.6",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",