gestalt-mobile 0.44.3 → 0.45.0

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.
@@ -16,8 +16,8 @@ SPDX-License-Identifier: AGPL-3.0-or-later
16
16
  <link rel="icon" href="/icons/gestalt-mobile-192.png" />
17
17
  <link rel="apple-touch-icon" href="/icons/gestalt-mobile-180.png" />
18
18
  <title>Gestalt Mobile</title>
19
- <script type="module" crossorigin src="/assets/index-DYZT_mLU.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-DEVCzFB9.css">
19
+ <script type="module" crossorigin src="/assets/index-UqpTKH1P.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-Copi3ec4.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -20,6 +20,7 @@ import { registerAutopilotRoutes } from './features/autopilot/register-routes.js
20
20
  import { registerFileRoutes } from './features/files/register-routes.js';
21
21
  import { registerMaintenanceRoutes } from './features/maintenance/register-routes.js';
22
22
  import { registerPwaRoutes } from './features/pwa/register-routes.js';
23
+ import { registerSelfDebug } from './features/self-debug/endpoint.js';
23
24
  export async function buildApp(deps) {
24
25
  // Keep the default boundary finite even when an endpoint forgot a narrower schema.
25
26
  const app = fastify({ logger: false, bodyLimit: 1024 * 1024 });
@@ -47,6 +48,8 @@ export async function buildApp(deps) {
47
48
  registerAuthRoutes(app, deps);
48
49
  registerCatalogRoutes(app, { bootstrap: deps.bootstrap, sessionDefaults: deps.sessionDefaults });
49
50
  registerSessionRoutes(app, deps);
51
+ if (deps.selfDebug)
52
+ registerSelfDebug(app, deps.selfDebug);
50
53
  if (deps.autopilot)
51
54
  registerAutopilotRoutes(app, deps.autopilot, deps.sessionRoutes?.idempotency, deps.sessionRoutes ? (id) => deps.sessionRoutes?.find(id)?.provider : undefined);
52
55
  if (deps.orgPlanAttention)
@@ -4,6 +4,8 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { once } from 'node:events';
7
+ import { execFile } from 'node:child_process';
8
+ import { promisify } from 'node:util';
7
9
  import { createHash } from 'node:crypto';
8
10
  import { mkdtemp, mkdir, rm, symlink, writeFile } from 'node:fs/promises';
9
11
  import { DatabaseSync } from 'node:sqlite';
@@ -2104,6 +2106,84 @@ describe('production composition', () => {
2104
2106
  .filter((call) => call === 'turn/start')).toHaveLength(1));
2105
2107
  await fixture.app.close();
2106
2108
  });
