gestalt-mobile 0.55.2 → 0.55.4

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
@@ -102,22 +102,34 @@ session-relative interpretation.
102
102
 
103
103
  ### Versioned model policy
104
104
 
105
- The `l1-model-policy-v1` capability and packaged `modelPolicyContract` describe
106
- schema validation and retention. `runtimeEnforcement` is `false`. When a
107
- versioned plan has a retained canonical executor, `gestalt_org_plan_health`
108
- can compare its configured thread model and effort with the requested L1 policy.
109
- This uses bounded thread metadata and the owning runtime's model catalog, with
110
- no transcript retrieval or extra model-probe turn. Missing values stay unknown;
111
- matching configuration does not admit automatic execution.
112
-
113
- Mobile rejects unsupported versioned-policy automation at enable,
114
- supervision-start, automatic root dispatch, and direct executor resume. Manual
115
- review, repair input and model selection remain available; unrelated legacy
116
- sessions retain their existing behavior. Native child creation inside manual or
117
- already-running turns is outside this guarantee. Strict runtime attestation,
118
- runtime-issued settings revisions and native child pre-spawn enforcement require
119
- separate integration work. They are deferred capabilities, not installation
120
- prerequisites, and package presence does not establish them.
105
+ Version-1 plans separate requested model choices from assurance. Existing plans
106
+ without `#+MODEL_POLICY_ASSURANCE` use disclosed **configured compatibility**;
107
+ their policy metadata and file bytes need no migration. An explicit
108
+ `#+MODEL_POLICY_ASSURANCE: configured` selects the same mode. Mobile validates
109
+ allowed models/efforts and higher-effort necessity, checks the active runtime
110
+ catalog before versioned root dispatch, and directs the root to launch the exact
111
+ L1 model/effort through supported overrides with inherited sandbox and approval
112
+ policy. Automatic executor resumes use that L1 policy rather than session defaults.
113
+
114
+ `#+MODEL_POLICY_ASSURANCE: runtime-attested` explicitly requires strict runtime
115
+ receipts. The current adapter cannot supply runtime-issued settings revisions;
116
+ strict plans fail with `RUNTIME_ATTESTATION_UNAVAILABLE` and remain strict until
117
+ the user authorizes a change. Repeated approvals or attention resolution cannot
118
+ provide that capability. Manual Off is independently respected. Legacy plans
119
+ without model policy keep their existing behavior.
120
+
121
+ `gestalt_org_plan_health` reports `executionAdmission.allowed`, configured
122
+ assurance and `runtimeEnforcement:false`. Its `modelPolicy` evidence separately
123
+ reports `admissionScope: runtime-attestation`, `admitted:false`, `attested:false`,
124
+ requested values and observed configured thread settings. Unknown values remain
125
+ null, never copied from requests. A configured match is not runtime attestation.
126
+ Controller-owned resume guards reject stale identities and observed mismatches,
127
+ and recheck authority immediately before dispatch and after thread recovery.
128
+ Native collaboration spawn/followup calls remain cooperatively root-supervised;
129
+ Mobile does not intercept them or guarantee universal pre-spawn enforcement.
130
+ One writer per L1, independent review, evidence gates, checkpoint continuation
131
+ and terminal whole-branch review remain required. See
132
+ [update and rollback guidance](docs/org-plan-policy-compatibility.md).
121
133
 
122
134
  ## Skill profiles
123
135
 
@@ -17,6 +17,7 @@ import WebSocket from 'ws';
17
17
  import { composeRelayApp } from './composition.js';
18
18
  import { autopilotExecutorLaunchPrompt } from './features/autopilot/application/policy.js';
19
19
  import { CodexJsonRpcError } from './platform/codex/json-rpc-client.js';
20
+ import { CodexSessionRuntime } from './platform/codex/session-runtime.js';
20
21
  import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-store.js';
21
22
  import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
22
23
  import { authorizationSessionId, authorizedDeviceId, localOwnerId, webAuthnCredentialId, } from './features/auth/domain/identifiers.js';
@@ -182,14 +183,17 @@ const acceptedL1WithNextTodoPlanText = () => `${completedAutopilotPlanText()}
182
183
  - Tests :: Exercise the next continuation.
183
184
  - Done when :: The next L1 starts exactly once.
184
185
  `;
185
- async function installAutopilotPlan(app, sessionId, workspacePath, name, childState = 'TODO', reason = 'supervision-start') {
186
+ async function installAutopilotPlan(app, sessionId, workspacePath, name, childState = 'TODO', reason = 'supervision-start', source) {
186
187
  const planPath = join(workspacePath, `${name}.org`);
187
- await writeFile(planPath, autopilotPlanText(childState));
188
+ await writeFile(planPath, source ?? autopilotPlanText(childState));
188
189
  await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, sessionId), planPath), JSON.stringify({
189
190
  schemaVersion: 1,
190
191
  planPath,
191
192
  reason,
192
193
  updatedAt: new Date().toISOString(),
194
+ ...(source?.includes('#+MODEL_POLICY_VERSION: 1')
195
+ ? { modelPolicyVersion: 1, requiredCapabilities: ['l1-model-policy-v1'] }
196
+ : {}),
193
197
  }));
194
198
  await expect
195
199
  .poll(async () => (await app.inject(`/api/sessions/${sessionId}/plan`)).statusCode)
@@ -197,7 +201,7 @@ async function installAutopilotPlan(app, sessionId, workspacePath, name, childSt
197
201
  expect((await app.inject({ method: 'POST', url: `/api/sessions/${sessionId}/restore` })).statusCode).toBe(200);
198
202
  return planPath;
199
203
  }
