gestalt-mobile 0.62.2 → 0.62.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
@@ -147,6 +147,18 @@ and terminal whole-branch review remain required. See
147
147
  [update and rollback guidance](docs/org-plan-policy-compatibility.md) and
148
148
  [prelaunch catalog recovery](docs/org-plan-prelaunch-catalog.md).
149
149
 
150
+ ## Continuing a plan in a new session
151
+
152
+ An explicit instruction to a new session to take over an unfinished Org Plan
153
+ authorizes `gestalt_org_plan_takeover({version:1,reason:"userDirectedTakeover"})`.
154
+ No additional approval is required. Mobile reserves plan ownership, fences old
155
+ supervisors, verifies their actor trees and background writers stopped, and
156
+ returns the exact executor identity to launch under the new root. It preserves
157
+ the plan, checkpoint history and verification gates. Old-root agent IDs are not
158
+ reused through native follow-up calls. Repeated calls do not launch another
159
+ executor; a failed stop returns a specific recovery code and grants no launch.
160
+ Manual Off racing the takeover and unrelated pending interactions remain gates.
161
+
150
162
  ## Skill profiles
151
163
 
152
164
  Global profiles live in `~/.gestalt/skill-profiles/<name>.yml` and use version 1 YAML:
@@ -1936,6 +1936,266 @@ describe('production composition', () => {
1936
1936
  expect(accepted.handles.flatMap((handle) => handle.calls)).not.toContain('turn/start');
1937
1937
  await accepted.app.close();
1938
1938
  });