2109
+ it('continues the same unloaded executor once after authoritative roster recovery', async () => {
2110
+ const handles = [];
2111
+ const launch = liveAppServer(handles);
2112
+ let unavailable = true;
2113
+ const timers = [];
2114
+ const fixture = await createProductionAutopilotFixture({
2115
+ activitySchedule: () => () => { },
2116
+ autopilotSchedule: (callback) => {
2117
+ const timer = { callback, cancelled: false, fired: false };
2118
+ timers.push(timer);
2119
+ return () => {
2120
+ timer.cancelled = true;
2121
+ };
2122
+ },
2123
+ launchAppServer: () => {
2124
+ const server = launch();
2125
+ handles.at(-1).respond = (method) => {
2126
+ if (method === 'thread/list' && unavailable)
2127
+ throw new Error('RPC_DOWN');
2128
+ if (method === 'thread/list')
2129
+ return {
2130
+ data: [
2131
+ {
2132
+ id: 'preserved-executor',
2133
+ status: { type: 'notLoaded' },
2134
+ source: { subAgent: { thread_spawn: { agent_path: '/root/l1' } } },
2135
+ },
2136
+ ],
2137
+ };
2138
+ if (method === 'thread/backgroundTerminals/list')
2139
+ throw new CodexJsonRpcError(-32600, 'thread not found: preserved-executor');
2140
+ return undefined;
2141
+ };
2142
+ return server;
2143
+ },
2144
+ });
2145
+ onTestFinished(() => fixture.app.close());
2146
+ await vi.waitFor(async () => {
2147
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({ autopilot: { enabled: true, reason: 'reconcileFailed' } });
2148
+ });
2149
+ unavailable = false;
2150
+ await fixture.app.inject({
2151
+ method: 'POST',
2152
+ url: `/api/sessions/${fixture.sessionId}/activity/refresh`,
2153
+ });
2154
+ const starts = () => handles
2155
+ .flatMap((handle) => handle.requests)
2156
+ .filter((request) => request.method === 'turn/start');
2157
+ await vi.waitFor(async () => {
2158
+ expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({
2159
+ agentActivity: {
2160
+ confidence: 'fresh',
2161
+ subagents: [
2162
+ {
2163
+ id: 'preserved-executor',
2164
+ canonicalPosition: 'L1',
2165
+ },
2166
+ ],
2167
+ },
2168
+ autopilot: { enabled: true },
2169
+ });
2170
+ expect(timers.some((timer) => !timer.cancelled && !timer.fired)).toBe(true);
2171
+ });
2172
+ for (let attempt = 0; attempt < 8 && starts().length === 0; attempt += 1) {
2173
+ const timer = timers.find((candidate) => !candidate.cancelled && !candidate.fired);
2174
+ expect(timer).toBeDefined();
2175
+ timer.fired = true;
2176
+ timer.callback();
2177
+ await vi.waitFor(() => expect(starts().length > 0 ||
2178
+ timers.some((candidate) => !candidate.cancelled && !candidate.fired)).toBe(true));
2179
+ }
2180
+ expect(starts()).toHaveLength(1);
2181
+ expect(starts()[0].params).toMatchObject({ threadId: 'preserved-executor' });
2182
+ for (const timer of timers.filter((candidate) => candidate.fired))
2183
+ timer.callback();
2184
+ await Promise.resolve();
2185
+ expect(starts()).toHaveLength(1);
2186
+ });
2107
2187
  it('production incompatible reconcile remains supervised and schedules reinspection', async () => {
2108
2188
  let reconciliations = 0;
2109
2189
  const timers = [];
@@ -3428,6 +3508,83 @@ describe('production composition', () => {
3428
3508
  });
3429
3509
  });
