gestalt-mobile 0.65.8 → 0.66.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.
Files changed (52) hide show
  1. package/README.md +22 -0
  2. package/dist/client/assets/index-BDsGojoG.js +128 -0
  3. package/dist/client/assets/{index-VDRT2Esv.css → index-DxsD-jG4.css} +1 -1
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/cli.js +2 -1
  6. package/dist/server/server/composition.contracts.js +179 -84
  7. package/dist/server/server/composition.js +65 -5
  8. package/dist/server/server/features/sessions/application/session-scratch.js +6 -0
  9. package/dist/server/server/features/sessions/clean-tmp/endpoint.js +68 -0
  10. package/dist/server/server/features/sessions/clean-tmp/use-case.js +82 -0
  11. package/dist/server/server/features/sessions/forget-session/endpoint.js +10 -2
  12. package/dist/server/server/features/sessions/forget-session/use-case.js +75 -0
  13. package/dist/server/server/features/sessions/get-session/endpoint.js +2 -1
  14. package/dist/server/server/features/sessions/list-sessions/endpoint.js +3 -0
  15. package/dist/server/server/features/sessions/promote-recent-thread/use-case.js +4 -1
  16. package/dist/server/server/features/sessions/register-routes.js +29 -2
  17. package/dist/server/server/features/sessions/start-session/endpoint.js +7 -0
  18. package/dist/server/server/features/sessions/start-session/use-case.js +4 -1
  19. package/dist/server/server/platform/catalog/filesystem-workspace-catalog.js +19 -1
  20. package/dist/server/server/platform/codex/codex-playwright.js +41 -3
  21. package/dist/server/server/platform/codex/codex-process-launcher.js +24 -2
  22. package/dist/server/server/platform/codex/codex-serena.js +2 -1
  23. package/dist/server/server/platform/codex/managed-playwright.js +48 -36
  24. package/dist/server/server/platform/codex/session-runtime.js +134 -4
  25. package/dist/server/server/platform/git/command.js +7 -1
  26. package/dist/server/server/platform/host-tests/runner.js +47 -6
  27. package/dist/server/server/platform/kimi/kimi-session-runtime.js +41 -0
  28. package/dist/server/server/platform/kimi/kimi-web-server-manager.js +13 -17
  29. package/dist/server/server/platform/maintenance/managed-upgrade.js +2 -1
  30. package/dist/server/server/platform/persistence/migrate.js +24 -0
  31. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +67 -0
  32. package/dist/server/server/platform/persistence/sqlite-session-repository.js +4 -0
  33. package/dist/server/server/platform/plans/org-plan-discovery.js +2 -0
  34. package/dist/server/server/platform/plans/plan-measurement-command.js +5 -1
  35. package/dist/server/server/platform/retrieval/codex-xerj.js +8 -1
  36. package/dist/server/server/platform/retrieval/managed-xerj.js +2 -1
  37. package/dist/server/server/platform/retrieval/repository-readiness.js +2 -1
  38. package/dist/server/server/platform/retrieval/xerj-indexer.js +21 -11
  39. package/dist/server/server/platform/scratch/child-environment.js +21 -0
  40. package/dist/server/server/platform/scratch/containment-fence.js +262 -0
  41. package/dist/server/server/platform/scratch/filesystem-scratch-cleanup.js +245 -0
  42. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +360 -0
  43. package/dist/server/server/platform/scratch/legacy-scratch-layouts.js +22 -0
  44. package/dist/server/server/platform/scratch/managed-scratch-owner.js +148 -0
  45. package/dist/server/server/platform/scratch/owned-process-group.js +53 -0
  46. package/dist/server/server/platform/scratch/owner-fence.js +27 -0
  47. package/dist/server/server/platform/scratch/scratch-filesystem.js +53 -0
  48. package/dist/server/server/platform/self-debug/workspace.js +3 -0
  49. package/dist/server/shared/contracts/session-forget.js +6 -0
  50. package/dist/server/shared/contracts/tmp-cleanup.js +6 -0
  51. package/package.json +1 -1
  52. package/dist/client/assets/index-CKJWzSwH.js +0 -128
@@ -26,7 +26,7 @@ import { exportControlPlaneTrace } from './features/control-plane-trace/export-t
26
26
  import { authorizationSessionId, authorizedDeviceId, localOwnerId, webAuthnCredentialId, } from './features/auth/domain/identifiers.js';
27
27
  import { deviceNickname } from './features/auth/domain/device-nickname.js';
28
28
  import { workspaceId } from './platform/catalog/workspace-id.js';
29
- import { planStatusDirectoryPath, planStatusFilePath, } from './platform/plans/filesystem-plan-status-source.js';
29
+ import { FilesystemPlanStatusSource, planStatusDirectoryPath, planStatusFilePath, } from './platform/plans/filesystem-plan-status-source.js';
30
30
  import { toOrgPlanAttentionAcknowledgement, toOrgPlanAttentionToolResponse, } from '../shared/contracts/org-plan-attention.js';