200
- async function createProductionAutopilotFixture(overrides = {}) {
204
+ async function createProductionAutopilotFixture(overrides = {}, source) {
201
205
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
202
206
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
203
207
  ownTemporaryPaths(root, dataDir);
@@ -222,7 +226,7 @@ async function createProductionAutopilotFixture(overrides = {}) {
222
226
  state: 'ready',
223
227
  threadId: expect.any(String),
224
228
  }));
225
- await installAutopilotPlan(app, sessionId, workspacePath, 'autopilot');
229
+ await installAutopilotPlan(app, sessionId, workspacePath, 'autopilot', 'TODO', 'supervision-start', source);
226
230
  return { app, dataDir, handles, root, sessionId, workspacePath };
227
231
  }
228
232
  async function holdCheckpointRequest(fixture, timers, requestId, expectHeld = true, compact = false) {
@@ -383,8 +387,259 @@ async function createUnauthorizedProductionApp(root, dataDir) {
383
387
  }
384
388
  describe('production composition', () => {
385
389
  describeCompositionConcern('autopilot', () => {
386
- it.each(['idle', 'active', 'retry'])('delivers acknowledged attention guidance to the %s supervisor and retains its explanation beyond the journal tail', async (mode) => {
387
- const fixture = await createProductionAutopilotFixture();
390
+ const versionedText = (state = 'TODO', strict = false) => '#+MODEL_POLICY_VERSION: 1\n' +
391
+ (strict ? '#+MODEL_POLICY_ASSURANCE: runtime-attested\n' : '') +
392
+ autopilotPlanText(state).replace(':REVIEW_STATUS: UNREVIEWED', `:REVIEW_STATUS: UNREVIEWED
393
+ :MODEL: gpt-6.1-sol
394
+ :REASONING_EFFORT: medium
395
+ :MODEL_RATIONALE: Composition contract with explicit launch choices.
396
+ :MODEL_FALLBACKS: none
397
+ :MODEL_ESCALATION_TRIGGER: A focused invariant fails.`);
398
+ const policyCatalog = {
399
+ data: [{ id: 'gpt-6.1-sol', supportedReasoningEfforts: [{ reasoningEffort: 'medium' }] }],
400
+ };
401
+ it('activates existing v1, validates catalog, dispatches launch instructions and records a report checkpoint', async () => {
402
+ const timers = [];
403
+ const fixture = await createProductionAutopilotFixture({
404
+ autopilotSchedule: (callback) => {
405
+ const timer = { callback, cancelled: false };
406
+ timers.push(timer);
407
+ return () => {
408
+ timer.cancelled = true;
409
+ };
410
+ },
411
+ }, versionedText());
412
+ const { app, sessionId, handles, workspacePath } = fixture;
413
+ onTestFinished(() => app.close());
414
+ for (const handle of handles)
415
+ handle.respond = (method) => (method === 'model/list' ? policyCatalog : undefined);
416
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
417
+ autopilot: {
418
+ enabled: true,
419
+ executionAdmission: { allowed: true, assurance: 'configured', runtimeEnforcement: false },
420
+ },
421
+ });
422
+ timers.find((timer) => !timer.cancelled).callback();
423
+ await vi.waitFor(() => expect(handles
424
+ .flatMap((handle) => handle.requests)
425
+ .filter((call) => call.method === 'turn/start')).toHaveLength(1));
426
+ const handle = handles.find((candidate) => candidate.requests.some((call) => call.method === 'turn/start'));
427
+ const start = handle.requests.find((call) => call.method === 'turn/start');
428
+ expect(start.params).toMatchObject({
429
+ input: [
430
+ {
431
+ text: expect.stringContaining('explicit model gpt-6.1-sol and reasoning_effort medium'),
432
+ },
433
+ ],
434
+ });
435
+ expect(JSON.stringify(start.params)).not.toContain('reasoning_effort high');
436
+ const session = (await app.inject(`/api/sessions/${sessionId}`)).json();
437
+ // Synthetic executor report: real composition validates the authoritative plan boundary.
438
+ await writeFile(join(workspacePath, 'autopilot.org'), versionedText('DONE'));
439
+ const result = await handle.request({
440
+ id: 9901,
441
+ method: 'item/tool/call',
442
+ params: {
443
+ threadId: session.threadId,
444
+ turnId: session.activeTurnId,
445
+ tool: 'gestalt_org_plan_checkpoint',
446
+ arguments: { kind: 'l2Completed' },
447
+ },
448
+ });
449
+ expect(result).toEqual(toOrgPlanCheckpointToolResponse('recorded'));
450
+ const db = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
451
+ try {
452
+ expect(db
453
+ .prepare("SELECT count(*) AS n FROM session_events WHERE type='org-plan.step-checkpointed'")
454
+ .get()).toMatchObject({ n: 1 });
455
+ }
456
+ finally {
457
+ db.close();
458
+ }
459
+ handle.notify({
460
+ method: 'turn/completed',
461
+ params: {
462
+ threadId: session.threadId,
463
+ turn: { id: session.activeTurnId, status: 'completed' },
464
+ },
465
+ });
466
+ await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${sessionId}`)).json().activeTurnId).toBeNull());
467
+ expect((await app.inject(`/api/sessions/${sessionId}/plan`)).json().steps[0]).toMatchObject({
468
+ reviewStatus: 'UNREVIEWED',
469
+ });
470
+ expect(handles.flatMap((handle) => handle.requests).filter((call) => call.method === 'turn/start')).toHaveLength(1);
471
+ });
472
+ it('keeps explicit strict v1 blocked at production activation without scheduling', async () => {
473
+ const timers = [];
474
+ const f = await createProductionAutopilotFixture({
475
+ autopilotSchedule: (callback) => {
476
+ timers.push(callback);
477
+ return () => { };
478
+ },
479
+ }, versionedText('TODO', true));
480
+ onTestFinished(() => f.app.close());
481
+ const response = await f.app.inject({
482
+ method: 'PUT',
483
+ url: `/api/sessions/${f.sessionId}/autopilot`,
484
+ payload: { enabled: true },
485
+ });
486
+ expect(response.statusCode).toBe(409);
487
+ expect(response.json()).toMatchObject({
488
+ reason: 'RUNTIME_ATTESTATION_UNAVAILABLE',
489
+ action: expect.stringContaining('explicitly requires'),
490
+ });
491
+ expect(timers).toHaveLength(0);
492
+ expect(f.handles
493
+ .flatMap((handle) => handle.requests)
494
+ .filter((call) => call.method === 'turn/start')).toHaveLength(0);
495
+ });
496
+ it.each([
497
+ 'match',
498
+ 'mismatch',
499
+ 'off-during-read',
500
+ 'policy-during-read',
501
+ 'same-plan-during-read',
502
+ 'off-on-during-recovery',
503
+ ])('guards configured executor dispatch in production: %s', async (scenario) => {
504
+ const timers = [];
505
+ const f = await createProductionAutopilotFixture({
506
+ autopilotActivity: (sessionId) => {
507
+ const observedAt = new Date().toISOString();
508
+ return {
509
+ sessionId,
510
+ rootThreadId: 'thread-1',
511
+ root: {
512
+ state: 'idle',
513
+ reason: 'turnCompleted',
514
+ observedAt,
515
+ lastActivityAt: observedAt,
516
+ },
517
+ subagents: [
518
+ {
519
+ id: 'child-1',
520
+ threadId: 'child-1',
521
+ taskPath: '/root/l1',
522
+ canonicalTaskName: 'l1',
523
+ canonicalPosition: 'L1',
524
+ continuationGeneration: 1,
525
+ outcome: 'partial',
526
+ ownedProcesses: [],
527
+ state: 'idle',
528
+ reason: 'turnCompleted',
529
+ observedAt,
530
+ lastActivityAt: observedAt,
531
+ },
532
+ ],
533
+ aggregateSubagents: 'idle',
534
+ confidence: 'fresh',
535
+ };
536
+ },
537
+ autopilotSchedule: (callback) => {
538
+ const timer = { callback, cancelled: false };
539
+ timers.push(timer);
540
+ return () => {
541
+ timer.cancelled = true;
542
+ };
543
+ },
544
+ }, versionedText());
545
+ onTestFinished(() => f.app.close());
546
+ const actualRootThreadId = (await f.app.inject(`/api/sessions/${f.sessionId}`)).json()
547
+ .threadId;
548
+ const pendingRead = Promise.withResolvers();
549
+ const pendingRecovery = Promise.withResolvers();
550
+ const resumeOperation = vi.spyOn(CodexSessionRuntime.prototype, 'startExecutorTurn');
551
+ onTestFinished(() => {
552
+ pendingRead.resolve({});
553
+ pendingRecovery.resolve({});
554
+ resumeOperation.mockRestore();
555
+ });
556
+ let sawRead = false, sawRecovery = false;
557
+ let childStarts = 0;
558
+ for (const handle of f.handles)
559
+ handle.respond = async (method, params) => {
560
+ if (method === 'model/list')
561
+ return policyCatalog;
562
+ if (method === 'thread/read' && params.threadId === 'child-1') {
563
+ sawRead = true;
564
+ if (['off-during-read', 'policy-during-read', 'same-plan-during-read'].includes(scenario))
565
+ await pendingRead.promise;
566
+ return {
567
+ thread: {
568
+ id: 'child-1',
569
+ parentThreadId: actualRootThreadId,
570
+ source: { subAgent: { thread_spawn: { agent_path: '/root/l1' } } },
571
+ status: { type: 'idle' },
572
+ model: scenario === 'mismatch' ? 'gpt-6-sol' : 'gpt-6.1-sol',
573
+ reasoningEffort: 'medium',
574
+ agentRole: 'default',
575
+ },
576
+ };
577
+ }
578
+ if (method === 'turn/start' && params.threadId === 'child-1') {
579
+ childStarts++;
580
+ if (scenario === 'off-on-during-recovery')
581
+ throw new CodexJsonRpcError(-32600, 'thread not found: child-1');
582
+ }
583
+ if (method === 'thread/resume' &&
584
+ params.threadId === 'child-1') {
585
+ sawRecovery = true;
586
+ await pendingRecovery.promise;
587
+ }
588
+ return undefined;
589
+ };
590
+ timers.find((timer) => !timer.cancelled).callback();
591
+ await vi.waitFor(() => expect(sawRead).toBe(true));
592
+ if (scenario === 'off-during-read' || scenario === 'off-on-during-recovery') {
593
+ if (scenario === 'off-on-during-recovery')
594
+ await vi.waitFor(() => expect(sawRecovery).toBe(true));
595
+ await f.app.inject({
596
+ method: 'PUT',
597
+ url: `/api/sessions/${f.sessionId}/autopilot`,
598
+ payload: { enabled: false },
599
+ });
600
+ if (scenario === 'off-on-during-recovery')
601
+ await f.app.inject({
602
+ method: 'PUT',
603
+ url: `/api/sessions/${f.sessionId}/autopilot`,
604
+ payload: { enabled: true },
605
+ });
606
+ }
607
+ if (scenario === 'policy-during-read') {
608
+ await writeFile(join(f.workspacePath, 'autopilot.org'), versionedText().replace(':MODEL: gpt-6.1-sol', ':MODEL: gpt-6-sol'));
609
+ await f.app.inject(`/api/sessions/${f.sessionId}/plan`);
610
+ }
611
+ if (scenario === 'same-plan-during-read') {
612
+ const planPath = join(f.workspacePath, 'autopilot.org');
613
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(f.workspacePath, f.sessionId), planPath), JSON.stringify({
614
+ schemaVersion: 1,
615
+ planPath,
616
+ reason: 'supervision-start',
617
+ updatedAt: new Date().toISOString(),
618
+ modelPolicyVersion: 1,
619
+ requiredCapabilities: ['l1-model-policy-v1'],
620
+ }));
621
+ await f.app.inject(`/api/sessions/${f.sessionId}/plan`);
622
+ }
623
+ pendingRead.resolve({});
624
+ pendingRecovery.resolve({});
625
+ if (scenario === 'match' || scenario === 'same-plan-during-read') {
626
+ await vi.waitFor(() => expect(childStarts).toBe(1));
627
+ const call = f.handles
628
+ .flatMap((handle) => handle.requests)
629
+ .find((call) => call.method === 'turn/start');
630
+ expect(call?.params).toMatchObject({
631
+ threadId: 'child-1',
632
+ model: 'gpt-6.1-sol',
633
+ effort: 'medium',
634
+ });
635
+ }
636
+ else {
637
+ await vi.waitFor(() => expect(resumeOperation.mock.settledResults[0]?.type).toBe('rejected'));
638
+ expect(childStarts).toBe(scenario === 'off-on-during-recovery' ? 1 : 0);
639
+ }
640
+ });
641
+ it.each(['idle', 'active', 'retry', 'configured'])('delivers acknowledged attention guidance to the %s supervisor and retains its explanation beyond the journal tail', async (mode) => {
642
+ const fixture = await createProductionAutopilotFixture({}, mode === 'configured' ? versionedText() : undefined);
388
643
  const { app, sessionId, handles } = fixture;
389
644
  onTestFinished(() => app.close());
390
645
  const handle = handles.filter((value) => value.request).at(-1);
@@ -88,6 +88,7 @@ import { agentCapacityRecoveryToolResponse } from '../shared/contracts/agent-cap
88
88
  import { isOrgPlanHealthCall } from '../shared/contracts/org-plan-health.js';
89
89
  import { ExecutorModelEvidenceReader } from './features/plans/application/executor-model-evidence.js';
90
90
  import { requireModelPolicyAdmission } from './features/plans/domain/model-policy-admission.js';
91
+ import { currentExecutableL1Index } from './features/plans/domain/supervised-plan.js';
91
92
  import { pwaIconUrl } from './features/pwa/register-routes.js';
92
93
  const generatedProtocolVersion = 'codex-cli 0.144.3';
93
94
  const checkpointDiagnostic = debuglog('gestalt-mobile:checkpoint');
@@ -313,14 +314,22 @@ export async function composeRelayApp(options) {
313
314
  const writer = await runtime.ensureWriter(session, new Date().toISOString());
314
315
  if (!current() || writer.session.activeTurnId || blockingInteractions(sessionId).length)
315
316
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
317
+ const selectedPlan = supervisedPlans.find(sessionId);
318
+ const selectedPlanFence = JSON.stringify(selectedPlan);
319
+ const selectedPolicy = selectedPlan?.modelPolicyVersion === 1
320
+ ? selectedPlan.steps[currentExecutableL1Index(selectedPlan)]?.modelPolicy
321
+ : undefined;
322
+ if (selectedPolicy)
323
+ await runtime.validateExecutorPolicy(sessionId, selectedPolicy);
316
324
  await options.autopilotBeforeTurnAccepted?.({ sessionId, controlId });
317
325
  requireOrgExecutionAdmission(sessionId);
318
326
  if (!current() ||
327
+ JSON.stringify(supervisedPlans.find(sessionId)) !== selectedPlanFence ||
319
328
  sessions.find(sessionId)?.activeTurnId ||
320
329
  blockingInteractions(sessionId).length)
321
330
  throw new Error('AUTOPILOT_START_UNAVAILABLE');
322
331
  const continuationPrompt = launchIdentity
323
- ? autopilotExecutorLaunchPrompt(launchIdentity)
332
+ ? autopilotExecutorLaunchPrompt(launchIdentity, supervisedPlans.find(sessionId))
324
333
  : AUTOPILOT_CONTINUATION_PROMPT;
325
334
  const recovery = autopilotStore.find(sessionId);
326
335
  const executorRecovery = recovery?.supervision?.outcome === 'probeRequired' &&
@@ -1097,7 +1106,42 @@ export async function composeRelayApp(options) {
1097
1106
  });
1098
1107
  },
1099
1108
  verify: (rpc, threadId, state) => capabilities.verify(rpc, threadId, state),
1100
- }, requireOrgExecutionAdmission)
1109
+ }, async (sessionId, threadId) => {
1110
+ requireOrgExecutionAdmission(sessionId);
1111
+ const plan = supervisedPlans.find(sessionId);
1112
+ if (plan?.modelPolicyVersion !== 1)
1113
+ return;
1114
+ const planFence = JSON.stringify(plan);
1115
+ const fence = () => {
1116
+ const state = autopilotStore.find(sessionId);
1117
+ return state?.requestedEnabled && state.executor?.threadId === threadId
1118
+ ? JSON.stringify([state.generation, state.planIdentity, state.executor])
1119
+ : null;
1120
+ };
1121
+ const before = fence();
1122
+ const assertCurrent = () => {
1123
+ requireOrgExecutionAdmission(sessionId);
1124
+ if (!before ||
1125
+ fence() !== before ||
1126
+ JSON.stringify(supervisedPlans.find(sessionId)) !== planFence ||
1127
+ blockingInteractions(sessionId).length)
1128
+ throw new Error('EXECUTOR_AUTHORITY_CHANGED');
1129
+ };
1130
+ assertCurrent();
1131
+ const report = await executorModelEvidence.read(sessionId);
1132
+ assertCurrent();
1133
+ if (!report ||
1134
+ report.child.threadId !== threadId ||
1135
+ report.configuration === 'mismatch' ||
1136
+ [
1137
+ 'CONTROLLER_BINDING_INVALID',
1138
+ 'CONTEXT_CHANGED',
1139
+ 'CHILD_BINDING_MISMATCH',
1140
+ 'OBSERVATION_CHANGED',
1141
+ ].includes(report.code))
1142
+ throw new Error(`EXECUTOR_POLICY_BLOCKED:${report?.code ?? 'CHILD_BINDING_UNKNOWN'}`);
1143
+ return { ...report.requested, assertCurrent };
1144
+ })
1101
1145
  : null;
1102
1146
  const handleKimiNotification = (sessionId, event) => {
1103
1147
  const occurredAt = new Date().toISOString();
@@ -9,8 +9,11 @@ export const AUTOPILOT_PROMPT_VERSION = 'v13';
9
9
  export const AUTOPILOT_CONTINUATION_PROMPT = 'Inspect the active supervised Org Plan. Refer to every L1 as L<a> and each nested L2 as L<a>.<b>, using one-based positions. Spawn exactly one executor per L1 and pass the exact literal task_name l<a>: l1 for L1, l2 for L2, and so on. Never create an L2-specific task name or append a title, role, nickname, plan name, or generated label. A validated DONE L2 and an accepted L1 are mandatory answer boundaries. The corresponding gestalt_org_plan_checkpoint call must be the last tool call of that root turn: immediately emit exactly one boundary final and end the turn, without followup_task, review, executor launch, or later milestone work. An accepted L1 always ends the root turn with a chat answer: never continue into the next L1 or emit post-acceptance documentation as commentary. Roll up commentary, files, verification, and commands since the previous boundary into that one answer; all later milestone activity belongs to a new root turn. On this later Autopilot turn, resume the same executor after an L2 boundary or launch exactly one fresh canonical executor for the next L1 after an accepted-L1 boundary. Treat a status question as an interruption: answer briefly, then perform the applicable continuation in the same turn. Before sending any blocker response or yielding because progress cannot continue safely, call gestalt_org_plan_attention for the matching decision-table blocker; never rely on blocker prose as the signal. When explicit human permission is required for a physical executor replacement, include executorReplacement with the exact canonicalTaskName; Mobile alone computes and persists the physical generation. Do not call attention for routine progress or a recoverable failure. Before yielding for known long work, call gestalt_autopilot_wait_lease version 2 with relevant observable wake conditions and a bounded maxWaitMs; it is one episode, so reassess before registering another in a later turn. Yield only when its response contains accepted:true; accepted:false means no continuation was registered and requires same-turn supervision. For GitHub PR CI, start an owned gh pr checks --watch process and lease processExited plus processResultAvailable while it runs. Timestamp watcher state-change and terminal observations in UTC; distinguish observation time from upstream updated_at and process exit time. When the Autopilot probe is active, register the compatible wait lease, declare genuine attention, or immediately do actionable work; never acknowledge waiting in prose. Do not send a status-only response.';
10
10
  export const AUTOPILOT_EXECUTOR_CONTINUATION_PROMPT = 'Continue the same assigned Org L1 from its durable state. A prior turn ending did not complete the objective. Consume any supplied process result and take the next legal L2 action. Whenever an L2 reaches DONE, return its concise structured evidence and end the executor turn so the root can publish that mandatory answer boundary. Also report at the L1 review boundary or through structured attention.';
11
11
  /** Builds a physical launch instruction while keeping durable L1 identity canonical. */
12
- export function autopilotExecutorLaunchPrompt(identity) {
13
- const launch = `Launch task_name ${identity.taskName} for canonical ${identity.canonicalPosition} with agent_type org-plan-executor and reasoning_effort high; the profile selects gpt-5.6-terra by default, so do not override its model. Retain the canonical label in status and review output.`;
12
+ export function autopilotExecutorLaunchPrompt(identity, plan) {
13
+ const policy = plan?.steps.find((_, index) => `L${index + 1}` === identity.canonicalPosition)?.modelPolicy;
14
+ const launch = policy
15
+ ? `Launch task_name ${identity.taskName} for canonical ${identity.canonicalPosition}, preferring agent_type default, fork_turns none, explicit model ${policy.model} and reasoning_effort ${policy.reasoningEffort}. If explicit overrides are unavailable, use the verified fixed org-plan-executor role only when both pins exactly match ${policy.model}/${policy.reasoningEffort}, omitting ineffective overrides. Load the executor duties and full L1 assignment from the Org-plan launch contract. Validate actual host support and sandbox/approval inheritance before spawning; unsupported routes are capability blockers. Assurance is configured compatibility: unavailable runtime metadata remains unknown and does not require repeated human approval. Reject observed settings mismatches; never call requested settings observed or runtime-enforced. Preserve one writer, independent review, checkpoint and terminal review gates.`
16
+ : `Launch task_name ${identity.taskName} for canonical ${identity.canonicalPosition} with agent_type org-plan-executor and reasoning_effort high; the profile selects gpt-5.6-terra by default, so do not override its model. Retain the canonical label in status and review output.`;
14
17
  if (identity.generation === 1)
15
18
  return `${AUTOPILOT_CONTINUATION_PROMPT} ${launch}`;
16
19
  return `${AUTOPILOT_CONTINUATION_PROMPT} ${launch} This exact replacement generation ${identity.generation} is durably authorized by Mobile; do not infer another generation from this prompt or the roster; the durable ${identity.canonicalTaskName} slot may remain reserved. Do not reuse that task_name or attempt to change an existing agent's model in place. Interrupt the previous physical executor if it is still running, then spawn the authorized ${identity.taskName}. Transfer sole ${identity.canonicalPosition} ownership and continue from its durable Org Plan and worktree state.`;
@@ -2830,7 +2830,9 @@ export class AutopilotCoordinator {
2830
2830
  observedAt: now,
2831
2831
  }),
2832
2832
  supervisionDelta: this.supervisionDelta(next),
2833
- ...(!admission.allowed ? { executionAdmission: admission } : {}),
2833
+ ...(admission.allowed && admission.scope === 'legacy'
2834
+ ? {}
2835
+ : { executionAdmission: admission }),
2834
2836
  };
2835
2837
  }
2836
2838
  modelPolicyAdmission(sessionId) {
@@ -3325,6 +3327,17 @@ function fingerprint(plan) {
3325
3327
  step.state,
3326
3328
  step.reviewStatus,
3327
3329
  step.children.map((child) => [child.id, child.state]),
3330
+ ...(plan.modelPolicyVersion
3331
+ ? [
3332
+ {
3333
+ version: plan.modelPolicyVersion,
3334
+ assurance: plan.modelPolicyAssurance ?? 'configured',
3335
+ model: step.modelPolicy?.model,
3336
+ reasoningEffort: step.modelPolicy?.reasoningEffort,
3337
+ necessity: step.modelPolicy?.necessity,
3338
+ },
3339
+ ]
3340
+ : []),
3328
3341
  ])));
3329
3342
  }
3330
3343
  function boundedUnique(values, limit) {
@@ -74,7 +74,10 @@ export class ExecutorModelEvidenceReader {
74
74
  catalogRevisionSource: 'normalized-content-digest',
75
75
  configuration: 'unknown',
76
76
  admitted: false,
77
+ attested: false,
78
+ admissionScope: 'runtime-attestation',
77
79
  runtimeEnforcement: false,
80
+ assurance: context.plan.modelPolicyAssurance ?? 'configured',
78
81
  code: 'CHILD_BINDING_UNKNOWN',
79
82
  unknown: [],
80
83
  };
@@ -109,7 +112,7 @@ export class ExecutorModelEvidenceReader {
109
112
  (executor.assignment.threadId !== executor.threadId ||
110
113
  executor.assignment.taskPath !== executor.taskPath ||
111
114
  executor.assignment.generation !== identity.generation)))
112
- return finish('CHILD_BINDING_UNKNOWN');
115
+ return finish('CONTROLLER_BINDING_INVALID');
113
116
  const fence = contextFence(context);
114
117
  let result;
115
118
  try {
@@ -175,6 +178,7 @@ function contextFence(context) {
175
178
  root: context?.rootThreadId,
176
179
  plan: context?.planIdentity,
177
180
  policyVersion: context?.plan?.modelPolicyVersion,
181
+ assurance: context?.plan?.modelPolicyAssurance,
178
182
  l1: step?.id,
179
183
  state: step?.state,
180
184
  policy: step?.modelPolicy ? executionPolicyDigest(step.modelPolicy) : null,
@@ -25,7 +25,7 @@ export function parseModelPolicy(properties, level, version) {
25
25
  const invalid = () => {
26
26
  throw new Error('INVALID_MODEL_POLICY');
27
27
  };
28
- if (properties.has('MODEL_POLICY_VERSION'))
28
+ if (properties.has('MODEL_POLICY_VERSION') || properties.has('MODEL_POLICY_ASSURANCE'))
29
29
  invalid();
30
30
  if (declared.length && (level === 2 || version === undefined))
31
31
  invalid();
@@ -26,6 +26,15 @@ export function parseSupervisedPlan(input) {
26
26
  declarations.some(({ line, index }) => line !== '#+MODEL_POLICY_VERSION: 1' || index >= firstHeading))
27
27
  return unavailable('INVALID_MODEL_POLICY');
28
28
  const modelPolicyVersion = declarations.length ? 1 : undefined;
29
+ const assurances = lines
30
+ .map((line, index) => ({ line, index }))
31
+ .filter(({ line }) => /^#\+MODEL_POLICY_ASSURANCE:/i.test(line));
32
+ if (assurances.length > 1 ||
33
+ assurances.some(({ line, index }) => !modelPolicyVersion ||
34
+ index >= firstHeading ||
35
+ !/^#\+MODEL_POLICY_ASSURANCE: (configured|runtime-attested)$/.test(line)))
36
+ return unavailable('INVALID_MODEL_POLICY');
37
+ const modelPolicyAssurance = assurances[0]?.line.split(': ')[1];
29
38
  for (let index = 0; index < lines.length;) {
30
39
  const line = lines[index];
31
40
  const metadataMatch = /^#\+([A-Z_]+):(?:[ \t](.*))?$/.exec(line);
@@ -138,6 +147,7 @@ export function parseSupervisedPlan(input) {
138
147
  ...(metadata.has('DATE') ? { date: metadata.get('DATE') } : {}),
139
148
  ...(metadata.has('KEYWORDS') ? { keywords: metadata.get('KEYWORDS') } : {}),
140
149
  ...(modelPolicyVersion ? { modelPolicyVersion } : {}),
150
+ ...(modelPolicyAssurance ? { modelPolicyAssurance } : {}),
141
151
  steps: built,
142
152
  totalSteps: allSteps.length,
143
153
  doneSteps: allSteps.filter((step) => step.state === 'DONE').length,
@@ -9,7 +9,9 @@ export function assessModelPolicyAdmission(plan, status = 'legacy') {
9
9
  allowed: false,
10
10
  code: 'AUTOPILOT_MODEL_POLICY_UNAVAILABLE',
11
11
  reason,
12
- action: 'Keep Org automation off until a compatible runtime can attest the canonical executor settings. Manual plan review and repair remain available.',
12
+ action: reason === 'RUNTIME_ATTESTATION_UNAVAILABLE'
13
+ ? 'This plan explicitly requires runtime-attested assurance. This adapter has no settings receipt/revision API. Use a runtime with attestation support, or explicitly authorize changing MODEL_POLICY_ASSURANCE to configured; repeating approval cannot provide attestation.'
14
+ : 'Repair the plan policy or its publication, then retry supervision. Manual Off and user authorization are separate from policy admission.',
13
15
  });
14
16
  if (status === 'unavailable')
15
17
  return blocked('POLICY_PROJECTION_UNAVAILABLE');
@@ -23,10 +25,35 @@ export function assessModelPolicyAdmission(plan, status = 'legacy') {
23
25
  return blocked('POLICY_FIELDS_INVALID');
24
26
  if (plan.steps.some((step) => !['gpt-6-luna', 'gpt-6-sol', 'gpt-6.1-sol'].includes(step.modelPolicy.model)))
25
27
  return blocked('MODEL_PROHIBITED');
26
- // Configured settings and locally derived digests from the current adapter do
27
- // not satisfy the Agents runtime receipt/revision contract. No bypass flag or
28
- // fixture can turn this prerequisite into live admission.
29
- return blocked('RUNTIME_ATTESTATION_UNAVAILABLE');
28
+ if (plan.steps.some((step) => {
29
+ const policy = step.modelPolicy;
30
+ const necessity = policy.necessity;
31
+ return (!['medium', 'high', 'xhigh'].includes(policy.reasoningEffort) ||
32
+ (policy.reasoningEffort === 'medium'
33
+ ? necessity !== null
34
+ : !necessity ||
35
+ !['unresolved-correctness', 'specific-reasoning'].includes(necessity.kind) ||
36
+ ![
37
+ necessity.whyMediumInadequate,
38
+ necessity.evidence,
39
+ necessity.affectedScope,
40
+ necessity.returnToMedium,
41
+ ...(policy.reasoningEffort === 'xhigh' ? [necessity.scopeReassessment] : []),
42
+ ].every((value) => typeof value === 'string' && value.trim())));
43
+ }))
44
+ return blocked('EFFORT_UNSUPPORTED');
45
+ const assurance = plan.modelPolicyAssurance ?? 'configured';
46
+ if (!['configured', 'runtime-attested'].includes(assurance))
47
+ return blocked('ASSURANCE_UNSUPPORTED');
48
+ if (assurance === 'runtime-attested')
49
+ return blocked('RUNTIME_ATTESTATION_UNAVAILABLE');
50
+ return {
51
+ allowed: true,
52
+ scope: 'configured',
53
+ assurance: 'configured',
54
+ runtimeEnforcement: false,
55
+ action: 'Compatibility mode: validate exact L1 launch settings and controller-owned executor identity. Observed mismatches block continuation. Missing runtime settings remain unknown; no runtime attestation is claimed.',
56
+ };
30
57
  }
31
58
  export class ModelPolicyAdmissionError extends Error {
32
59
  admission;
@@ -5,6 +5,7 @@
5
5
  */
6
6
  import { ORG_PLAN_CAPABILITIES } from '../plans/org-plan-capabilities.js';
7
7
  import { readExecutorConfiguration } from './executor-configuration.js';
8
+ import { decodeCodexPolicyCatalog } from './codex-model-catalog.js';
8
9
  import { RelaySession, } from '../../features/sessions/model/relay-session.js';
9
10
  import { randomUUID } from 'node:crypto';
10
11
  import { createPlanMeasurementSnapshot, } from '../../features/plans/application/measurement-snapshot.js';
@@ -277,7 +278,7 @@ export class CodexSessionRuntime {
277
278
  return RelaySession.rehydrate(session).startTurn(result, now).snapshot;
278
279
  }
279
280
  async startExecutorTurn(session, childThreadId, text, clientUserMessageId) {
280
- this.requireExecutorAdmission?.(session.id);
281
+ const policy = await this.requireExecutorAdmission?.(session.id, childThreadId);
281
282
  const resource = this.sessions.get(session.id);
282
283
  if (!resource)
283
284
  throw new Error('CODEX_SESSION_NOT_RUNNING');
@@ -285,15 +286,16 @@ export class CodexSessionRuntime {
285
286
  threadId: childThreadId,
286
287
  input: [{ type: 'text', text, text_elements: [] }],
287
288
  clientUserMessageId,
288
- ...(session.modelSettings?.executorModel
289
- ? { model: session.modelSettings.executorModel }
289
+ ...((policy?.model ?? session.modelSettings?.executorModel)
290
+ ? { model: policy?.model ?? session.modelSettings?.executorModel }
290
291
  : {}),
291
- ...(session.modelSettings?.executorReasoningEffort
292
- ? { effort: session.modelSettings.executorReasoningEffort }
292
+ ...((policy?.reasoningEffort ?? session.modelSettings?.executorReasoningEffort)
293
+ ? { effort: policy?.reasoningEffort ?? session.modelSettings?.executorReasoningEffort }
293
294
  : {}),
294
295
  };
295
296
  let response;
296
297
  try {
298
+ policy?.assertCurrent();
297
299
  response = await resource.process.rpc.request('turn/start', params);
298
300
  }
299
301
  catch (error) {
@@ -305,9 +307,13 @@ export class CodexSessionRuntime {
305
307
  error.code !== -32600 ||
306
308
  error.message !== `thread not found: ${childThreadId}`)
307
309
  throw error;
308
- this.requireExecutorAdmission?.(session.id);
310
+ await this.requireExecutorAdmission?.(session.id, childThreadId);
309
311
  await resource.process.rpc.request('thread/resume', { threadId: childThreadId });
310
- this.requireExecutorAdmission?.(session.id);
312
+ const refreshed = await this.requireExecutorAdmission?.(session.id, childThreadId);
313
+ policy?.assertCurrent();
314
+ if (JSON.stringify(refreshed) !== JSON.stringify(policy))
315
+ throw new Error('EXECUTOR_POLICY_CHANGED');
316
+ refreshed?.assertCurrent();
311
317
  response = await resource.process.rpc.request('turn/start', params);
312
318
  }
313
319
  const result = decodeTurnStart(response);
@@ -315,6 +321,33 @@ export class CodexSessionRuntime {
315
321
  resource.turnThreads.set(result, childThreadId);
316
322
  return result;
317
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');
329
+ let timer;
330
+ let catalog;
331
+ try {
332
+ catalog = decodeCodexPolicyCatalog(await Promise.race([
333
+ resource.process.rpc.request('model/list', {}),
334
+ new Promise((_, reject) => {
335
+ timer = setTimeout(() => reject(new Error('EXECUTOR_CATALOG_UNAVAILABLE')), 5_000);
336
+ }),
337
+ ]));
338
+ }
339
+ finally {
340
+ if (timer)
341
+ clearTimeout(timer);
342
+ }
343
+ if (!catalog || this.sessions.get(sessionId) !== resource || !resource.active)
344
+ throw new Error('EXECUTOR_CATALOG_UNAVAILABLE');
345
+ const model = catalog.models.find((entry) => entry.id === policy.model);
346
+ if (!model)
347
+ throw new Error('EXECUTOR_MODEL_UNAVAILABLE');
348
+ if (!model.reasoningEfforts.includes(policy.reasoningEffort))
349
+ throw new Error('EXECUTOR_EFFORT_UNSUPPORTED');
350
+ }
318
351
  /** The sole authoritative in-process ownership probe. It never launches a child. */
319
352
  ownsWriter(sessionId) {
320
353
  return this.sessions.get(sessionId)?.active === true;
@@ -7,7 +7,6 @@ import { spawn } from 'node:child_process';
7
7
  import { access } from 'node:fs/promises';
8
8
  import { constants } from 'node:fs';
9
9
  import { isAbsolute, join } from 'node:path';
10
- export const managedXerjVersion = '1.0.0-rc.87';
11
10
  /** The manager alone owns backend identity, authentication and shared lifetime. */
12
11
  export class ManagedXerj {
13
12
  environment;
@@ -69,7 +68,8 @@ export class ManagedXerj {
69
68
  if (value.status === 'unavailable')
70
69
  return settle(unavailable('managed-backend-unavailable'));
71
70
  if (value.status !== 'ready' ||
72
- value.version !== managedXerjVersion ||
71
+ typeof value.version !== 'string' ||
72
+ !/^[0-9]+\.[0-9]+\.[0-9]+(?:[-+][A-Za-z0-9.-]+)?$/.test(value.version) ||
73
73
  typeof value.endpoint !== 'string' ||
74
74
  !/^http:\/\/(127\.0\.0\.1|\[::1\])(?::\d{1,5})?$/.test(value.endpoint))
75
75
  throw new Error();
@@ -6,8 +6,7 @@
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
7
  import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
8
8
  import { join } from 'node:path';
9
- import { managedXerjVersion } from './managed-xerj.js';
10
- // Content-affecting rc.87 settings. Reused in the command and fingerprint so
9
+ // Content-affecting settings. Reused in the command and fingerprint so
11
10
  // changing an operational setting cannot accidentally require a rebuild.
12
11
  export const xerjContentArguments = [
13
12
  '--no-graph',
@@ -24,7 +23,6 @@ export function xerjIndexConfig(root, prefix, endpoint) {
24
23
  root,
25
24
  prefix,
26
25
  endpoint,
27
- nativeVersion: managedXerjVersion,
28
26
  contentArguments: xerjContentArguments,
29
27
  followSymlinks: false,
30
28
  label: null,
@@ -40,8 +38,13 @@ const filename = '.gestalt-index-config.json';
40
38
  export async function checkXerjIndexConfig(directory, expected) {
41
39
  try {
42
40
  const saved = JSON.parse(await readFile(join(directory, filename), 'utf8'));
41
+ // Older fingerprints included a pinned version. Validate their integrity
42
+ // before comparing content settings; native XERJ owns index compatibility.
43
+ const settings = { ...saved.settings };
44
+ delete settings.nativeVersion;
43
45
  return saved.schemaVersion === expected.schemaVersion &&
44
- saved.fingerprint === expected.fingerprint &&
46
+ createHash('sha256').update(JSON.stringify(settings)).digest('hex') ===
47
+ expected.fingerprint &&
45
48
  createHash('sha256').update(JSON.stringify(saved.settings)).digest('hex') ===
46
49
  saved.fingerprint
47
50
  ? 'compatible'
@@ -18,7 +18,9 @@
18
18
  ],
19
19
  "modelPolicyContract": {
20
20
  "version": 1,
21
- "scope": "schema-and-retention",
21
+ "scope": "configured-launch-and-retention",
22
+ "defaultAssurance": "configured",
23
+ "strictAttestation": false,
22
24
  "runtimeEnforcement": false
23
25
  }
24
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.55.2",
3
+ "version": "0.55.4",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",