3430
3510
  describeCompositionConcern('sessions', () => {
3511
+ it('starts Self DEBUG as an independent root with the installed executor settings and persists its incident packet', async () => {
3512
+ const root = await mkdtemp(join(tmpdir(), 'gestalt-debug-root-'));
3513
+ const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-debug-state-'));
3514
+ const homeDirectory = await mkdtemp(join(tmpdir(), 'gestalt-debug-home-'));
3515
+ ownTemporaryPaths(root, dataDir, homeDirectory);
3516
+ await mkdir(join(root, 'workspace'));
3517
+ const debugRoot = join(homeDirectory, '.gestalt', 'self-debug');
3518
+ await mkdir(debugRoot, { recursive: true });
3519
+ const exec = promisify(execFile);
3520
+ for (const name of ['gestalt', 'gestalt-mobile', 'gestalt-agents']) {
3521
+ await exec('git', ['init', join(debugRoot, name)]);
3522
+ await exec('git', [
3523
+ '-C',
3524
+ join(debugRoot, name),
3525
+ 'remote',
3526
+ 'add',
3527
+ 'origin',
3528
+ `https://github.com/dyne/${name}.git`,
3529
+ ]);
3530
+ }
3531
+ // Isolate the same profile path production resolves, including an explicit CODEX_HOME.
3532
+ const codexHome = join(homeDirectory, '.codex');
3533
+ vi.stubEnv('CODEX_HOME', codexHome);
3534
+ onTestFinished(() => {
3535
+ vi.unstubAllEnvs();
3536
+ });
3537
+ await mkdir(join(codexHome, 'agents'), { recursive: true });
3538
+ await writeFile(join(codexHome, 'agents', 'org-plan-executor.toml'), 'model = "configured-debug-model"\nmodel_reasoning_effort = "high"\n');
3539
+ const handles = [];
3540
+ const app = await composeAuthorizedApp({
3541
+ root,
3542
+ dataDir,
3543
+ homeDirectory,
3544
+ relyingParty,
3545
+ installedCodexVersion: 'codex-cli 0.144.3',
3546
+ startAppServers: true,
3547
+ launchAppServer: liveAppServer(handles),
3548
+ componentVersions: [{ id: 'codex', label: 'Codex', version: '0.144.3' }],
3549
+ sessionModelCatalog: { list: async () => ['gpt-5.6-terra', 'configured-debug-model'] },
3550
+ profiles: {
3551
+ list: async () => [],
3552
+ require: async () => ({ name: 'default', state: 'ok', status: 'ready' }),
3553
+ },
3554
+ });
3555
+ onTestFinished(() => app.close());
3556
+ const sourceId = await createComposedSession(app);
3557
+ await app.inject({ method: 'POST', url: `/api/sessions/${sourceId}/stop`, payload: {} });
3558
+ const confirmation = (await app.inject(`/api/sessions/${sourceId}/debug`)).json();
3559
+ expect(confirmation.context.mobileSession).toBe(sourceId);
3560
+ const response = await app.inject({
3561
+ method: 'POST',
3562
+ url: `/api/sessions/${sourceId}/debug`,
3563
+ payload: { confirmationId: confirmation.confirmationId },
3564
+ });
3565
+ expect(response.statusCode).toBe(202);
3566
+ const debug = response.json();
3567
+ expect(debug.id).not.toBe(sourceId);
3568
+ expect(debug.workspacePath).toBe(debugRoot);
3569
+ expect(debug.model).toBe('configured-debug-model');
3570
+ expect(debug.threadId).not.toBe(confirmation.context.codexThread);
3571
+ const request = handles
3572
+ .flatMap((handle) => handle.requests)
3573
+ .find((request) => request.method === 'turn/start' &&
3574
+ request.params.threadId === debug.threadId);
3575
+ expect(request?.params).toMatchObject({
3576
+ model: 'configured-debug-model',
3577
+ effort: 'high',
3578
+ input: [{ type: 'text', text: expect.stringContaining('User detected an error') }],
3579
+ });
3580
+ expect((await app.inject('/api/sessions'))
3581
+ .json()
3582
+ .find((session) => session.id === debug.id).selfDebug).toEqual(debug.selfDebug);
3583
+ expect((await app.inject(`/api/sessions/${debug.id}/debug/trace`)).json()).toMatchObject({
3584
+ context: confirmation.context,
3585
+ sourceAgent: { status: 'unavailable' },
3586
+ });
3587
+ });
3431
3588
  it('does not resolve a Git operation target outside the configured root', async () => {
3432
3589
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
3433
3590
  const outside = await mkdtemp(join(tmpdir(), 'gestalt-mobile-outside-'));
@@ -3971,7 +4128,7 @@ describe('production composition', () => {
3971
4128
  // Model and skill catalogs run for bootstrap and session start; the active child closes with the relay.
3972
4129
  await vi.waitFor(() => expect(closed).toBe(5));
3973
4130
  });
3974
- it('reconciles an interaction cleared upstream as no longer pending', async () => {
4131
+ it('reconciles cleared interactions and unloaded child rosters through later activity', async () => {
3975
4132
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
3976
4133
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
3977
4134
  ownTemporaryPaths(root, dataDir);
@@ -3979,6 +4136,7 @@ describe('production composition', () => {
3979
4136
  const handles = [];
3980
4137
  const activityCallbacks = [];
3981
4138
  const activityDiagnostic = vi.fn();
4139
+ let includeUnloadedChild = false;
3982
4140
  const app = await composeAuthorizedApp({
3983
4141
  root,
3984
4142
  dataDir,
@@ -4008,6 +4166,20 @@ describe('production composition', () => {
4008
4166
  throw new Error('READ_DOWN');
4009
4167
  return { thread: { id: 'thread-1', status: { type: 'idle' }, turns: [] } };
4010
4168
  }
4169
+ if (method === 'thread/list')
4170
+ return {
4171
+ data: includeUnloadedChild
4172
+ ? [
4173
+ {
4174
+ id: 'l4',
4175
+ status: { type: 'notLoaded' },
4176
+ source: { subAgent: { thread_spawn: { agent_path: '/root/l4' } } },
4177
+ },
4178
+ ]
4179
+ : [],
4180
+ };
4181
+ if (method === 'thread/backgroundTerminals/list')
4182
+ throw new CodexJsonRpcError(-32600, 'thread not found: l4');
4011
4183
  if (method === 'model/list')
4012
4184
  return { data: [{ id: 'gpt-5.6-terra' }] };
4013
4185
  if (method === 'skills/list')
@@ -4049,6 +4221,19 @@ describe('production composition', () => {
4049
4221
  state: 'ready',
4050
4222
  agentActivity: { confidence: 'fresh' },
4051
4223
  });
4224
+ // A durable child may be absent from the writer's process registry.
4225
+ // Its process RPC must not prevent roster publication or future refreshes.
4226
+ includeUnloadedChild = true;
4227
+ await app.inject({ method: 'POST', url: `/api/sessions/${sessionId}/activity/refresh` });
4228
+ await vi.waitFor(async () => {
4229
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
4230
+ agentActivity: {
4231
+ confidence: 'fresh',
4232
+ subagents: [{ id: 'l4', canonicalPosition: 'L4', state: 'disconnected' }],
4233
+ },
4234
+ });
4235
+ });
4236
+ expect(activityDiagnostic).not.toHaveBeenCalled();
4052
4237
  const reconciliationCalls = handle.calls.filter((method) => method === 'thread/read' || method === 'thread/list');
4053
4238
  const ordinarySave = await app.inject({
4054
4239
  method: 'POST',
@@ -4121,7 +4306,10 @@ describe('production composition', () => {
4121
4306
  params: { thread: { id: 'thread-1', status: { type: 'active' } } },
4122
4307
  });
4123
4308
  expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
4124
- agentActivity: { root: { state: 'working' }, subagents: [] },
4309
+ agentActivity: {
4310
+ root: { state: 'working' },
4311
+ subagents: [{ id: 'l4', canonicalPosition: 'L4', state: 'disconnected' }],
4312
+ },
4125
4313
  });
4126
4314
  const pending = handle.request({
4127
4315
  id: 7,
@@ -11,6 +11,9 @@ import { SessionModelConfig } from './platform/codex/session-model-config.js';
11
11
  import { basename, dirname, join, resolve } from 'node:path';
12
12
  import { debuglog } from 'node:util';
13
13
  import { buildApp } from './app.js';
14
+ import { SelfDebugWorkspace } from './platform/self-debug/workspace.js';
15
+ import { createSelfDebugSession } from './features/self-debug/create-session.js';
16
+ import { startSession } from './features/sessions/start-session/use-case.js';
14
17
  import { FilesystemWorkspaceCatalog } from './platform/catalog/filesystem-workspace-catalog.js';
15
18
  import { FilesystemWorkspaceFiles } from './platform/filesystem/filesystem-workspace-files.js';
16
19
  import { protocolCompatibility } from './platform/codex/protocol-compatibility.js';
@@ -381,6 +384,8 @@ export async function composeRelayApp(options) {
381
384
  options.onAutopilotCoordinator?.(autopilot);
382
385
  const workspaces = new FilesystemWorkspaceCatalog(root);
383
386
  const workspaceFiles = new FilesystemWorkspaceFiles();
387
+ const debugHome = options.homeDirectory ?? homedir();
388
+ const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
384
389
  const homeDirectory = options.homeDirectory ?? homedir();
385
390
  // Constructing the manager is cheap (no spawn until `ensure`); building it
386
391
  // before the model catalog lets the catalog reuse the gestalt-owned servers.
@@ -1226,6 +1231,111 @@ export async function composeRelayApp(options) {
1226
1231
  protocolCompatible: protocol.compatible,
1227
1232
  providers: providerAvailability,
1228
1233
  },
1234
+ selfDebug: runtime
1235
+ ? {
1236
+ find: (id) => sessions.find(id),
1237
+ createId: randomUUID,
1238
+ now: () => new Date().toISOString(),
1239
+ context: (source) => {
1240
+ const control = autopilotStore.find(source.id);
1241
+ return {
1242
+ handoffTrace: control?.checkpoints?.activeHandoffId ?? null,
1243
+ control: control?.lastControlId ?? null,
1244
+ mobileSession: source.id,
1245
+ codexThread: source.provider === 'codex' ? source.threadId : null,
1246
+ sourceThread: source.threadId,
1247
+ provider: source.provider,
1248
+ capturedAt: new Date().toISOString(),
1249
+ versions: options.componentVersions ?? [],
1250
+ };
1251
+ },
1252
+ readTrace: (debug) => debugWorkspace.readTrace(debug),
1253
+ create: (context) => createSelfDebugSession(context, {
1254
+ createId: randomUUID,
1255
+ now: () => new Date().toISOString(),
1256
+ settings: async () => {
1257
+ const installed = await debugWorkspace.settings();
1258
+ const source = sessions.find(context.mobileSession);
1259
+ const defaults = await sessionDefaults.read();
1260
+ return {
1261
+ ...installed,
1262
+ model: source?.modelSettings?.executorModel ??
1263
+ defaults?.executorModel ??
1264
+ installed.model,
1265
+ reasoningEffort: source?.modelSettings?.executorReasoningEffort ??
1266
+ defaults?.executorReasoningEffort ??
1267
+ installed.reasoningEffort,
1268
+ };
1269
+ },
1270
+ capture: async (id, capturedContext, agent) => {
1271
+ const captured = await debugWorkspace.capture(id, capturedContext, agent);
1272
+ return {
1273
+ ...captured,
1274
+ absoluteTracePath: join(captured.root, captured.debug.tracePath),
1275
+ };
1276
+ },
1277
+ askSource: async (id, context, debug) => {
1278
+ const source = sessions.find(context.mobileSession);
1279
+ if (source && source.threadId === (context.sourceThread ?? context.codexThread))
1280
+ await debugWorkspace.askSource(id, source, debug, async (prompt) => {
1281
+ const sourceRuntime = ownerRuntime(source);
1282
+ // Never resume or replace the source writer merely to ask for diagnostics.
1283
+ if (!sourceRuntime?.ownsWriter(source.id))
1284
+ throw new Error('DEBUG_SOURCE_UNAVAILABLE');
1285
+ if (source.state === 'turnActive' && source.activeTurnId)
1286
+ await sourceRuntime.queueTurnInput(source, source.activeTurnId, prompt, `self-debug-${id}`);
1287
+ else if (source.state === 'ready') {
1288
+ const started = await sourceRuntime.startTurn(source, prompt, `self-debug-${id}`, new Date().toISOString());
1289
+ saveSession(started);
1290
+ activity.observe({
1291
+ sessionId: source.id,
1292
+ occurredAt: started.updatedAt,
1293
+ kind: 'turnStarted',
1294
+ threadId: started.threadId,
1295
+ turnId: started.activeTurnId,
1296
+ });
1297
+ }
1298
+ else
1299
+ throw new Error('DEBUG_SOURCE_UNAVAILABLE');
1300
+ });
1301
+ },
1302
+ createSession: async (id, root, agent) => {
1303
+ await debugWorkspace.prepare();
1304
+ const debugCatalog = new FilesystemWorkspaceCatalog(root);
1305
+ const [workspace] = await debugCatalog.list();
1306
+ return startSession({
1307
+ workspaceId: workspace.id,
1308
+ profile: 'default',
1309
+ provider: 'codex',
1310
+ model: agent.model,
1311
+ reasoningEffort: agent.reasoningEffort,
1312
+ sandbox: 'workspace-git',
1313
+ approvalPolicy: 'never',
1314
+ }, {
1315
+ createId: () => id,
1316
+ now: () => new Date().toISOString(),
1317
+ save: saveSession,
1318
+ workspaces: debugCatalog,
1319
+ profiles: options.profiles,
1320
+ skillProfiles,
1321
+ skillCatalog,
1322
+ sessionModels,
1323
+ });
1324
+ },
1325
+ start: (session) => runtime.start(session, new Date().toISOString()),
1326
+ startTurn: (session, prompt, messageId) => runtime.startTurn(session, prompt, messageId, new Date().toISOString()),
1327
+ find: (id) => sessions.find(id),
1328
+ save: saveSession,
1329
+ onStarted: (session) => activity.observe({
1330
+ sessionId: session.id,
1331
+ occurredAt: session.updatedAt,
1332
+ kind: 'turnStarted',
1333
+ threadId: session.threadId,
1334
+ turnId: session.activeTurnId,
1335
+ }),
1336
+ }),
1337
+ }
1338
+ : undefined,
1229
1339
  sessionRoutes: {
1230
1340
  createId: randomUUID,
1231
1341
  now: () => new Date().toISOString(),
@@ -69,8 +69,14 @@ function classifySupervisedActivity(activity, plan) {
69
69
  (process.state === 'running' || process.state === 'detached-active'));
70
70
  return !historical || supervisedProcess;
71
71
  });
72
+ // A fresh authoritative roster can retain the current executor while its
73
+ // runtime is unloaded. Re-reading that same status cannot load it: allow the
74
+ // coordinator's fenced continuation to resume the existing physical thread.
75
+ const resumable = (child) => child.canonicalPosition === `L${position}` &&
76
+ Boolean(child.taskPath && child.canonicalTaskName) &&
77
+ child.state === 'disconnected';
72
78
  // An aggregate-only observation cannot prove which child is historical.
73
- if (retained.length === activity.subagents.length)
79
+ if (retained.length === activity.subagents.length && !retained.some(resumable))
74
80
  return classifyAgentActivity(activity);
75
81
  if (activity.root.state === 'awaitingHuman' ||
76
82
  retained.some((child) => child.state === 'awaitingHuman'))
@@ -82,12 +88,12 @@ function classifySupervisedActivity(activity, plan) {
82
88
  (process.state === 'running' || process.state === 'detached-active'))))
83
89
  return 'active';
84
90
  if (activity.root.state === 'disconnected' ||
85
- retained.some((child) => child.state === 'disconnected'))
91
+ retained.some((child) => child.state === 'disconnected' && !resumable(child)))
86
92
  return 'reconcile';
87
93
  const rootSettled = activity.root.state === 'idle' ||
88
94
  activity.root.state === 'blocked' ||
89
95
  activity.root.state === 'awaitingAgent';
90
- const childrenSettled = retained.every((child) => child.state === 'idle' || child.state === 'blocked');
96
+ const childrenSettled = retained.every((child) => child.state === 'idle' || child.state === 'blocked' || resumable(child));
91
97
  return rootSettled && childrenSettled ? 'settled' : 'observe';
92
98
  }
93
99
  /** A deliberately pure, exhaustive safety gate. Adapters may only enact this result. */
@@ -5,6 +5,66 @@
5
5
  */
6
6
  import { DatabaseSync } from 'node:sqlite';
7
7
  const relevant = /^(?:org-plan\.|autopilot\.|agent\.activity\.|session\.status\.)/;
8
+ // Export structural telemetry only. Event types alone do not imply payload safety.
9
+ const diagnosticFields = new Set([
10
+ 'traceId',
11
+ 'handoffId',
12
+ 'controlId',
13
+ 'turnId',
14
+ 'requestId',
15
+ 'threadId',
16
+ 'sessionId',
17
+ 'generation',
18
+ 'sequence',
19
+ 'state',
20
+ 'status',
21
+ 'reason',
22
+ 'code',
23
+ 'enabled',
24
+ 'requestedEnabled',
25
+ 'desiredState',
26
+ 'stopReason',
27
+ 'failureCount',
28
+ 'noProgressCount',
29
+ 'canonicalPosition',
30
+ 'taskPath',
31
+ 'taskName',
32
+ 'continuationGeneration',
33
+ 'activeHandoffId',
34
+ 'lastControlId',
35
+ 'lastTurnId',
36
+ 'confidence',
37
+ 'observedAt',
38
+ 'root',
39
+ 'subagents',
40
+ 'processes',
41
+ 'aggregateSubagents',
42
+ 'aggregateProcesses',
43
+ 'kind',
44
+ 'id',
45
+ 'parentThreadId',
46
+ 'running',
47
+ 'completed',
48
+ 'pending',
49
+ 'count',
50
+ ]);
51
+ export function redactDiagnosticPayload(value, depth = 0) {
52
+ if (depth > 8)
53
+ return null;
54
+ if (typeof value === 'string')
55
+ return value.length <= 200 && /^[a-zA-Z0-9_./:@+-]*$/.test(value) ? value : '[redacted]';
56
+ if (typeof value === 'number')
57
+ return Number.isFinite(value) ? value : null;
58
+ if (typeof value === 'boolean' || value === null)
59
+ return value;
60
+ if (Array.isArray(value))
61
+ return value.slice(0, 100).map((item) => redactDiagnosticPayload(item, depth + 1));
62
+ if (!value || typeof value !== 'object')
63
+ return null;
64
+ return Object.fromEntries(Object.entries(value)
65
+ .filter(([key]) => diagnosticFields.has(key))
66
+ .map(([key, item]) => [key, redactDiagnosticPayload(item, depth + 1)]));
67
+ }
8
68
  function objectPayload(value) {
9
69
  try {
10
70
  const parsed = JSON.parse(value);
@@ -50,12 +110,13 @@ export function exportControlPlaneTrace(databasePath, sessionId, generatedAt = n
50
110
  const database = new DatabaseSync(databasePath, { readOnly: true });
51
111
  try {
52
112
  const rows = database
53
- .prepare('SELECT sequence,occurred_at,type,payload_json FROM session_events WHERE session_id = ? ORDER BY sequence')
113
+ .prepare("SELECT sequence,occurred_at,type,payload_json FROM session_events WHERE session_id = ? AND (type LIKE 'org-plan.%' OR type LIKE 'autopilot.%' OR type LIKE 'agent.activity.%' OR type LIKE 'session.status.%') ORDER BY sequence DESC LIMIT 5000")
54
114
  .all(sessionId);
55
115
  const events = rows
116
+ .reverse()
56
117
  .filter((row) => relevant.test(row.type))
57
118
  .map((row) => {
58
- const payload = objectPayload(row.payload_json);
119
+ const payload = redactDiagnosticPayload(objectPayload(row.payload_json));
59
120
  return {
60
121
  sequence: row.sequence,
61
122
  occurredAt: row.occurred_at,
@@ -0,0 +1,34 @@
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 { selfDebugPrompt, } from '../../../shared/contracts/self-debug.js';
7
+ import { RelaySession } from '../sessions/model/relay-session.js';
8
+ export async function createSelfDebugSession(context, deps) {
9
+ const id = deps.createId();
10
+ const agent = await deps.settings();
11
+ const captured = await deps.capture(id, context, agent);
12
+ // Diagnostic collection is best effort; source-agent failure never blocks the new root.
13
+ try {
14
+ await deps.askSource(id, context, captured.debug);
15
+ }
16
+ catch {
17
+ /* Captured evidence remains sufficient to begin. */
18
+ }
19
+ let session = await deps.createSession(id, captured.root, agent);
20
+ session = { ...session, selfDebug: captured.debug };
21
+ deps.save(session);
22
+ try {
23
+ session = await deps.start(session);
24
+ deps.save(session);
25
+ session = await deps.startTurn(session, selfDebugPrompt(captured.debug, captured.absoluteTracePath), `self-debug-root-${id}`);
26
+ deps.save(session);
27
+ deps.onStarted(session);
28
+ return session;
29
+ }
30
+ catch (error) {
31
+ deps.save(RelaySession.rehydrate(deps.find(id) ?? session).requireAttention(deps.now()).snapshot);
32
+ throw error;
33
+ }
34
+ }
@@ -0,0 +1,81 @@
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 { z } from 'zod';
7
+ import { problem } from '../../platform/http/problem.js';
8
+ const paramsSchema = z.object({ sessionId: z.string().min(1).max(200) });
9
+ const bodySchema = z.object({ confirmationId: z.string().min(1).max(200) }).strict();
10
+ /** A confirmation is bound to one existing thread; repeat submits share the same operation. */
11
+ export function registerSelfDebug(app, deps) {
12
+ const confirmations = new Map();
13
+ app.get('/api/sessions/:sessionId/debug', async (request, reply) => {
14
+ const parsed = paramsSchema.safeParse(request.params);
15
+ const source = parsed.success ? deps.find(parsed.data.sessionId) : null;
16
+ if (!source?.threadId)
17
+ return reply
18
+ .code(404)
19
+ .send(problem('DEBUG_SESSION_NOT_FOUND', 404, 'Select an existing Chat session.'));
20
+ const now = Date.parse(deps.now());
21
+ for (const [key, value] of confirmations)
22
+ if (value.expiresAt <= now)
23
+ confirmations.delete(key);
24
+ if (confirmations.size >= 100)
25
+ return reply
26
+ .code(429)
27
+ .send(problem('DEBUG_CONFIRMATION_LIMIT', 429, 'Too many pending debug requests. Try again shortly.'));
28
+ const confirmationId = deps.createId();
29
+ const context = deps.context(source);
30
+ confirmations.set(confirmationId, { context, expiresAt: now + 30 * 60 * 1000 });
31
+ return { confirmationId, context };
32
+ });
33
+ app.post('/api/sessions/:sessionId/debug', { bodyLimit: 1024 }, async (request, reply) => {
34
+ const params = paramsSchema.safeParse(request.params);
35
+ const body = bodySchema.safeParse(request.body);
36
+ const confirmation = body.success ? confirmations.get(body.data.confirmationId) : null;
37
+ if (!params.success ||
38
+ !confirmation ||
39
+ confirmation.context.mobileSession !== params.data.sessionId ||
40
+ confirmation.expiresAt <= Date.parse(deps.now()))
41
+ return reply
42
+ .code(409)
43
+ .send(problem('DEBUG_CONFIRMATION_EXPIRED', 409, 'Reopen DEBUG to confirm the current session details.'));
44
+ if (!confirmation.operation) {
45
+ const source = deps.find(params.data.sessionId);
46
+ if (!source ||
47
+ source.threadId !== (confirmation.context.sourceThread ?? confirmation.context.codexThread))
48
+ return reply
49
+ .code(409)
50
+ .send(problem('DEBUG_SOURCE_CHANGED', 409, 'The source session changed. Reopen DEBUG.'));
51
+ confirmation.operation = deps.create(confirmation.context);
52
+ }
53
+ try {
54
+ return reply.code(202).send(await confirmation.operation);
55
+ }
56
+ catch {
57
+ // Keep the rejected operation: a transport retry must never duplicate a partial session.
58
+ return reply
59
+ .code(503)
60
+ .send(problem('DEBUG_START_FAILED', 503, 'Self DEBUG could not start. Check Sessions for a saved debug session before trying again.'));
61
+ }
62
+ });
63
+ app.get('/api/sessions/:sessionId/debug/trace', async (request, reply) => {
64
+ const params = paramsSchema.safeParse(request.params);
65
+ const session = params.success ? deps.find(params.data.sessionId) : null;
66
+ if (!session?.selfDebug)
67
+ return reply
68
+ .code(404)
69
+ .send(problem('DEBUG_TRACE_NOT_FOUND', 404, 'This session has no diagnostic trace.'));
70
+ try {
71
+ return reply
72
+ .type('application/json; charset=utf-8')
73
+ .send(await deps.readTrace(session.selfDebug));
74
+ }
75
+ catch {
76
+ return reply
77
+ .code(404)
78
+ .send(problem('DEBUG_TRACE_NOT_FOUND', 404, 'The diagnostic trace is no longer available.'));
79
+ }
80
+ });
81
+ }
@@ -175,6 +175,7 @@ function copy(snapshot) {
175
175
  return {
176
176
  ...snapshot,
177
177
  ...(snapshot.modelSettings ? { modelSettings: { ...snapshot.modelSettings } } : {}),
178
+ ...(snapshot.selfDebug ? { selfDebug: structuredClone(snapshot.selfDebug) } : {}),
178
179
  ...(snapshot.effectiveSkillSelection === undefined
179
180
  ? {}
180
181
  : {