31
31
  import { toOrgPlanCheckpointToolResponse } from '../shared/contracts/org-plan-checkpoint.js';
32
32
  import { applyProjectionEvent, createChatProjection, acceptSnapshot, } from '../client/features/chat/chat-projection.js';
@@ -56,6 +56,11 @@ function liveAppServer(handles) {
56
56
  return () => {
57
57
  const handle = { calls: [], requests: [], pendingResponses: new Map() };
58
58
  handles.push(handle);
59
+ const close = () => {
60
+ for (const pending of handle.pendingResponses.values())
61
+ pending.reject(new Error('CODEX_SERVER_REQUEST_CANCELLED'));
62
+ handle.pendingResponses.clear();
63
+ };
59
64
  return {
60
65
  rpc: {
61
66
  request: async (method, params) => {
@@ -123,10 +128,11 @@ function liveAppServer(handles) {
123
128
  };
124
129
  },
125
130
  },
126
- close: () => {
127
- for (const pending of handle.pendingResponses.values())
128
- pending.reject(new Error('CODEX_SERVER_REQUEST_CANCELLED'));
129
- handle.pendingResponses.clear();
131
+ close,
132
+ // This in-memory double owns no OS process. Cancelling its queued replies
133
+ // completes its resource lifetime; real process proof is tested separately.
134
+ closeAndWait: async () => {
135
+ close();
130
136
  },
131
137
  onExit: () => () => { },
132
138
  };
@@ -3563,67 +3569,75 @@ describe('production composition', () => {
3563
3569
  };
3564
3570
  },
3565
3571
  });
3566
- expect((await fixture.app.inject({
3567
- method: 'PUT',
3568
- url: `/api/sessions/${fixture.sessionId}/autopilot`,
3569
- payload: { enabled: true },
3570
- })).statusCode).toBe(200);
3571
- // Initial supervision schedules its control and keeps a separate,
3572
- // bounded reconciliation watchdog while activity is still stale.
3573
- await vi.waitFor(() => expect(timers).toHaveLength(2));
3574
- const staleTimer = timers[0];
3575
- if (action === 'close') {
3576
- await writeFile(join(fixture.workspacePath, 'autopilot.org'), completedAutopilotPlanText());
3577
- await expect
3578
- .poll(async () => (await fixture.app.inject(`/api/sessions/${fixture.sessionId}/plan`)).json()
3579
- .allDone)
3580
- .toBe(true);
3581
- expect((await fixture.app.inject({
3582
- method: 'DELETE',
3583
- url: `/api/sessions/${fixture.sessionId}/plan`,
3584
- })).statusCode).toBe(204);
3585
- }
3586
- else if (action === 'replace') {
3587
- await installAutopilotPlan(fixture.app, fixture.sessionId, fixture.workspacePath, 'replacement');
3588
- }
3589
- else {
3590
- const method = action === 'delete' ? 'DELETE' : 'POST';
3591
- const suffix = action === 'delete' ? '' : `/${action}`;
3572
+ try {
3592
3573
  expect((await fixture.app.inject({
3593
- method,
3594
- url: `/api/sessions/${fixture.sessionId}${suffix}`,
3595
- })).statusCode).toBeGreaterThanOrEqual(200);
3596
- }
3597
- if (action === 'delete') {
3598
- const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
3599
- const row = database
3600
- .prepare('SELECT state, requested_enabled, stop_reason FROM autopilot_sessions WHERE session_id = ?')
3601
- .get(fixture.sessionId);
3602
- database.close();
3603
- // Forgetting cascades the terminal row with the session itself; the
3604
- // absence is the durable proof that no queued control can be reopened.
3605
- expect(row).toBeUndefined();
3606
- }
3607
- else if (action === 'replace') {
3608
- await vi.waitFor(() => expect(staleTimer.cancelled).toBe(true));
3609
- await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({
3610
- autopilot: { enabled: true, state: expect.stringMatching(/monitoring|backoff/) },
3611
- }));
3574
+ method: 'PUT',
3575
+ url: `/api/sessions/${fixture.sessionId}/autopilot`,
3576
+ payload: { enabled: true },
3577
+ })).statusCode).toBe(200);
3578
+ // Initial supervision schedules its control and keeps a separate,
3579
+ // bounded reconciliation watchdog while activity is still stale.
3580
+ await vi.waitFor(() => expect(timers).toHaveLength(2));
3581
+ const staleTimer = timers[0];
3582
+ if (action === 'close') {
3583
+ await writeFile(join(fixture.workspacePath, 'autopilot.org'), completedAutopilotPlanText());
3584
+ await expect
3585
+ .poll(async () => (await fixture.app.inject(`/api/sessions/${fixture.sessionId}/plan`)).json()
3586
+ .allDone)
3587
+ .toBe(true);
3588
+ expect((await fixture.app.inject({
3589
+ method: 'DELETE',
3590
+ url: `/api/sessions/${fixture.sessionId}/plan`,
3591
+ })).statusCode).toBe(204);
3592
+ }
3593
+ else if (action === 'replace') {
3594
+ await installAutopilotPlan(fixture.app, fixture.sessionId, fixture.workspacePath, 'replacement');
3595
+ }
3596
+ else {
3597
+ const method = action === 'delete' ? 'DELETE' : 'POST';
3598
+ const suffix = action === 'delete' ? '' : `/${action}`;
3599
+ const response = await fixture.app.inject({
3600
+ method,
3601
+ url: `/api/sessions/${fixture.sessionId}${suffix}`,
3602
+ });
3603
+ if (action === 'delete')
3604
+ expect(response.statusCode, response.body).toBe(204);
3605
+ else
3606
+ expect(response.statusCode).toBeGreaterThanOrEqual(200);
3607
+ }
3608
+ if (action === 'delete') {
3609
+ const database = new DatabaseSync(join(fixture.dataDir, 'relay.sqlite'));
3610
+ const row = database
3611
+ .prepare('SELECT state, requested_enabled, stop_reason FROM autopilot_sessions WHERE session_id = ?')
3612
+ .get(fixture.sessionId);
3613
+ database.close();
3614
+ // Forgetting cascades the terminal row with the session itself; the
3615
+ // absence is the durable proof that no queued control can be reopened.
3616
+ expect(row).toBeUndefined();
3617
+ }
3618
+ else if (action === 'replace') {
3619
+ await vi.waitFor(() => expect(staleTimer.cancelled).toBe(true));
3620
+ await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({
3621
+ autopilot: { enabled: true, state: expect.stringMatching(/monitoring|backoff/) },
3622
+ }));
3623
+ }
3624
+ else {
3625
+ await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({
3626
+ autopilot: {
3627
+ enabled: false,
3628
+ state: 'disabled',
3629
+ reason: action === 'close' ? 'planRemoved' : 'sessionEnded',
3630
+ },
3631
+ }));
3632
+ }
3633
+ expect(staleTimer.cancelled, action).toBe(true);
3634
+ staleTimer.callback();
3635
+ await Promise.resolve();
3636
+ expect(fixture.handles.flatMap((candidate) => candidate.calls)).not.toContain('turn/start');
3612
3637
  }