1939
+ it('lets a user-directed new session take over the unfinished plan without an approval or an unreachable old-root executor', async () => {
1940
+ const handles = [];
1941
+ let previousRoot = '';
1942
+ const launch = liveAppServer(handles);
1943
+ let coordinator;
1944
+ const fixture = {
1945
+ ...(await createProductionAutopilotFixture({
1946
+ activitySchedule: () => () => { },
1947
+ autopilotSchedule: () => () => { },
1948
+ onAutopilotCoordinator: (value) => {
1949
+ coordinator = value;
1950
+ },
1951
+ launchAppServer: () => {
1952
+ const server = launch(), request = server.rpc.request;
1953
+ server.rpc.request = async (method, params) => method === 'thread/read' &&
1954
+ params.threadId === 'previous-child'
1955
+ ? {
1956
+ thread: {
1957
+ id: 'previous-child',
1958
+ parentThreadId: previousRoot,
1959
+ status: { type: 'idle' },
1960
+ turns: [],
1961
+ },
1962
+ }
1963
+ : method === 'thread/resume'
1964
+ ? { thread: { id: params.threadId } }
1965
+ : request(method, params);
1966
+ return server;
1967
+ },
1968
+ })),
1969
+ handles,
1970
+ };
1971
+ onTestFinished(() => fixture.app.close());
1972
+ const { SqliteAutopilotStore } = await import('./platform/persistence/sqlite-autopilot-store.js');
1973
+ previousRoot = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()
1974
+ .threadId;
1975
+ const db = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
1976
+ onTestFinished(() => db.close());
1977
+ const store = new SqliteAutopilotStore(db);
1978
+ const old = store.find(fixture.sessionId);
1979
+ store.save({
1980
+ ...old,
1981
+ executor: {
1982
+ canonicalPosition: 'L1',
1983
+ canonicalTaskName: 'l1',
1984
+ threadId: 'previous-child',
1985
+ taskPath: '/root/l1',
1986
+ l1State: 'TODO',
1987
+ lastActivityAt: new Date().toISOString(),
1988
+ ownedProcesses: [],
1989
+ outcome: 'partial',
1990
+ continuationGeneration: 1,
1991
+ continuationCount: 2,
1992
+ },
1993
+ });
1994
+ await fixture.app.inject({
1995
+ method: 'POST',
1996
+ url: `/api/sessions/${fixture.sessionId}/release`,
1997
+ });
1998
+ const incoming = await createComposedSession(fixture.app);
1999
+ await installAutopilotPlan(fixture.app, incoming, fixture.workspacePath, 'autopilot');
2000
+ const started = await fixture.app.inject({
2001
+ method: 'POST',
2002
+ url: `/api/sessions/${incoming}/turns`,
2003
+ payload: {
2004
+ text: 'Take over the unfinished plan here.',
2005
+ clientUserMessageId: 'takeover-test',
2006
+ },
2007
+ });
2008
+ expect(started.statusCode).toBe(202);
2009
+ const current = (await fixture.app.inject(`/api/sessions/${incoming}`)).json();
2010
+ const handle = handles.find((h) => h.requests.some((r) => r.method === 'turn/start' &&
2011
+ r.params.threadId === current.threadId));
2012
+ const request = (id) => handle.request({
2013
+ id,
2014
+ method: 'item/tool/call',
2015
+ params: {
2016
+ threadId: current.threadId,
2017
+ turnId: current.activeTurnId,
2018
+ tool: 'gestalt_org_plan_takeover',
2019
+ arguments: { version: 1, reason: 'userDirectedTakeover' },
2020
+ },
2021
+ });
2022
+ const result = (await request(9910));
2023
+ const accepted = JSON.parse(result.contentItems[0].text);
2024
+ expect(accepted).toMatchObject({
2025
+ accepted: true,
2026
+ alreadyOwner: false,
2027
+ identity: { canonicalTaskName: 'l1', taskName: 'l1_g2', generation: 2 },
2028
+ });
2029
+ expect(store.find(incoming)).toMatchObject({
2030
+ requestedEnabled: true,
2031
+ executor: { replacement: { reason: 'userDirectedTakeover', taskName: 'l1_g2' } },
2032
+ });
2033
+ expect(db
2034
+ .prepare("SELECT count(*) AS n FROM pending_interactions WHERE kind='orgPlanAttention'")
2035
+ .get()).toEqual({ n: 0 });
2036
+ expect(db
2037
+ .prepare("SELECT count(*) AS n FROM session_events WHERE type='autopilot.supervisor-taken-over'")
2038
+ .get()).toEqual({ n: 1 });
2039
+ expect(JSON.parse((await request(9911)).contentItems[0].text)).toMatchObject({
2040
+ accepted: true,
2041
+ alreadyOwner: true,
2042
+ identity: { taskName: 'l1_g2', generation: 2 },
2043
+ });
2044
+ expect((await fixture.app.inject({
2045
+ method: 'POST',
2046
+ url: `/api/sessions/${fixture.sessionId}/turns`,
2047
+ payload: { text: 'stale supervisor' },
2048
+ })).statusCode).toBe(409);
2049
+ handle.respond = (method, params) => {
2050
+ if (method === 'thread/list')
2051
+ return {
2052
+ data: params.parentThreadId === current.threadId
2053
+ ? [
2054
+ {
2055
+ id: 'new-child',
2056
+ parentThreadId: current.threadId,
2057
+ status: { type: 'idle' },
2058
+ source: { subAgent: { thread_spawn: { agent_path: '/root/l1_g2' } } },
2059
+ },
2060
+ ]
2061
+ : [],
2062
+ };
2063
+ if (method === 'thread/read')
2064
+ return {
2065
+ thread: {
2066
+ id: params.threadId,
2067
+ parentThreadId: current.threadId,
2068
+ status: {
2069
+ type: params.threadId === current.threadId
2070
+ ? 'active'
2071
+ : 'idle',
2072
+ },
2073
+ turns: [],
2074
+ },
2075
+ };
2076
+ return undefined;
2077
+ };
2078
+ await fixture.app.inject({
2079
+ method: 'POST',
2080
+ url: `/api/sessions/${incoming}/activity/refresh`,
2081
+ });
2082
+ expect(coordinator.reconcileExecutorBinding(incoming)).toMatchObject({ status: 'ready' });
2083
+ expect(store.find(incoming).executor).toMatchObject({
2084
+ threadId: 'new-child',
2085
+ taskPath: '/root/l1_g2',
2086
+ continuationGeneration: 2,
2087
+ });
2088
+ expect(store.find(fixture.sessionId).requestedEnabled).toBe(false);
2089
+ });
2090
+ it.each(['checkpoint', 'wait expiry'])('continues the durable root after %s when startup observed a provisional disconnected thread', async (boundary) => {
2091
+ const timers = [];
2092
+ const handles = [];
2093
+ const launch = liveAppServer(handles);
2094
+ let coordinator;
2095
+ const fixture = {
2096
+ ...(await createProductionAutopilotFixture({
2097
+ launchAppServer: () => {
2098
+ const server = launch();
2099
+ const request = server.rpc.request;
2100
+ server.rpc.request = async (method, params) => {
2101
+ if (method === 'thread/start')
2102
+ handles.at(-1).notify?.({
2103
+ method: 'thread/started',
2104
+ params: { thread: { id: 'provisional-root', status: { type: 'notLoaded' } } },
2105
+ });
2106
+ return request(method, params);
2107
+ };
2108
+ return server;
2109
+ },
2110
+ activitySchedule: () => () => { },
2111
+ autopilotSchedule: (callback, delayMs) => {
2112
+ const timer = { callback, delayMs, cancelled: false, fired: false };
2113
+ timers.push(timer);
2114
+ return () => {
2115
+ timer.cancelled = true;
2116
+ };
2117
+ },
2118
+ onAutopilotCoordinator: (value) => {
2119
+ coordinator = value;
2120
+ },
2121
+ })),
2122
+ handles,
2123
+ };
2124
+ onTestFinished(() => fixture.app.close());
2125
+ let threadId;
2126
+ let turnId;
2127
+ let handle;
2128
+ if (boundary === 'checkpoint') {
2129
+ const checkpoint = await holdCheckpointRequest(fixture, timers, 8910);
2130
+ ({ threadId, turnId, handle } = checkpoint);
2131
+ handle.responseSettled({ id: 8910, outcome: 'resultWritten' });
2132
+ await expect(checkpoint.response).resolves.toEqual(toOrgPlanCheckpointToolResponse('recorded'));
2133
+ }
2134
+ else {
2135
+ const first = timers.find((timer) => !timer.cancelled);
2136
+ expect(first).toBeDefined();
2137
+ first.fired = true;
2138
+ first.callback();
2139
+ await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().activeTurnId).toEqual(expect.any(String)));
2140
+ const session = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json();
2141
+ threadId = session.threadId;
2142
+ turnId = session.activeTurnId;
2143
+ handle = handles.find((candidate) => candidate.requests.some((request) => request.method === 'turn/start'));
2144
+ expect(coordinator.registerProactiveWait(fixture.sessionId, {
2145
+ id: 'wait-report',
2146
+ leaseId: 'wait-lease',
2147
+ wakeConditions: ['executorChanged'],
2148
+ maxWaitMs: 60_000,
2149
+ })).toBe(true);
2150
+ }
2151
+ handle.notify({
2152
+ method: 'turn/completed',
2153
+ params: { threadId, turn: { id: turnId, status: 'completed' } },
2154
+ });
2155
+ await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json().agentActivity
2156
+ .root.state).toBe('idle'));
2157
+ if (boundary === 'wait expiry') {
2158
+ expect(coordinator.snapshot(fixture.sessionId).health).toMatchObject({
2159
+ supervision: 'parked',
2160
+ wait: { present: true },
2161
+ });
2162
+ expect(timers.some((timer) => !timer.cancelled && timer.delayMs > 59_000 && timer.delayMs <= 60_000)).toBe(true);
2163
+ vi.useFakeTimers({ toFake: ['Date'] });
2164
+ onTestFinished(() => {
2165
+ vi.useRealTimers();
2166
+ });
2167
+ vi.setSystemTime(new Date(Date.now() + 60_001));
2168
+ }
2169
+ const starts = () => handles
2170
+ .flatMap((candidate) => candidate.requests)
2171
+ .filter((request) => request.method === 'turn/start');
2172
+ for (let attempt = 0; attempt < 8 && starts().length < 2; attempt++) {
2173
+ for (const timer of timers.filter((candidate) => !candidate.cancelled && !candidate.fired)) {
2174
+ timer.fired = true;
2175
+ timer.callback();
2176
+ }
2177
+ await new Promise((resolve) => setImmediate(resolve));
2178
+ }
2179
+ await vi.waitFor(() => expect(starts()).toHaveLength(2));
2180
+ expect(coordinator.snapshot(fixture.sessionId).health.wait.present).toBe(false);
2181
+ expect(starts().map((request) => request.params.threadId)).toEqual([threadId, threadId]);
2182
+ for (const timer of timers.filter((candidate) => candidate.fired))
2183
+ timer.callback();
2184
+ await new Promise((resolve) => setImmediate(resolve));
2185
+ expect(starts()).toHaveLength(2);
2186
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
2187
+ try {
2188
+ expect(database
2189
+ .prepare("SELECT count(*) AS count FROM autopilot_controls WHERE session_id = ? AND status = 'started'")
2190
+ .get(fixture.sessionId)).toEqual({ count: 2 });
2191
+ expect(database
2192
+ .prepare('SELECT count(*) AS count FROM session_events WHERE session_id = ? AND type = ?')
2193
+ .get(fixture.sessionId, boundary === 'checkpoint' ? 'org-plan.step-reported' : 'autopilot.final-rejected')).toEqual({ count: 1 });
2194
+ }
2195
+ finally {
2196
+ database.close();
2197
+ }
2198
+ });
1939
2199
  it('continues the root after a checkpoint with a completed assigned executor', async () => {
1940
2200
  const timers = [];
1941
2201
  let coordinator;
@@ -4030,9 +4290,11 @@ describe('production composition', () => {
4030
4290
  database.close();
4031
4291
  }
4032
4292
  const handle = fixture.handles.find((candidate) => candidate.notify);
4293
+ const rootThreadId = (await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()
4294
+ .threadId;
4033
4295
  handle.notify({
4034
4296
  method: 'thread/started',
4035
- params: { thread: { id: 'thread-1', status: { type: 'idle' } } },
4297
+ params: { thread: { id: rootThreadId, status: { type: 'idle' } } },
4036
4298
  });
4037
4299
  handle.notify({
4038
4300
  method: 'item/started',
@@ -4041,7 +4303,7 @@ describe('production composition', () => {
4041
4303
  type: 'collabToolCall',
4042
4304
  tool: 'spawn_agent',
4043
4305
  status: 'inProgress',
4044
- senderThreadId: 'thread-1',
4306
+ senderThreadId: rootThreadId,
4045
4307
  receiverThreadId: 'child-1',
4046
4308
  agentStatus: 'working',
4047
4309
  },
@@ -4060,7 +4322,7 @@ describe('production composition', () => {
4060
4322
  type: 'collabToolCall',
4061
4323
  tool: 'wait',
4062
4324
  status: status === 'failed' ? 'failed' : 'completed',
4063
- senderThreadId: 'thread-1',
4325
+ senderThreadId: rootThreadId,
4064
4326
  receiverThreadId: 'child-1',
4065
4327
  agentStatus: status,
4066
4328
  },
@@ -62,6 +62,10 @@ import { SessionSupervisor } from './platform/runtime/session-supervisor.js';
62
62
  import { mapWithConcurrency } from './platform/runtime/concurrency.js';
63
63
  import { RelaySession, } from './features/sessions/model/relay-session.js';
64
64
  import { AgentActivityRegistry } from './features/agent-activity/registry.js';
65
+ import { SupervisionTakeover } from './features/autopilot/application/takeover-supervision.js';
66
+ import { SqliteSupervisionTakeoverStore } from './platform/persistence/sqlite-supervision-takeover-store.js';
67
+ import { isOrgPlanTakeoverCall } from '../shared/contracts/org-plan-takeover.js';
68
+ import { WriterAcquisitionError } from './features/sessions/application/writer-acquisition.js';
65
69
  import { toAgentActivityDto } from './features/agent-activity/activity-dto.js';
66
70
  import { decodeAgentActivityFacts, decodeToolEfficiencyFacts, } from './platform/codex/activity-facts.js';
67
71
  import { ToolEfficiencyProjection } from './features/agent-activity/tool-efficiency-projection.js';
@@ -143,11 +147,25 @@ export async function composeRelayApp(options) {
143
147
  const interactions = new SqlitePendingInteractionStore(database);
144
148
  const idempotency = new SqliteIdempotencyStore(database);
145
149
  const autopilotStore = new SqliteAutopilotStore(database);
150
+ const takeoverStore = new SqliteSupervisionTakeoverStore(database, autopilotStore);
146
151
  const attentionResolutionOperations = new Map();
147
152
  const checkpointHandoffTimers = new Map();
148
153
  const attentionAcknowledgementTimers = new Map();
149
154
  const checkpointHandoffRecoveries = new Set();
150
155
  const supervisedPlans = new SupervisedPlanRegistry();
156
+ const supervisorOwnership = (sessionId) => {
157
+ const identity = supervisedPlans.identity(sessionId) ?? autopilotStore.find(sessionId)?.planIdentity;
158
+ const owner = identity ? takeoverStore.owner(identity) : null;
159
+ return !owner
160
+ ? 'owned'
161
+ : owner.sessionId !== sessionId
162
+ ? identity && takeoverStore.retired(identity, sessionId)
163
+ ? 'replaced'
164
+ : 'transferring'
165
+ : owner.phase === 'stopping'
166
+ ? 'transferring'
167
+ : 'owned';
168
+ };
151
169
  const requireOrgExecutionAdmission = (sessionId) => requireModelPolicyAdmission(supervisedPlans.find(sessionId), supervisedPlans.modelPolicyStatus(sessionId));
152
170
  const planStatusSource = new FilesystemPlanStatusSource(join(dirname(databasePath), 'plans'));
153
171
  const planMeasurementHelperPath = options.planMeasurementHelperPath ?? process.env.GESTALT_MOBILE_ORG_PLAN_HELPER;
@@ -207,6 +225,7 @@ export async function composeRelayApp(options) {
207
225
  publishSessionStatus(snapshot.sessionId, occurredAt);
208
226
  notifyAutopilotActivity(snapshot.sessionId);
209
227
  }, {
228
+ rootThreadId: (sessionId) => sessions.find(sessionId)?.threadId ?? null,
210
229
  // Evidence arms one bounded reconciliation; healthy sessions are never polled.
211
230
  schedule: options.activitySchedule ??
212
231
  ((callback, delayMs) => {
@@ -270,6 +289,7 @@ export async function composeRelayApp(options) {
270
289
  },
271
290
  });
272
291
  const autopilot = new AutopilotCoordinator({
292
+ supervisorOwnership,
273
293
  pendingProcessResult: (sessionId) => hostTests?.hasUnreadResult(sessionId) ?? false,
274
294
  processResultState: (sessionId, runId) => hostTests?.resultState(sessionId, runId) ?? 'missing',
275
295
  modelPolicyStatus: (sessionId) => supervisedPlans.modelPolicyStatus(sessionId),
@@ -311,6 +331,8 @@ export async function composeRelayApp(options) {
311
331
  nextControlId: (sessionId, generation) => `autopilot-${generation}-${createHash('sha256').update(`${sessionId}:${randomUUID()}`).digest('hex').slice(0, 16)}`,
312
332
  turnStarter: {
313
333
  start: async (sessionId, controlId, generation, launchIdentity) => {
334
+ if (supervisorOwnership(sessionId) !== 'owned')
335
+ throw new Error('AUTOPILOT_START_UNAVAILABLE');
314
336
  const current = () => {
315
337
  const state = autopilotStore.find(sessionId);
316
338
  return Boolean(state &&
@@ -379,6 +401,8 @@ export async function composeRelayApp(options) {
379
401
  },
380
402
  executorController: {
381
403
  resume: async (sessionId, threadId, generation, trigger) => {
404
+ if (supervisorOwnership(sessionId) !== 'owned')
405
+ throw new Error('AUTOPILOT_EXECUTOR_UNAVAILABLE');
382
406
  const session = sessions.find(sessionId);
383
407
  if (!session || !runtime || blockingInteractions(sessionId).length)
384
408
  throw new Error('AUTOPILOT_EXECUTOR_UNAVAILABLE');
@@ -749,6 +773,58 @@ export async function composeRelayApp(options) {
749
773
  };
750
774
  let closing = false;
751
775
  let runtime = null;
776
+ const takeover = new SupervisionTakeover({
777
+ store: takeoverStore,
778
+ now: () => new Date().toISOString(),
779
+ context: (id) => {
780
+ const session = sessions.find(id);
781
+ const plan = supervisedPlans.findCurrent(id);
782
+ const identity = supervisedPlans.identity(id);
783
+ if (!session || !plan || !identity)
784
+ return null;
785
+ return {
786
+ session,
787
+ plan,
788
+ identity,
789
+ state: autopilotStore.find(id),
790
+ admission: autopilot.snapshot(id).executionAdmission?.allowed !== false,
791
+ held: blockingInteractions(id).length > 0,
792
+ localExecutor: activity
793
+ .snapshot(id, new Date().toISOString())
794
+ .subagents.some((child) => Boolean(child.canonicalPosition) ||
795
+ ['working', 'awaitingAgent'].includes(child.state) ||
796
+ child.ownedProcesses?.some((process) => ['running', 'detached-active'].includes(process.state))),
797
+ };
798
+ },
799
+ predecessors: (context) => sessions.list().flatMap((session) => {
800
+ if (session.id === context.session.id ||
801
+ session.workspacePath !== context.session.workspacePath ||
802
+ session.provider !== 'codex')
803
+ return [];
804
+ const state = autopilotStore.find(session.id);
805
+ return state && state.planIdentity === context.identity ? [{ session, state }] : [];
806
+ }),
807
+ fence: (id) => autopilot.cancel(id, 'sessionEnded'),
808
+ stop: async ({ session, state }) => {
809
+ if (!runtime || (hostTests?.supervisionSummary(session.id).running ?? 0) > 0)
810
+ return false;
811
+ if (!(await runtime.quiesceForTakeover(session, state.executor?.ownedProcesses ?? [], state.executor)))
812
+ return false;
813
+ const latest = sessions.find(session.id);
814
+ if (!latest || latest.threadId !== session.threadId)
815
+ return false;
816
+ dismissPendingInteractions(session.id, new Date().toISOString());
817
+ const released = RelaySession.rehydrate(latest).release(new Date().toISOString()).snapshot;
818
+ sessions.save(released);
819
+ activity.disconnected(session.id, released.updatedAt);
820
+ events.publish(journal.append(session.id, 'session.updated', released, released.updatedAt));
821
+ return true;
822
+ },
823
+ changed: (id) => {
824
+ autopilot.planStatusChanged(id);
825
+ autopilot.restore(id);
826
+ },
827
+ });
752
828
  const providerRecovery = new SessionProviderRecovery({
753
829
  find: (id) => sessions.find(id),
754
830
  authority: (id) => {
@@ -1187,6 +1263,26 @@ export async function composeRelayApp(options) {
1187
1263
  reasonCode: 'checkpointBoundaryAmbiguous',
1188
1264
  })) === true);
1189
1265
  }
1266
+ if (!rawInteraction && isOrgPlanTakeoverCall(request)) {
1267
+ const result = origin.kind === 'root' &&
1268
+ origin.physicalTurnId === session.activeTurnId &&
1269
+ session.threadId
1270
+ ? await takeover.takeOver(sessionId, session.threadId, session.activeTurnId)
1271
+ : { accepted: false, code: 'CURRENT_ROOT_REQUIRED' };
1272
+ const response = result.accepted && 'identity' in result
1273
+ ? {
1274
+ ...result,
1275
+ instruction: result.boundaryFinalRequired
1276
+ ? 'The previous root has a persisted checkpoint awaiting its mandatory report. Emit that boundary final now and end this root turn without launching an executor. The following root turn will receive the authorized executor identity through the normal checkpoint continuation.'
1277
+ : 'Mobile already stopped and retired the previous supervisors. This takeover is authorized by the user instruction. Do not follow up or interrupt old-root agent IDs. Consult this root’s native roster: resume the returned task name if present, otherwise launch it exactly once. ' +
1278
+ autopilotExecutorLaunchPrompt(result.identity, supervisedPlans.find(sessionId)),
1279
+ }
1280
+ : result;
1281
+ return (runtime?.resolveServerRequest(sessionId, String(request.id), {
1282
+ success: true,
1283
+ contentItems: [{ type: 'inputText', text: JSON.stringify(response) }],
1284
+ }) === true);
1285
+ }
1190
1286
  if (!rawInteraction && isAgentCapacityRecoveryCall(request)) {
1191
1287
  const rootOwned = origin.kind === 'root' && origin.physicalTurnId === session.activeTurnId;
1192
1288
  return (rootOwned &&
@@ -1815,6 +1911,8 @@ export async function composeRelayApp(options) {
1815
1911
  : undefined,
1816
1912
  ensureWriter: runtime || kimiRuntime
1817
1913
  ? async (session) => {
1914
+ if (supervisorOwnership(session.id) === 'replaced')
1915
+ throw new WriterAcquisitionError('supervisorReplaced');
1818
1916
  dismissPendingInteractions(session.id, new Date().toISOString());
1819
1917
  const owner = ownerRuntime(session);
1820
1918
  if (!owner)
@@ -28,9 +28,13 @@ export class AgentActivityRegistry {
28
28
  observe(fact) {
29
29
  if (this.#disposed.has(fact.sessionId))
30
30
  return this.snapshot(fact.sessionId, fact.occurredAt);
31
- const current = this.snapshot(fact.sessionId, fact.occurredAt);
31
+ const snapshot = this.snapshot(fact.sessionId, fact.occurredAt);
32
+ const rootThreadId = this.options.rootThreadId?.(fact.sessionId);
33
+ const current = rootThreadId && rootThreadId !== snapshot.rootThreadId
34
+ ? Object.freeze({ ...snapshot, rootThreadId })
35
+ : snapshot;
32
36
  const next = withActivityConfidence(projectAgentActivity(current, fact), fact.kind === 'collaboration' && !fact.childId ? 'stale' : 'fresh');
33
- if (next !== current) {
37
+ if (next !== snapshot) {
34
38
  this.#snapshots.set(fact.sessionId, next);
35
39
  this.publish(next, fact.occurredAt);
36
40
  }
@@ -5,8 +5,9 @@
5
5
  */
6
6
  import { currentExecutableL1Index, } from '../../plans/domain/supervised-plan.js';
7
7
  import { parseOrgPlanAgentIdentity } from '../../../../shared/org-plan-position.js';
8
- export const AUTOPILOT_PROMPT_VERSION = 'v14';
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.';
8
+ export const AUTOPILOT_PROMPT_VERSION = 'v15';
9
+ export const AUTOPILOT_CONTINUATION_PROMPT = 'If the user instructed this new session to take over an unfinished plan whose executor belongs to a previous root, call gestalt_org_plan_takeover with version 1 and reason userDirectedTakeover before launching or following up an executor. The user instruction supplies takeover authorization; do not request another approval or declare hardBlock merely because an old-root agent is not found. Use only the exact executor identity returned by Mobile after it confirms previous writers stopped. If that task name exists in this root, resume it instead of spawning it again. An alreadyOwner response without an identity means reconcile and resume this root’s existing executor. A failed takeover is a specific runtime recovery failure, never permission to launch a competing writer. ' +
10
+ '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
11
  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
12
  /** Builds a physical launch instruction while keeping durable L1 identity canonical. */
12
13
  export function autopilotExecutorLaunchPrompt(identity, plan) {
@@ -568,6 +568,9 @@ export class AutopilotCoordinator {
568
568
  });
569
569
  }
570
570
  enable(sessionId) {
571
+ if (this.deps.supervisorOwnership?.(sessionId) &&
572
+ this.deps.supervisorOwnership(sessionId) !== 'owned')
573
+ return { code: 'AUTOPILOT_SESSION_UNAVAILABLE' };
571
574
  const session = this.deps.session(sessionId);
572
575
  if (!session || !session.threadId || !['ready', 'turnActive'].includes(session.state))
573
576
  return { code: 'AUTOPILOT_SESSION_UNAVAILABLE' };
@@ -1383,6 +1386,9 @@ export class AutopilotCoordinator {
1383
1386
  * while a new identity can receive its own explicit supervision request.
1384
1387
  */
1385
1388
  supervisionStarted(sessionId) {
1389
+ if (this.deps.supervisorOwnership?.(sessionId) &&
1390
+ this.deps.supervisorOwnership(sessionId) !== 'owned')
1391
+ return { code: 'AUTOPILOT_SESSION_UNAVAILABLE' };
1386
1392
  const currentPlan = this.deps.plan(sessionId);
1387
1393
  const admission = this.modelPolicyAdmission(sessionId);
1388
1394
  if (!admission.allowed)
@@ -3182,6 +3188,11 @@ export class AutopilotCoordinator {
3182
3188
  return 'unknown';
3183
3189
  }
3184
3190
  decision(sessionId, state) {
3191
+ const ownership = this.deps.supervisorOwnership?.(sessionId);
3192
+ if (ownership === 'replaced')
3193
+ return { kind: 'disable', reason: 'sessionUnavailable' };
3194
+ if (ownership === 'transferring')
3195
+ return { kind: 'observe' };
3185
3196
  if (state.supervision?.outcome === 'parked')
3186
3197
  return { kind: 'observe' };
3187
3198
  const plan = this.deps.plan(sessionId);
@@ -3273,7 +3284,8 @@ export class AutopilotCoordinator {
3273
3284
  const activity = this.deps.activity(sessionId);
3274
3285
  if (activity?.confidence === 'fresh' &&
3275
3286
  Date.parse(this.deps.now()) - Date.parse(activity.root.observedAt) <=
3276
- this.deps.policy.staleAfterMs) {
3287
+ this.deps.policy.staleAfterMs &&
3288
+ this.decision(sessionId, current).kind !== 'reconcile') {
3277
3289
  if (current.stopReason === 'reconcileFailed')
3278
3290
  this.persist({ ...current, stopReason: null, updatedAt: this.deps.now() });
3279
3291
  this.evaluate(sessionId);
@@ -3521,7 +3533,7 @@ function operationErrorKind(error) {
3521
3533
  return 'RANGE_ERROR';
3522
3534
  return 'UNKNOWN';
3523
3535
  }
3524
- function fingerprint(plan) {
3536
+ export function fingerprint(plan) {
3525
3537
  return requirePlanFingerprint(JSON.stringify(plan.steps.map((step) => [
3526
3538
  step.id,
3527
3539
  step.state,
@@ -0,0 +1,206 @@
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 { disabledAutopilot } from '../domain/autopilot-session.js';
7
+ import { currentExecutableL1Index, } from '../../plans/domain/supervised-plan.js';
8
+ import { fingerprint as planFingerprint } from './service.js';
9
+ import { executorAssignment, executorIdentity, } from '../domain/supervised-lifecycle.js';
10
+ import { startSupervisionProtocol } from '../domain/supervision-protocol.js';
11
+ /** Explicit user direction supplies authority. Runtime quiescence supplies sole-writer evidence. */
12
+ export class SupervisionTakeover {
13
+ deps;
14
+ running = new Map();
15
+ constructor(deps) {
16
+ this.deps = deps;
17
+ }
18
+ takeOver(sessionId, threadId, turnId) {
19
+ const prior = this.running.get(sessionId);
20
+ if (prior)
21
+ return prior;
22
+ const run = this.run(sessionId, threadId, turnId).catch(() => ({
23
+ accepted: false,
24
+ code: 'TAKEOVER_RUNTIME_UNAVAILABLE',
25
+ }));
26
+ this.running.set(sessionId, run);
27
+ void run.finally(() => {
28
+ if (this.running.get(sessionId) === run)
29
+ this.running.delete(sessionId);
30
+ });
31
+ return run;
32
+ }
33
+ async run(sessionId, threadId, turnId) {
34
+ const before = this.deps.context(sessionId);
35
+ if (!before ||
36
+ before.session.provider !== 'codex' ||
37
+ before.session.threadId !== threadId ||
38
+ before.session.activeTurnId !== turnId)
39
+ return { accepted: false, code: 'CURRENT_ROOT_REQUIRED' };
40
+ if (!before.admission)
41
+ return { accepted: false, code: 'EXECUTION_POLICY_UNAVAILABLE' };
42
+ if (before.held)
43
+ return { accepted: false, code: 'PENDING_INTERACTION' };
44
+ const index = currentExecutableL1Index(before.plan);
45
+ if (index < 0 || before.plan.executionComplete)
46
+ return { accepted: false, code: 'NO_UNFINISHED_MILESTONE' };
47
+ const existing = this.deps.store.owner(before.identity);
48
+ if (existing?.sessionId === sessionId && existing.phase === 'ready') {
49
+ const pending = before.state?.executor?.replacement;
50
+ const identity = pending &&
51
+ pending.planIdentity === before.identity &&
52
+ pending.planFingerprint === planFingerprint(before.plan) &&
53
+ pending.canonicalPosition === `L${index + 1}`
54
+ ? executorIdentity(pending.canonicalTaskName, pending.generation)
55
+ : !before.state?.executor
56
+ ? executorIdentity(`l${index + 1}`, 1)
57
+ : null;
58
+ if (!before.localExecutor && identity)
59
+ return {
60
+ accepted: true,
61
+ alreadyOwner: true,
62
+ identity,
63
+ previousSessionIds: [],
64
+ boundaryFinalRequired: Boolean(before.state?.checkpoints?.pendingTurnId),
65
+ };
66
+ return { accepted: true, alreadyOwner: true };
67
+ }
68
+ if (before.localExecutor)
69
+ return { accepted: false, code: 'CURRENT_EXECUTOR_ALREADY_PRESENT' };
70
+ const previous = this.deps
71
+ .predecessors(before)
72
+ .filter((p) => p.session.id !== sessionId &&
73
+ p.session.provider === 'codex' &&
74
+ p.session.workspacePath === before.session.workspacePath &&
75
+ p.state.planIdentity === before.identity);
76
+ if (!previous.length)
77
+ return { accepted: false, code: 'PREVIOUS_SUPERVISOR_NOT_FOUND' };
78
+ if (existing &&
79
+ existing.sessionId !== sessionId &&
80
+ !previous.some((p) => p.session.id === existing.sessionId))
81
+ return { accepted: false, code: 'PREVIOUS_SUPERVISOR_NOT_FOUND' };
82
+ const fingerprint = planFingerprint(before.plan);
83
+ const generation = before.state?.generation ?? 0;
84
+ const claim = this.deps.store.claim(before.identity, sessionId);
85
+ if (!claim)
86
+ return { accepted: false, code: 'TAKEOVER_IN_PROGRESS' };
87
+ if (!this.deps.store.retire(claim, previous.map((p) => p.session.id)))
88
+ return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
89
+ // Fence every predecessor before the first asynchronous process operation.
90
+ for (const p of previous)
91
+ if (!this.deps.store.stopped(before.identity, p.session.id))
92
+ this.deps.fence(p.session.id);
93
+ for (const p of previous) {
94
+ if (this.deps.store.stopped(before.identity, p.session.id))
95
+ continue;
96
+ if (!(await this.deps.stop(p)))
97
+ return { accepted: false, code: 'PREVIOUS_WRITER_NOT_STOPPED' };
98
+ if (!this.deps.store.markStopped(claim, p.session.id))
99
+ return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
100
+ }
101
+ const current = this.deps.context(sessionId);
102
+ if (!current ||
103
+ current.session.threadId !== threadId ||
104
+ current.session.activeTurnId !== turnId ||
105
+ current.identity !== before.identity ||
106
+ planFingerprint(current.plan) !== fingerprint ||
107
+ (current.state?.generation ?? 0) !== generation ||
108
+ current.held ||
109
+ current.localExecutor ||
110
+ !current.admission)
111
+ return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
112
+ const canonicalTaskName = `l${index + 1}`;
113
+ const executors = previous
114
+ .map((p) => p.state.executor)
115
+ .filter((e) => e?.canonicalTaskName === canonicalTaskName);
116
+ const source = executors.sort((a, b) => (b.replacement?.generation ?? b.continuationGeneration) -
117
+ (a.replacement?.generation ?? a.continuationGeneration))[0];
118
+ const nextGeneration = source
119
+ ? Math.max(...executors.map((e) => e.replacement?.generation ?? e.continuationGeneration)) +
120
+ 1
121
+ : 1;
122
+ const identity = executorIdentity(canonicalTaskName, nextGeneration);
123
+ const history = current.state?.checkpoints ??
124
+ [...previous]
125
+ .filter((p) => p.state.checkpoints?.planIdentity === before.identity)
126
+ .sort((a, b) => b.state.updatedAt.localeCompare(a.state.updatedAt))[0]?.state.checkpoints;
127
+ const now = this.deps.now();
128
+ const state = {
129
+ ...(current.state ?? disabledAutopilot(sessionId, now)),
130
+ requestedEnabled: true,
131
+ state: 'monitoring',
132
+ stopReason: null,
133
+ blocking: undefined,
134
+ planIdentity: current.identity,
135
+ planFingerprint: fingerprint,
136
+ generation: generation + 1,
137
+ lastControlId: null,
138
+ nextEvaluationAt: null,
139
+ consecutiveNoProgress: 0,
140
+ supervision: startSupervisionProtocol(fingerprint),
141
+ ...(history
142
+ ? {
143
+ checkpoints: {
144
+ ...history,
145
+ pendingTurnId: history.pendingTurnId ? turnId : null,
146
+ checkpointHandoffFailed: false,
147
+ rootContinuationFromTurnId: undefined,
148
+ },
149
+ }
150
+ : {}),
151
+ executor: source
152
+ ? {
153
+ ...source,
154
+ l1State: current.plan.steps[index].state,
155
+ outcome: 'failed',
156
+ blocking: undefined,
157
+ ownedProcesses: [],
158
+ commands: [],
159
+ continuationCount: 0,
160
+ resumeFailures: 0,
161
+ assignment: executorAssignment(source, 'unavailable'),
162
+ replacement: {
163
+ ...identity,
164
+ planIdentity: current.identity,
165
+ planFingerprint: fingerprint,
166
+ previous: executorAssignment(source, 'unavailable'),
167
+ reason: 'userDirectedTakeover',
168
+ evidence: 'explicit-user-takeover',
169
+ },
170
+ }
171
+ : undefined,
172
+ updatedAt: now,
173
+ };
174
+ const previousSessionIds = previous.map((p) => p.session.id);
175
+ if (!this.deps.store.complete(claim, state, [
176
+ {
177
+ sessionId,
178
+ type: 'autopilot.supervisor-taken-over',
179
+ occurredAt: now,
180
+ payload: {
181
+ previousSessionIds,
182
+ canonicalTaskName,
183
+ taskName: identity.taskName,
184
+ generation: identity.generation,
185
+ authority: 'explicit-user-takeover',
186
+ },
187
+ },
188
+ ], { threadId, turnId }))
189
+ return { accepted: false, code: 'TAKEOVER_CONTEXT_CHANGED' };
190
+ // Publication cannot undo committed ownership or mint another generation.
191
+ // The durable outbox and normal activity reconciliation can retry refresh.
192
+ try {
193
+ this.deps.changed(sessionId);
194
+ }
195
+ catch {
196
+ /* committed takeover remains accepted */
197
+ }
198
+ return {
199
+ accepted: true,
200
+ alreadyOwner: false,
201
+ identity,
202
+ previousSessionIds,
203
+ boundaryFinalRequired: Boolean(history?.pendingTurnId),
204
+ };
205
+ }
206
+ }
@@ -42,10 +42,10 @@ export function autopilotSnapshot(state, retryLimit, facts = {
42
42
  Number.isFinite(evaluationAt) &&
43
43
  evaluationAt > Date.parse(facts.observedAt);
44
44
  const rootWorking = facts.activeTurn;
45
- // Runtime observations are current at observedAt. A slow or old durable
46
- // transition must not turn an actually active root/timer/reconciliation or
47
- // installed wait lease into a false idle signal.
48
- const liveContinuation = parkedWait || scheduled || rootWorking || facts.executorActive || facts.reconciling;
45
+ // A reconciliation is an attempt to restore evidence, not a continuation.
46
+ // Actual work, an armed control, or an owned wait remain live evidence even
47
+ // when the durable transition is old.
48
+ const liveContinuation = parkedWait || scheduled || rootWorking || facts.executorActive;
49
49
  const healthy = state.requestedEnabled &&
50
50
  !state.checkpoints?.checkpointHandoffFailed &&
51
51
  facts.planMatches &&
@@ -66,7 +66,7 @@ export function autopilotSnapshot(state, retryLimit, facts = {
66
66
  ? 'waitingForAgentEvent'
67
67
  : healthy && scheduled
68
68
  ? 'continuationScheduled'
69
- : healthy && (supervision === 'probeRequired' || facts.reconciling)
69
+ : facts.reconciling || (healthy && supervision === 'probeRequired')
70
70
  ? 'checkingState'
71
71
  : healthy && rootWorking
72
72
  ? 'rootWorking'
@@ -193,7 +193,11 @@ export function parsePersistedSupervisedLifecycle(value) {
193
193
  ? parseExecutorAssignment(replacementPreviousValue)
194
194
  : undefined;
195
195
  const replacementReason = replacementValue &&
196
- stringValue(replacementValue.reason, ['explicitExecutorRejection', 'humanPermissionGranted']);
196
+ stringValue(replacementValue.reason, [
197
+ 'explicitExecutorRejection',
198
+ 'humanPermissionGranted',
199
+ 'userDirectedTakeover',
200
+ ]);
197
201
  const replacementEvidence = replacementValue && boundedText(replacementValue.evidence);
198
202
  if (!canonicalPosition ||
199
203
  !canonicalTaskName ||
@@ -13,6 +13,13 @@ export class WriterAcquisitionError extends Error {
13
13
  }
14
14
  export function writerAcquisitionProblem(kind) {
15
15
  switch (kind) {
16
+ case 'supervisorReplaced':
17
+ return {
18
+ status: 409,
19
+ code: 'SESSION_SUPERVISOR_REPLACED',
20
+ retryable: false,
21
+ detail: 'Another session took over this plan. Continue there, or direct a new session to take over.',
22
+ };
16
23
  case 'writerBusy':
17
24
  return {
18
25
  status: 409,
@@ -16,10 +16,37 @@ export function launchCodexAppServer(input) {
16
16
  });
17
17
  const rpc = new JsonRpcClient(child.stdout, child.stdin);
18
18
  child.once('error', (error) => rpc.fail(error));
19
+ child.stdin.on('error', (error) => rpc.fail(error));
20
+ // App-server diagnostics are not protocol output. Drain them without retaining
21
+ // potentially sensitive contents or letting a full stderr pipe block shutdown.
22
+ child.stderr.resume();
23
+ let closing = false;
24
+ let shutdownTimer;
25
+ child.once('exit', () => {
26
+ clearTimeout(shutdownTimer);
27
+ child.stdin.destroy();
28
+ });
29
+ // close follows stdout drainage; exit alone can precede a final RPC response.
30
+ child.once('close', () => rpc.fail(new Error('CODEX_APP_SERVER_EXITED')));
19
31
  return {
20
32
  child,
21
33
  rpc,
22
- close: () => child.kill('SIGTERM'),
34
+ close: () => {
35
+ if (closing)
36
+ return;
37
+ closing = true;
38
+ rpc.fail(new Error('CODEX_APP_SERVER_CLOSED'));
39
+ // EOF also releases older managed proxies blocked in a filesystem read.
40
+ child.stdin.end();
41
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null)
42
+ return;
43
+ child.kill('SIGTERM');
44
+ shutdownTimer = setTimeout(() => {
45
+ if (child.exitCode === null && child.signalCode === null)
46
+ child.kill('SIGKILL');
47
+ }, 3_000);
48
+ shutdownTimer.unref();
49
+ },
23
50
  onExit: (listener) => {
24
51
  child.once('exit', listener);
25
52
  return () => child.off('exit', listener);
@@ -17,6 +17,7 @@ import { gestaltOrgPlanHealthDynamicTool } from '../../../shared/contracts/org-p
17
17
  import { gestaltTestRunnerDynamicTool } from '../../../shared/contracts/host-tests.js';
18
18
  import { gestaltAutopilotWaitLeaseDynamicTool } from '../../../shared/contracts/autopilot-wait-lease.js';
19
19
  import { gestaltAgentCapacityRecoveryDynamicTool } from '../../../shared/contracts/agent-capacity-recovery.js';
20
+ import { gestaltOrgPlanTakeoverDynamicTool } from '../../../shared/contracts/org-plan-takeover.js';
20
21
  import { gestaltManagedPlaywrightDynamicTool } from '../../../shared/contracts/managed-playwright.js';
21
22
  import { countDiffLines } from '../../../shared/contracts/file-change.js';
22
23
  import { threadPlanName } from './thread-plan-name.js';
@@ -472,6 +473,135 @@ export class CodexSessionRuntime {
472
473
  });
473
474
  return true;
474
475
  }
476
+ /** Stops the previous root's actor tree without transferring its native collaboration namespace. */
477
+ async quiesceForTakeover(session, recordedProcesses = [], executor) {
478
+ let expired = false;
479
+ let timer;
480
+ try {
481
+ return await Promise.race([
482
+ this.quiesceTakeoverActors(session, recordedProcesses, executor, () => !expired),
483
+ new Promise((resolve) => {
484
+ timer = setTimeout(() => {
485
+ expired = true;
486
+ this.stop(session.id);
487
+ resolve(false);
488
+ }, 30_000);
489
+ }),
490
+ ]);
491
+ }
492
+ finally {
493
+ if (timer)
494
+ clearTimeout(timer);
495
+ }
496
+ }
497
+ async quiesceTakeoverActors(session, recordedProcesses, executor, allowed) {
498
+ const writer = await this.ensureWriter(session, new Date().toISOString());
499
+ if (!allowed()) {
500
+ await this.release(session.id);
501
+ return false;
502
+ }
503
+ if (writer.replacementCreated || writer.session.threadId !== session.threadId)
504
+ return false;
505
+ const resource = this.sessions.get(session.id);
506
+ const topology = await this.readExecutorTopology(writer.session);
507
+ if (!resource || !allowed() || topology.kind !== 'observed')
508
+ return false;
509
+ const current = () => allowed() &&
510
+ this.sessions.get(session.id) === resource &&
511
+ resource.active &&
512
+ resource.threadId === session.threadId;
513
+ const threads = [
514
+ {
515
+ id: topology.rootThreadId,
516
+ status: topology.rootActive ? 'active' : 'idle',
517
+ taskPath: '/root',
518
+ qualified: true,
519
+ },
520
+ ...topology.children,
521
+ ...(executor
522
+ ? [
523
+ {
524
+ id: executor.threadId,
525
+ taskPath: executor.taskPath,
526
+ status: 'unknown',
527
+ qualified: true,
528
+ },
529
+ ]
530
+ : []),
531
+ ];
532
+ const seen = new Set();
533
+ for (let index = 0; index < threads.length; index++) {
534
+ if (!current())
535
+ return false;
536
+ const thread = { ...threads[index] };
537
+ if (seen.has(thread.id))
538
+ continue;
539
+ if (seen.size >= 64)
540
+ return false;
541
+ seen.add(thread.id);
542
+ if (index > 0)
543
+ threads.push(...(await this.listDirectChildrenFromProcess(resource.process, thread.id, () => this.sessions.get(session.id) === resource &&
544
+ resource.active &&
545
+ resource.threadId === session.threadId)));
546
+ if (thread.qualified === false)
547
+ return false;
548
+ if (thread.status === 'unknown') {
549
+ const metadata = await resource.process.rpc.request('thread/read', {
550
+ threadId: thread.id,
551
+ includeTurns: false,
552
+ });
553
+ const observed = asRecord(asRecord(metadata)?.thread);
554
+ const status = String(asRecord(observed?.status)?.type);
555
+ if (observed?.id !== thread.id ||
556
+ observed.parentThreadId !== topology.rootThreadId ||
557
+ !['active', 'idle', 'notLoaded'].includes(status))
558
+ return false;
559
+ thread.status = status;
560
+ }
561
+ const processes = await this.inspectChildProcesses(writer.session, thread);
562
+ if (!current())
563
+ return false;
564
+ if (thread.status === 'notLoaded' &&
565
+ recordedProcesses.some((p) => p.ownerThreadId === thread.id && ['running', 'detached-active'].includes(p.state)))
566
+ return false;
567
+ if (thread.status !== 'notLoaded')
568
+ await this.interruptExecutor(writer.session, thread.id);
569
+ for (const process of processes) {
570
+ if (!current())
571
+ return false;
572
+ if (['running', 'detached-active'].includes(process.state) &&
573
+ !(await this.terminateChildProcess(writer.session, thread.id, process.processId, `takeover:${thread.id}:${process.itemId}`, process)))
574
+ return false;
575
+ }
576
+ }
577
+ if (recordedProcesses.some((process) => ['running', 'detached-active'].includes(process.state) &&
578
+ !seen.has(process.ownerThreadId)))
579
+ return false;
580
+ for (const threadId of seen) {
581
+ if (!current())
582
+ return false;
583
+ const result = await resource.process.rpc.request('thread/read', {
584
+ threadId,
585
+ includeTurns: false,
586
+ });
587
+ const thread = asRecord(asRecord(result)?.thread);
588
+ if (thread?.id !== threadId ||
589
+ !['idle', 'notLoaded'].includes(String(asRecord(thread.status)?.type)))
590
+ return false;
591
+ const processes = await this.inspectChildProcesses(writer.session, {
592
+ id: threadId,
593
+ status: String(asRecord(thread.status)?.type),
594
+ qualified: true,
595
+ });
596
+ if (processes.some((p) => ['running', 'detached-active'].includes(p.state)))
597
+ return false;
598
+ }
599
+ if (!current())
600
+ return false;
601
+ resource.beginExplicitShutdown();
602
+ resource.dispose();
603
+ return true;
604
+ }
475
605
  async queueTurnInput(session, turnId, text, clientUserMessageId) {
476
606
  const resource = this.sessions.get(session.id);
477
607
  if (!resource || !session.threadId)
@@ -1015,6 +1145,7 @@ export class CodexSessionRuntime {
1015
1145
  gestaltTestRunnerDynamicTool,
1016
1146
  gestaltAutopilotWaitLeaseDynamicTool,
1017
1147
  gestaltAgentCapacityRecoveryDynamicTool,
1148
+ gestaltOrgPlanTakeoverDynamicTool,
1018
1149
  gestaltManagedPlaywrightDynamicTool,
1019
1150
  ],
1020
1151
  });
@@ -1122,6 +1253,7 @@ export class CodexSessionRuntime {
1122
1253
  gestaltTestRunnerDynamicTool,
1123
1254
  gestaltAutopilotWaitLeaseDynamicTool,
1124
1255
  gestaltAgentCapacityRecoveryDynamicTool,
1256
+ gestaltOrgPlanTakeoverDynamicTool,
1125
1257
  gestaltManagedPlaywrightDynamicTool,
1126
1258
  ],
1127
1259
  ...(session.model ? { model: session.model } : {}),
@@ -28,6 +28,8 @@ function migrateWorkspaceGitDefaults(database) {
28
28
  }
29
29
  export function migrate(database) {
30
30
  database.exec(schema);
31
+ database.exec('CREATE TABLE IF NOT EXISTS org_plan_retired_supervisors (plan_identity TEXT NOT NULL, session_id TEXT NOT NULL, stopped INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(plan_identity, session_id))');
32
+ database.exec('CREATE TABLE IF NOT EXISTS org_plan_takeovers (plan_identity TEXT PRIMARY KEY, session_id TEXT NOT NULL, epoch INTEGER NOT NULL, phase TEXT NOT NULL)');
31
33
  database.exec('CREATE TABLE IF NOT EXISTS tool_efficiency (session_id TEXT PRIMARY KEY REFERENCES relay_sessions(id) ON DELETE CASCADE, state_json TEXT NOT NULL)');
32
34
  database.exec(`CREATE TABLE IF NOT EXISTS chat_transport_diagnostics (
33
35
  id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -0,0 +1,122 @@
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
+ /** A durable plan-scoped reservation also fences a superseded supervisor after relay restart. */
7
+ export class SqliteSupervisionTakeoverStore {
8
+ db;
9
+ autopilot;
10
+ constructor(db, autopilot) {
11
+ this.db = db;
12
+ this.autopilot = autopilot;
13
+ }
14
+ owner(planIdentity) {
15
+ const row = this.db
16
+ .prepare('SELECT session_id,epoch,phase FROM org_plan_takeovers WHERE plan_identity=?')
17
+ .get(planIdentity);
18
+ return row
19
+ ? { planIdentity, sessionId: row.session_id, epoch: row.epoch, phase: row.phase }
20
+ : null;
21
+ }
22
+ retired(planIdentity, sessionId) {
23
+ return Boolean(this.db
24
+ .prepare('SELECT 1 FROM org_plan_retired_supervisors WHERE plan_identity=? AND session_id=?')
25
+ .get(planIdentity, sessionId));
26
+ }
27
+ stopped(planIdentity, sessionId) {
28
+ return Boolean(this.db
29
+ .prepare('SELECT 1 FROM org_plan_retired_supervisors WHERE plan_identity=? AND session_id=? AND stopped=1')
30
+ .get(planIdentity, sessionId));
31
+ }
32
+ markStopped(claim, sessionId) {
33
+ return (this.db
34
+ .prepare("UPDATE org_plan_retired_supervisors SET stopped=1 WHERE plan_identity=? AND session_id=? AND EXISTS (SELECT 1 FROM org_plan_takeovers WHERE plan_identity=? AND session_id=? AND epoch=? AND phase='stopping')")
35
+ .run(claim.planIdentity, sessionId, claim.planIdentity, claim.sessionId, claim.epoch)
36
+ .changes === 1);
37
+ }
38
+ retire(claim, sessionIds) {
39
+ this.db.exec('BEGIN IMMEDIATE');
40
+ try {
41
+ const current = this.owner(claim.planIdentity);
42
+ if (!current ||
43
+ current.sessionId !== claim.sessionId ||
44
+ current.epoch !== claim.epoch ||
45
+ current.phase !== 'stopping') {
46
+ this.db.exec('ROLLBACK');
47
+ return false;
48
+ }
49
+ for (const sessionId of sessionIds)
50
+ this.db
51
+ .prepare('INSERT OR IGNORE INTO org_plan_retired_supervisors (plan_identity,session_id) VALUES (?,?)')
52
+ .run(claim.planIdentity, sessionId);
53
+ this.db.exec('COMMIT');
54
+ return true;
55
+ }
56
+ catch (error) {
57
+ this.db.exec('ROLLBACK');
58
+ throw error;
59
+ }
60
+ }
61
+ claim(planIdentity, sessionId) {
62
+ this.db.exec('BEGIN IMMEDIATE');
63
+ try {
64
+ const previous = this.owner(planIdentity);
65
+ if (previous?.phase === 'stopping' && previous.sessionId !== sessionId) {
66
+ const owner = this.db
67
+ .prepare('SELECT state,active_turn_id FROM relay_sessions WHERE id=?')
68
+ .get(previous.sessionId);
69
+ if (owner && (owner.state === 'turnActive' || owner.active_turn_id)) {
70
+ this.db.exec('ROLLBACK');
71
+ return null;
72
+ }
73
+ }
74
+ const epoch = previous?.sessionId === sessionId ? previous.epoch : (previous?.epoch ?? 0) + 1;
75
+ const phase = previous?.sessionId === sessionId ? previous.phase : 'stopping';
76
+ this.db
77
+ .prepare('INSERT INTO org_plan_takeovers (plan_identity,session_id,epoch,phase) VALUES (?,?,?,?) ON CONFLICT(plan_identity) DO UPDATE SET session_id=excluded.session_id,epoch=excluded.epoch,phase=excluded.phase')
78
+ .run(planIdentity, sessionId, epoch, phase);
79
+ this.db.exec('COMMIT');
80
+ return { planIdentity, sessionId, epoch, phase };
81
+ }
82
+ catch (error) {
83
+ this.db.exec('ROLLBACK');
84
+ throw error;
85
+ }
86
+ }
87
+ complete(claim, state, events, root) {
88
+ this.db.exec('BEGIN IMMEDIATE');
89
+ try {
90
+ const current = this.owner(claim.planIdentity);
91
+ const base = this.autopilot.find(state.sessionId);
92
+ const session = this.db
93
+ .prepare('SELECT thread_id,active_turn_id FROM relay_sessions WHERE id=?')
94
+ .get(state.sessionId);
95
+ if (!session ||
96
+ session.thread_id !== root.threadId ||
97
+ session.active_turn_id !== root.turnId ||
98
+ !current ||
99
+ current.sessionId !== claim.sessionId ||
100
+ current.epoch !== claim.epoch ||
101
+ current.phase !== 'stopping' ||
102
+ (base?.generation ?? 0) !== state.generation - 1) {
103
+ this.db.exec('ROLLBACK');
104
+ return false;
105
+ }
106
+ this.autopilot.save(state);
107
+ for (const e of events)
108
+ this.db
109
+ .prepare('INSERT INTO autopilot_outbox (session_id,type,payload_json,occurred_at) VALUES (?,?,?,?)')
110
+ .run(e.sessionId, e.type, JSON.stringify(e.payload), e.occurredAt);
111
+ this.db
112
+ .prepare("UPDATE org_plan_takeovers SET phase='ready' WHERE plan_identity=?")
113
+ .run(claim.planIdentity);
114
+ this.db.exec('COMMIT');
115
+ return true;
116
+ }
117
+ catch (error) {
118
+ this.db.exec('ROLLBACK');
119
+ throw error;
120
+ }
121
+ }
122
+ }
@@ -0,0 +1,32 @@
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
+ export const gestaltOrgPlanTakeoverDynamicTool = {
7
+ type: 'function',
8
+ name: 'gestalt_org_plan_takeover',
9
+ description: 'Take over the current unfinished Org Plan in this new supervisor session when the user explicitly instructed you to take over or continue it here. That instruction supplies authorization; do not ask for another approval or declare a permission blocker. Mobile fences previous supervisors, confirms their writers stopped, preserves checkpoint history, and returns the exact replacement executor identity for this root. Retries return the same pending identity, never a new generation: if that task name already exists in this root, resume it instead of spawning it again. Do not follow up or interrupt an executor belonging to another root. Does not waive review, model-policy, or pending-interaction gates. On failure, report the returned specific recovery code; never launch a competing writer.',
10
+ inputSchema: {
11
+ type: 'object',
12
+ additionalProperties: false,
13
+ required: ['version', 'reason'],
14
+ properties: {
15
+ version: { const: 1 },
16
+ reason: { const: 'userDirectedTakeover' },
17
+ },
18
+ },
19
+ };
20
+ export function isOrgPlanTakeoverCall(input) {
21
+ if (input.method !== 'item/tool/call' || !record(input.params))
22
+ return false;
23
+ const args = input.params.arguments;
24
+ return (input.params.tool === gestaltOrgPlanTakeoverDynamicTool.name &&
25
+ record(args) &&
26
+ Object.keys(args).length === 2 &&
27
+ args.version === 1 &&
28
+ args.reason === 'userDirectedTakeover');
29
+ }
30
+ function record(value) {
31
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
32
+ }
@@ -8,6 +8,7 @@
8
8
  "checkpoint-tool",
9
9
  "l2-report-boundary",
10
10
  "agent-capacity-recovery",
11
+ "user-directed-supervisor-takeover",
11
12
  "controller-status",
12
13
  "canonical-agent-identity",
13
14
  "session-verdict",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.62.2",
3
+ "version": "0.62.4",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",