gestalt-mobile 0.62.1 → 0.62.3

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:
@@ -248,8 +260,10 @@ permissions are never broadened to repair them. Kimi behavior is unchanged.
248
260
  Managed launch provides `GESTALT_MANAGER_BIN`. Direct Mobile launch discovers
249
261
  `gestalt` on `PATH`, or accepts an absolute executable path through that same
250
262
  environment variable. Without a manager or installed xerj, chat starts normally.
251
- `XERJ_READY_TIMEOUT_MS` bounds optional readiness, including discovery and the
252
- actual connection, with a five-second default. Startup never installs xerj,
263
+ `XERJ_READY_TIMEOUT_MS` bounds optional backend preparation with a five-second
264
+ default. XERJ's native MCP handshake gets a separate five-second allowance;
265
+ connection verification gets another bounded five seconds after thread startup.
266
+ Slow preparation cannot consume the handshake budget. Startup never installs xerj,
253
267
  downloads models or indexes repositories. Install explicitly with
254
268
  `gestalt xerj install`; inspect readiness with `gestalt xerj status`.
255
269
 
@@ -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,