3613
- else {
3614
- await vi.waitFor(async () => expect((await fixture.app.inject(`/api/sessions/${fixture.sessionId}`)).json()).toMatchObject({
3615
- autopilot: {
3616
- enabled: false,
3617
- state: 'disabled',
3618
- reason: action === 'close' ? 'planRemoved' : 'sessionEnded',
3619
- },
3620
- }));
3638
+ finally {
3639
+ await fixture.app.close();
3621
3640
  }
3622
- expect(staleTimer.cancelled, action).toBe(true);
3623
- staleTimer.callback();
3624
- await Promise.resolve();
3625
- expect(fixture.handles.flatMap((candidate) => candidate.calls)).not.toContain('turn/start');
3626
- await fixture.app.close();
3627
3641
  }
3628
3642
  }, 15_000);
3629
3643
  it('production duplicate and missing completion notifications coalesce without double control', async () => {
@@ -5773,6 +5787,9 @@ describe('production composition', () => {
5773
5787
  ownTemporaryPaths(root, dataDir);
5774
5788
  await mkdir(join(root, 'workspace'));
5775
5789
  const writers = [];
5790
+ const reads = [];
5791
+ const releaseReads = [];
5792
+ let finishing = false;
5776
5793
  const unhandled = [];
5777
5794
  const onUnhandled = (reason) => unhandled.push(reason);
5778
5795
  process.on('unhandledRejection', onUnhandled);
@@ -5795,6 +5812,9 @@ describe('production composition', () => {
5795
5812
  },
5796
5813
  launchAppServer: () => {
5797
5814
  const writer = {};
5815
+ const close = () => {
5816
+ writer.closed = true;
5817
+ };
5798
5818
  return {
5799
5819
  rpc: {
5800
5820
  request: async (method, params) => {
@@ -5802,11 +5822,17 @@ describe('production composition', () => {
5802
5822
  writers.push(writer);
5803
5823
  return { thread: { id: `thread-${writers.length}` } };
5804
5824
  }
5805
- if (method === 'thread/read')
5806
- return await new Promise((resolve, reject) => {
5825
+ if (method === 'thread/read') {
5826
+ if (finishing)
5827
+ return { thread: { turns: [] } };
5828
+ const reading = new Promise((resolve, reject) => {
5807
5829
  writer.releaseRead = () => resolve({ thread: { turns: [] } });
5808
5830
  writer.rejectRead = () => reject(new Error('LATE_READ_FAILURE'));
5831
+ releaseReads.push(writer.releaseRead);
5809
5832
  });
5833
+ reads.push(reading);
5834
+ return await reading;
5835
+ }
5810
5836
  if (method === 'thread/list')
5811
5837
  return { data: [] };
5812
5838
  if (method === 'model/list')
@@ -5823,29 +5849,47 @@ describe('production composition', () => {
5823
5849
  },
5824
5850
  onServerRequest: () => () => { },
5825
5851
  },
5826
- close: () => { },
5852
+ close,
5853
+ // There is no child process in this double. Keep the deliberately
5854
+ // deferred reply independent so late reconciliation is still tested.
5855
+ closeAndWait: async () => {
5856
+ close();
5857
+ },
5827
5858
  onExit: () => () => { },
5828
5859
  };
5829
5860
  },
5830
5861
  });
5831
- const forgottenId = await createComposedSession(app);
5832
- await vi.waitFor(() => expect(writers[0]?.releaseRead).toBeTypeOf('function'));
5833
- expect((await app.inject({ method: 'DELETE', url: `/api/sessions/${forgottenId}` })).statusCode).toBe(204);
5834
- writers[0].rejectRead();
5835
- await Promise.resolve();
5836
- await Promise.resolve();
5837
- expect(unhandled).toEqual([]);
5838
- expect((await app.inject('/api/bootstrap')).statusCode).toBe(200);
5839
- const liveId = await createComposedSession(app);
5840
- await vi.waitFor(() => expect(writers[1]?.notify).toBeTypeOf('function'));
5841
- writers[1].notify({
5842
- method: 'thread/started',
5843
- params: { thread: { id: 'thread-2', status: { type: 'active' } } },
5844
- });
5845
- await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${liveId}`)).json()).toMatchObject({
5846
- agentActivity: { root: { state: 'working' } },
5847
- }));
5848
- await app.close();
5862
+ try {
5863
+ const forgottenId = await createComposedSession(app);
5864
+ await vi.waitFor(() => expect(writers[0]?.releaseRead).toBeTypeOf('function'));
5865
+ const forgotten = await app.inject({
5866
+ method: 'DELETE',
5867
+ url: `/api/sessions/${forgottenId}`,
5868
+ });
5869
+ expect(forgotten.statusCode, forgotten.body).toBe(204);
5870
+ expect(writers[0]?.closed).toBe(true);
5871
+ writers[0].rejectRead();
5872
+ await Promise.resolve();
5873
+ await Promise.resolve();
5874
+ expect(unhandled).toEqual([]);
5875
+ expect((await app.inject('/api/bootstrap')).statusCode).toBe(200);
5876
+ const liveId = await createComposedSession(app);
5877
+ await vi.waitFor(() => expect(writers[1]?.notify).toBeTypeOf('function'));
5878
+ writers[1].notify({
5879
+ method: 'thread/started',
5880
+ params: { thread: { id: 'thread-2', status: { type: 'active' } } },
5881
+ });
5882
+ await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${liveId}`)).json()).toMatchObject({
5883
+ agentActivity: { root: { state: 'working' } },
5884
+ }));
5885
+ }
5886
+ finally {
5887
+ finishing = true;
5888
+ for (const release of releaseReads)
5889
+ release();
5890
+ await Promise.allSettled(reads);
5891
+ await app.close();
5892
+ }
5849
5893
  });
5850
5894
  it('uses the relay root for detached history reads and Open never resumes', async () => {
5851
5895
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
@@ -5990,6 +6034,7 @@ describe('production composition', () => {
5990
6034
  ['GET', '/api/sessions/recent-threads', '/api/sessions/recent-threads', 'protected'],
5991
6035
  ['HEAD', '/api/sessions/recent-threads', '/api/sessions/recent-threads', 'protected'],
5992
6036
  ['GET', '/api/sessions/:id', '/api/sessions/session-1', 'protected'],
6037
+ ['DELETE', '/api/sessions/:id', '/api/sessions/session-1', 'protected'],
5993
6038
  ['GET', '/api/sessions/:id/attention', '/api/sessions/session-1/attention', 'protected'],
5994
6039
  [
5995
6040
  'POST',
@@ -6151,6 +6196,7 @@ describe('production composition', () => {
6151
6196
  ],
6152
6197
  ['POST', '/api/git/clone', '/api/git/clone', 'protected'],
6153
6198
  ['POST', '/api/maintenance/quit', '/api/maintenance/quit', 'protected'],
6199
+ ['POST', '/api/maintenance/clean-tmp', '/api/maintenance/clean-tmp', 'protected'],
6154
6200
  ['POST', '/api/maintenance/upgrade', '/api/maintenance/upgrade', 'protected'],
6155
6201
  ['GET', '/api/maintenance/upgrade', '/api/maintenance/upgrade', 'protected'],
6156
6202
  ['HEAD', '/api/maintenance/upgrade', '/api/maintenance/upgrade', 'protected'],
@@ -6360,6 +6406,55 @@ describe('production composition', () => {
6360
6406
  });
6361
6407
  });
6362
6408
  describeCompositionConcern('sessions', () => {
6409
+ it('does not return retained display history as current when an in-flight plan refresh is superseded by mandatory rejection', async () => {
6410
+ const { app, sessionId, workspacePath } = await createProductionAutopilotFixture();
6411
+ const url = `/api/sessions/${sessionId}/plan`;
6412
+ const previous = (await app.inject(url)).json();
6413
+ const actualRefresh = FilesystemPlanStatusSource.prototype.refresh;
6414
+ let release;
6415
+ const blocked = new Promise((resolve) => {
6416
+ release = resolve;
6417
+ });
6418
+ const refresh = vi
6419
+ .spyOn(FilesystemPlanStatusSource.prototype, 'refresh')
6420
+ .mockImplementationOnce(async (id) => {
6421
+ expect(id).toBe(sessionId);
6422
+ await blocked;
6423
+ // ActiveLease retires an older in-flight read with null after its policy
6424
+ // selection revision changes; its existing filesystem test covers that gate.
6425
+ return null;
6426
+ });
6427
+ const pending = app.inject(url).then((response) => response);
6428
+ try {
6429
+ await vi.waitFor(() => expect(refresh).toHaveBeenCalledOnce());
6430
+ const source = refresh.mock.contexts[0];
6431
+ await writeFile(join(planStatusDirectoryPath(workspacePath, sessionId), 'unsupported.plan-status.json'), JSON.stringify({
6432
+ schemaVersion: 1,
6433
+ modelPolicyVersion: 2,
6434
+ requiredCapabilities: ['l1-model-policy-v2'],
6435
+ }));
6436
+ await actualRefresh.call(source, sessionId);
6437
+ const rejected = (await app.inject(`/api/sessions/${sessionId}`)).json();
6438
+ expect(rejected.autopilot.executionAdmission).toMatchObject({
6439
+ allowed: false,
6440
+ reason: 'POLICY_PROJECTION_UNAVAILABLE',
6441
+ });
6442
+ expect(rejected.lastOrgPlan.title).toBe(previous.title);
6443
+ release?.();
6444
+ expect((await pending).statusCode).toBe(204);
6445
+ expect((await app.inject({
6446
+ method: 'PUT',
6447
+ url: `/api/sessions/${sessionId}/autopilot`,
6448
+ payload: { enabled: true },
6449
+ })).statusCode).toBe(409);
6450
+ }
6451
+ finally {
6452
+ release?.();
6453
+ await pending;
6454
+ refresh.mockRestore();
6455
+ await app.close();
6456
+ }
6457
+ });
6363
6458
  it('persists replay-stable tool groups from runtime notifications without charging provider tokens', async () => {
6364
6459
  const homeDirectory = await mkdtemp(join(tmpdir(), 'gestalt-efficiency-home-'));
6365
6460
  ownTemporaryPaths(homeDirectory);
@@ -15,6 +15,12 @@ import { SqliteTransportDiagnostics } from './platform/persistence/sqlite-transp
15
15
  import { buildApp } from './app.js';
16
16
  import { ManagedUpgrade } from './platform/maintenance/managed-upgrade.js';
17
17
  import { LocalHostTestRunner } from './platform/host-tests/runner.js';
18
+ import { FilesystemSessionScratch } from './platform/scratch/filesystem-session-scratch.js';
19
+ import { FilesystemScratchCleanup } from './platform/scratch/filesystem-scratch-cleanup.js';
20
+ import { ForgetSession } from './features/sessions/forget-session/use-case.js';
21
+ import { SqliteForgetOperationStore } from './platform/persistence/sqlite-forget-operation-store.js';
22
+ import { CleanSessionScratch } from './features/sessions/clean-tmp/use-case.js';
23
+ import { withHistoryScratchContainment, withScratchContainment, } from './platform/scratch/containment-fence.js';
18
24
  import { loadWorkspaceHostTestConfig, within } from './platform/host-tests/config.js';
19
25
  import { handleHostTestTool } from './features/host-tests/application/handle-tool.js';
20
26
  import { gestaltTestRunnerDynamicTool } from '../shared/contracts/host-tests.js';
@@ -142,6 +148,7 @@ export async function composeRelayApp(options) {
142
148
  throw error;
143
149
  }
144
150
  const sessions = new SqliteSessionRepository(database);
151
+ const forgetOperations = new SqliteForgetOperationStore(database);
145
152
  // Only sessions found while opening the relay database belong to a previous
146
153
  // process. A listen hook can run after a new session has already started in
147
154
  // this process; detaching that live writer would make restore and activity
@@ -484,6 +491,7 @@ export async function composeRelayApp(options) {
484
491
  const debugHome = options.homeDirectory ?? homedir();
485
492
  const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
486
493
  const homeDirectory = options.homeDirectory ?? homedir();
494
+ const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id));
487
495
  // Constructing the manager is cheap (no spawn until `ensure`); building it
488
496
  // before the model catalog lets the catalog reuse the gestalt-owned servers.
489
497
  const kimiManager = options.kimiServerManager ??
@@ -491,6 +499,7 @@ export async function composeRelayApp(options) {
491
499
  ? new KimiWebServerManager({
492
500
  stateBase: kimiStateBase(homeDirectory),
493
501
  sourceShareDir: join(homeDirectory, '.kimi-code'),
502
+ serviceScratch: (profileKey) => sessionScratch.allocateService(root, `kimi-${profileKey}`),
494
503
  })
495
504
  : undefined);
496
505
  const kimiModels = new KimiModelCatalog(kimiManager ?? null, kimiManager != null);
@@ -514,11 +523,11 @@ export async function composeRelayApp(options) {
514
523
  const retrievalCapability = options.xerj === 'off'
515
524
  ? { check: async () => ({ status: 'absent' }) }
516
525
  : (options.retrievalCapability ?? new ManagedXerj());
517
- const xerjIndexer = new XerjIndexer(root, options.xerj ?? 'manual', retrievalCapability);
526
+ const xerjIndexer = new XerjIndexer(root, options.xerj ?? 'manual', retrievalCapability, process.env, console.warn, () => sessionScratch.allocateService(root, 'xerj-indexer'));
518
527
  const xerj = new CodexXerj(retrievalCapability);
519
528
  const serenaInstallation = new ManagedSerena();
520
529
  const capabilities = new CodexCapabilities(xerj, new CodexSerena(serenaInstallation));
521
- const playwright = new CodexPlaywright(new ManagedPlaywright());
530
+ const playwright = new CodexPlaywright(new ManagedPlaywright(), sessionScratch);
522
531
  const playwrightAuthority = (session) => {
523
532
  const plan = supervisedPlans.findCurrent(session.id);
524
533
  const active = plan?.steps[currentExecutableL1Index(plan)];
@@ -1375,7 +1384,7 @@ export async function composeRelayApp(options) {
1375
1384
  await runtime.validateExecutorPolicy(sessionId, report.requested);
1376
1385
  assertCurrent();
1377
1386
  return { ...report.requested, assertCurrent };
1378
- })
1387
+ }, sessionScratch)
1379
1388
  : null;
1380
1389
  const handleKimiNotification = (sessionId, event) => {
1381
1390
  const occurredAt = new Date().toISOString();
@@ -1424,6 +1433,7 @@ export async function composeRelayApp(options) {
1424
1433
  kimiRuntime = kimiManager
1425
1434
  ? new KimiSessionRuntime({
1426
1435
  servers: kimiManager,
1436
+ scratch: sessionScratch,
1427
1437
  skillsFor: async (session) => {
1428
1438
  const config = await resolveSkills(session);
1429
1439
  return config?.map((entry) => ({
@@ -1455,6 +1465,8 @@ export async function composeRelayApp(options) {
1455
1465
  }, (planPath, stepId, snapshot) => checkpointPlanMeasurement(planMeasurementHelperPath, planPath, stepId, snapshot));
1456
1466
  }
1457
1467
  const saveSession = (session) => {
1468
+ if (forgetOperations.find(session.id))
1469
+ return;
1458
1470
  const prior = sessions.find(session.id);
1459
1471
  sessions.save(session);
1460
1472
  events.publish(journal.append(session.id, 'session.updated', session, session.updatedAt));
@@ -1469,6 +1481,7 @@ export async function composeRelayApp(options) {
1469
1481
  if (becameRuntimeReady)
1470
1482
  autopilot.restore(session.id);
1471
1483
  };
1484
+ const publishSession = (session) => withScratchContainment(session.workspacePath, () => saveSession(session));
1472
1485
  if (kimiRuntime) {
1473
1486
  // A gestalt-owned kimi web process exited or its websocket dropped: stop
1474
1487
  // the durable session like the codex supervisor does, without a resume
@@ -1483,6 +1496,37 @@ export async function composeRelayApp(options) {
1483
1496
  }
1484
1497
  /** Routes a session to the runtime owning its provider's llm service. */
1485
1498
  const ownerRuntime = (session) => session.provider === 'kimi' ? kimiRuntime : runtime;
1499
+ const scratchCleanup = new FilesystemScratchCleanup();
1500
+ const cleanTmp = new CleanSessionScratch({
1501
+ sessions: () => sessions.list(),
1502
+ knownWorkspacePaths: async () => [root, ...sessions.knownWorkspacePaths()],
1503
+ additionalWorkspacePaths: () => workspaces.knownWorkspacePaths(),
1504
+ storage: scratchCleanup,
1505
+ });
1506
+ const forgetSessions = new ForgetSession({
1507
+ operations: forgetOperations,
1508
+ find: (id) => sessions.find(id),
1509
+ now: () => new Date().toISOString(),
1510
+ release: async (session) => {
1511
+ providerRecovery.cancel(session.id);
1512
+ autopilot.cancel(session.id, 'sessionEnded');
1513
+ planMeasurementRefresh?.stop(session.id);
1514
+ dismissPendingInteractions(session.id, new Date().toISOString());
1515
+ activity.dispose(session.id);
1516
+ await hostTests?.cancelSession(session.id);
1517
+ await capacityRecoveryTasks.get(session.id)?.catch(() => undefined);
1518
+ await ownerRuntime(session)?.releaseForForget(session);
1519
+ await playwright.waitForRelease(session.id);
1520
+ },
1521
+ clean: (session, operationId) => scratchCleanup.cleanSession(session, () => {
1522
+ const operation = forgetOperations.find(session.id);
1523
+ return operation?.operationId === operationId && operation.phase === 'cleaning';
1524
+ }, () => sessions.list()),
1525
+ changed: (operation) => {
1526
+ if (sessions.find(operation.sessionId))
1527
+ events.publish(journal.append(operation.sessionId, 'session.forget.updated', operation, operation.updatedAt));
1528
+ },
1529
+ });
1486
1530
  if (runtime) {
1487
1531
  scheduleAgentCapacityRecovery = (sessionId, acknowledge) => {
1488
1532
  if (closing || capacityRecoveries.has(sessionId) || !acknowledge())
@@ -1618,7 +1662,7 @@ export async function composeRelayApp(options) {
1618
1662
  if (!within(await realpath(root), await realpath(workspace)))
1619
1663
  throw new Error('Host test workspace is outside the configured root');
1620
1664
  return loadWorkspaceHostTestConfig(workspace);
1621
- });
1665
+ }, sessionScratch);
1622
1666
  await hostTests.initialize();
1623
1667
  }
1624
1668
  const transportDiagnostics = new SqliteTransportDiagnostics(database);
@@ -1700,9 +1744,11 @@ export async function composeRelayApp(options) {
1700
1744
  sessions: {
1701
1745
  list: () => sessions.list().map((session) => {
1702
1746
  const plan = supervisedPlans.find(session.id);
1747
+ const forgetOperation = forgetOperations.find(session.id);
1703
1748
  return {
1704
1749
  ...withPendingInteractions(session),
1705
1750
  ...(plan ? { plan } : {}),
1751
+ ...(forgetOperation ? { forgetOperation } : {}),
1706
1752
  };
1707
1753
  }),
1708
1754
  },
@@ -1772,6 +1818,7 @@ export async function composeRelayApp(options) {
1772
1818
  createId: () => id,
1773
1819
  now: () => new Date().toISOString(),
1774
1820
  save: saveSession,
1821
+ publish: publishSession,
1775
1822
  workspaces: debugCatalog,
1776
1823
  profiles: options.profiles,
1777
1824
  skillProfiles,
@@ -1795,9 +1842,12 @@ export async function composeRelayApp(options) {
1795
1842
  }
1796
1843
  : undefined,
1797
1844
  sessionRoutes: {
1845
+ forget: (id) => forgetSessions.execute(id),
1846
+ forgetOperation: (id) => forgetOperations.find(id),
1798
1847
  createId: randomUUID,
1799
1848
  now: () => new Date().toISOString(),
1800
1849
  save: saveSession,
1850
+ publish: publishSession,
1801
1851
  find: (id) => withPendingInteractions(sessions.find(id)),
1802
1852
  list: () => sessions.list().map((session) => withPendingInteractions(session)),
1803
1853
  plan: (id) => supervisedPlans.find(id),
@@ -1920,6 +1970,7 @@ export async function composeRelayApp(options) {
1920
1970
  now: () => new Date().toISOString(),
1921
1971
  list: () => sessions.list(),
1922
1972
  save: saveSession,
1973
+ publish: (session) => withHistoryScratchContainment(session.workspacePath, () => saveSession(session)),
1923
1974
  read: (session) => {
1924
1975
  const owner = ownerRuntime(session);
1925
1976
  if (!owner)
@@ -1984,6 +2035,7 @@ export async function composeRelayApp(options) {
1984
2035
  publishInteractionResolved(sessionId, requestId, occurredAt, outcome);
1985
2036
  },
1986
2037
  },
2038
+ tmpCleanup: cleanTmp,
1987
2039
  sessionEvents: {
1988
2040
  exists: (id) => sessions.find(id) !== null,
1989
2041
  replay: (id, after) => {
@@ -2006,7 +2058,7 @@ export async function composeRelayApp(options) {
2006
2058
  const refreshed = await planStatusSource.refresh(id);
2007
2059
  if (refreshed?.kind === 'updated')
2008
2060
  return refreshed.plan;
2009
- return refreshed ? null : supervisedPlans.find(id);
2061
+ return refreshed ? null : supervisedPlans.findCurrent(id);
2010
2062
  },
2011
2063
  open: async (id, planName) => {
2012
2064
  const session = sessions.find(id);
@@ -2144,6 +2196,8 @@ export async function composeRelayApp(options) {
2144
2196
  await mapWithConcurrency(sessions
2145
2197
  .list()
2146
2198
  .filter((session) => persistedSessionIds.has(session.id) && session.threadId !== null), 2, async (session) => {
2199
+ if (forgetOperations.find(session.id))
2200
+ return;
2147
2201
  // The status lease must repopulate the authoritative plan projection before
2148
2202
  // a durable coordinator is restored. Writer detachment is a process concern,
2149
2203
  // not a human disable: a later fenced continuation can reacquire it safely.
@@ -2160,6 +2214,8 @@ export async function composeRelayApp(options) {
2160
2214
  });
2161
2215
  };
2162
2216
  app.addHook('onListen', async () => {
2217
+ for (const id of forgetOperations.pendingIds())
2218
+ void forgetSessions.execute(id).catch(() => undefined);
2163
2219
  if (options.xerj)
2164
2220
  xerjIndexer.start();
2165
2221
  const profile = (await options.profiles.list()).find((item) => item.state === 'ok')?.name;
@@ -2170,6 +2226,8 @@ export async function composeRelayApp(options) {
2170
2226
  // enter KimiSkillCatalog through their normal operation paths instead.
2171
2227
  // Rehydrate durable attachments even when this relay does not launch Codex writers.
2172
2228
  for (const session of sessions.list()) {
2229
+ if (forgetOperations.find(session.id))
2230
+ continue;
2173
2231
  if (!persistedSessionIds.has(session.id) || session.provider === 'kimi')
2174
2232
  continue;
2175
2233
  if (session.lastOrgPlan?.attached && session.lastOrgPlan.path) {
@@ -2192,6 +2250,7 @@ export async function composeRelayApp(options) {
2192
2250
  closing = true;
2193
2251
  providerRecovery.dispose();
2194
2252
  await hostTests?.close();
2253
+ await forgetSessions.drain();
2195
2254
  await retrievalCapability.close?.();
2196
2255
  await xerjIndexer.close();
2197
2256
  for (const [sessionId, timer] of capacityRecoveryTimers) {
@@ -2223,6 +2282,7 @@ export async function composeRelayApp(options) {
2223
2282
  }
2224
2283
  }
2225
2284
  runtime?.stopAll();
2285
+ await runtime?.drainReleases();
2226
2286
  kimiRuntime?.stopAll();
2227
2287
  await kimiManager?.stopAll();
2228
2288
  planStatusSource.closeAll();
@@ -0,0 +1,6 @@
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 {};
@@ -0,0 +1,68 @@
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 requestSchema = z.object({}).strict();
9
+ const counter = z.number().int().min(0).max(Number.MAX_SAFE_INTEGER);
10
+ const responseSchema = z.object({
11
+ status: z.enum(['complete', 'partial']),
12
+ folders: z.object({ removed: counter, skipped: counter, failed: counter }),
13
+ workspaces: z.object({
14
+ cleaned: counter,
15
+ removed: counter,
16
+ skipped: counter,
17
+ failed: counter,
18
+ unavailable: counter,
19
+ }),
20
+ reasons: z.object({
21
+ protected: counter,
22
+ busy: counter,
23
+ lease: counter,
24
+ unrecognized: counter,
25
+ unsafe: counter,
26
+ unavailable: counter,
27
+ io: counter,
28
+ }),
29
+ });
30
+ export function registerCleanTmp(app, cleanup) {
31
+ app.post('/api/maintenance/clean-tmp', async (request, reply) => {
32
+ reply.header('Cache-Control', 'no-store');
33
+ if (!requestSchema.safeParse(request.body === undefined ? {} : request.body).success ||
34
+ !requestSchema.safeParse(request.query ?? {}).success)
35
+ return reply
36
+ .code(400)
37
+ .send(problem('INVALID_REQUEST', 400, 'Clean TMP does not accept paths or options.'));
38
+ if (!cleanup)
39
+ return reply
40
+ .code(503)
41
+ .send(problem('TMP_CLEANUP_UNAVAILABLE', 503, 'Temporary cleanup is unavailable.'));
42
+ try {
43
+ const result = await cleanup.execute();
44
+ const response = responseSchema.parse({
45
+ status: result.status,
46
+ folders: {
47
+ removed: result.folders.removed,
48
+ skipped: result.folders.skipped,
49
+ failed: result.folders.failed,
50
+ },
51
+ workspaces: {
52
+ cleaned: result.workspaces.cleaned,
53
+ removed: result.workspaces.removed,
54
+ skipped: result.workspaces.skipped,
55
+ failed: result.workspaces.failed,
56
+ unavailable: result.workspaces.unavailable,
57
+ },
58
+ reasons: result.folders.reasons,
59
+ });
60
+ return reply.send(response);
61
+ }
62
+ catch {
63
+ return reply
64
+ .code(503)
65
+ .send(problem('TMP_CLEANUP_UNAVAILABLE', 503, 'Could not inspect temporary storage.'));
66
+ }
67
+ });
68
+ }