gestalt-mobile 0.68.3 → 0.68.5

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 (31) hide show
  1. package/README.md +15 -4
  2. package/dist/client/assets/index-CCTlWqX8.css +1 -0
  3. package/dist/client/assets/index-Dl5gXKZh.js +183 -0
  4. package/dist/client/index.html +2 -2
  5. package/dist/server/server/composition.contracts.js +198 -9
  6. package/dist/server/server/composition.js +39 -10
  7. package/dist/server/server/features/plans/application/plan-attachment-supervision.js +27 -0
  8. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +10 -0
  9. package/dist/server/server/features/plans/execute-plan/endpoint.js +1 -1
  10. package/dist/server/server/features/sessions/application/workspace-conflict.js +19 -0
  11. package/dist/server/server/features/sessions/forget-session/endpoint.js +7 -0
  12. package/dist/server/server/features/sessions/forget-session/use-case.js +8 -2
  13. package/dist/server/server/features/sessions/register-routes.js +1 -0
  14. package/dist/server/server/features/sessions/restore-session/endpoint.js +10 -1
  15. package/dist/server/server/features/sessions/start-turn/use-case.js +13 -1
  16. package/dist/server/server/platform/codex/session-runtime.js +18 -0
  17. package/dist/server/server/platform/http/problem-handler.js +9 -0
  18. package/dist/server/server/platform/kimi/kimi-session-runtime.js +5 -0
  19. package/dist/server/server/platform/persistence/migrate.js +17 -0
  20. package/dist/server/server/platform/persistence/sqlite-event-journal.js +6 -2
  21. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +38 -6
  22. package/dist/server/server/platform/persistence/sqlite-session-repository.js +29 -7
  23. package/dist/server/server/platform/persistence/sqlite-workspace-lifecycle.js +59 -0
  24. package/dist/server/server/platform/plans/filesystem-plan-status-source.js +2 -2
  25. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +3 -1
  26. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +123 -0
  27. package/dist/server/shared/contracts/org-plan-execution.js +1 -1
  28. package/dist/server/shared/contracts/plan-signal.js +2 -1
  29. package/package.json +1 -1
  30. package/dist/client/assets/index-BZ3ivopC.js +0 -183
  31. package/dist/client/assets/index-DRbCnCbk.css +0 -1
@@ -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-BZ3ivopC.js"></script>
20
- <link rel="stylesheet" crossorigin href="/assets/index-DRbCnCbk.css">
19
+ <script type="module" crossorigin src="/assets/index-Dl5gXKZh.js"></script>
20
+ <link rel="stylesheet" crossorigin href="/assets/index-CCTlWqX8.css">
21
21
  </head>
22
22
  <body>
23
23
  <div id="app"></div>
@@ -143,10 +143,10 @@ function liveAppServer(handles) {
143
143
  };
144
144
  };
145
145
  }
146
- async function createComposedSession(app) {
146
+ async function createComposedSession(app, workspaceName = 'workspace') {
147
147
  const workspace = (await app.inject('/api/bootstrap'))
148
148
  .json()
149
- .workspaces[0]?.children.find((item) => item.name === 'workspace');
149
+ .workspaces[0]?.children.find((item) => item.name === workspaceName);
150
150
  expect(workspace).toBeDefined();
151
151
  const created = await app.inject({
152
152
  method: 'POST',
@@ -1865,6 +1865,21 @@ describe('production composition', () => {
1865
1865
  expect(opened.statusCode).toBe(200);
1866
1866
  expect(opened.json()).toMatchObject({ title: 'Autopilot fixture', allDone: false });
1867
1867
  expect((await app.inject(`/api/sessions/${sessionId}/plan`)).statusCode).toBe(200);
1868
+ expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
1869
+ lastOrgPlan: { supervision: false },
1870
+ autopilot: { enabled: false },
1871
+ });
1872
+ // This coordinator fixture begins execution through the supervisor's explicit
1873
+ // helper publication, independently of the passive visualizer attachment.
1874
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, sessionId), planPath), JSON.stringify({
1875
+ schemaVersion: 1,
1876
+ planPath,
1877
+ reason: 'supervision-start',
1878
+ updatedAt: new Date().toISOString(),
1879
+ }));
1880
+ await vi.waitFor(async () => expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
1881
+ lastOrgPlan: { supervision: true },
1882
+ }));
1868
1883
  await app.listen({ host: '127.0.0.1', port: 0 });
1869
1884
  const address = app.server.address();
1870
1885
  if (!address || typeof address === 'string')
@@ -1963,6 +1978,8 @@ describe('production composition', () => {
1963
1978
  ownTemporaryPaths(root, dataDir);
1964
1979
  const workspacePath = join(root, 'workspace');
1965
1980
  await mkdir(workspacePath);
1981
+ const otherWorkspace = join(root, 'workspace-other');
1982
+ await mkdir(otherWorkspace);
1966
1983
  const handles = [];
1967
1984
  const app = await composeAuthorizedApp({
1968
1985
  root,
@@ -1982,7 +1999,10 @@ describe('production composition', () => {
1982
1999
  });
1983
2000
  onTestFinished(() => app.close());
1984
2001
  // Managed TMPDIR fixtures share an ancestor publication fence during session creation.
1985
- const sessions = [await createComposedSession(app), await createComposedSession(app)];
2002
+ const sessions = [
2003
+ await createComposedSession(app),
2004
+ await createComposedSession(app, 'workspace-other'),
2005
+ ];
1986
2006
  await vi.waitFor(async () => expect(await Promise.all(sessions.map(async (sessionId) => (await app.inject(`/api/sessions/${sessionId}`)).json().state))).toEqual(['ready', 'ready']));
1987
2007
  const planText = `#+TITLE: Autopilot fixture
1988
2008
  * WIP [#A] Parent
@@ -2004,9 +2024,10 @@ describe('production composition', () => {
2004
2024
  - Done when :: The plan remains incomplete.
2005
2025
  `;
2006
2026
  await Promise.all(sessions.map(async (sessionId, index) => {
2007
- const planPath = join(workspacePath, `autopilot-${index}.org`);
2027
+ const selectedWorkspace = index === 0 ? workspacePath : otherWorkspace;
2028
+ const planPath = join(selectedWorkspace, `autopilot-${index}.org`);
2008
2029
  await writeFile(planPath, planText);
2009
- await writeFile(planStatusFilePath(planStatusDirectoryPath(workspacePath, sessionId), planPath), JSON.stringify({
2030
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(selectedWorkspace, sessionId), planPath), JSON.stringify({
2010
2031
  schemaVersion: 1,
2011
2032
  planPath,
2012
2033
  reason: 'supervision-start',
@@ -4303,8 +4324,10 @@ describe('production composition', () => {
4303
4324
  },
4304
4325
  });
4305
4326
  onTestFinished(() => fixture.app.close());
4306
- const peer = await createComposedSession(fixture.app);
4307
- await installAutopilotPlan(fixture.app, peer, fixture.workspacePath, 'peer-plan');
4327
+ const peerWorkspace = join(fixture.root, 'workspace-peer');
4328
+ await mkdir(peerWorkspace);
4329
+ const peer = await createComposedSession(fixture.app, 'workspace-peer');
4330
+ await installAutopilotPlan(fixture.app, peer, peerWorkspace, 'peer-plan');
4308
4331
  const starts = () => fixture.handles
4309
4332
  .flatMap((handle) => handle.requests)
4310
4333
  .filter((request) => request.method === 'turn/start');
@@ -5689,7 +5712,8 @@ describe('production composition', () => {
5689
5712
  });
5690
5713
  expect(transitions).toBeDefined();
5691
5714
  const sessionA = await createComposedSession(app);
5692
- const sessionB = await createComposedSession(app);
5715
+ await mkdir(join(root, 'workspace-peer'));
5716
+ const sessionB = await createComposedSession(app, 'workspace-peer');
5693
5717
  const handleA = await vi.waitFor(() => {
5694
5718
  const handle = handles.find((candidate) => candidate.calls.includes('thread/start'));
5695
5719
  expect(handle?.request).toBeDefined();
@@ -5918,7 +5942,8 @@ describe('production composition', () => {
5918
5942
  launchAppServer: liveAppServer(handles),
5919
5943
  });
5920
5944
  const supportedSession = await createComposedSession(first);
5921
- const legacySession = await createComposedSession(first);
5945
+ await mkdir(join(root, 'workspace-legacy'));
5946
+ const legacySession = await createComposedSession(first, 'workspace-legacy');
5922
5947
  await vi.waitFor(() => expect(handles.filter((handle) => handle.calls.includes('thread/start'))).toHaveLength(2));
5923
5948
  const started = handles.filter((handle) => handle.calls.includes('thread/start'));
5924
5949
  const supportedRequest = started[0].request(attentionCall(901));
@@ -6820,6 +6845,169 @@ describe('production composition', () => {
6820
6845
  runtimeStart.mockRestore();
6821
6846
  }
6822
6847
  });
6848
+ it.each(['TODO', 'WIP'])('keeps a validated %s plan passive in the visualizer until Execute is confirmed', async (state) => {
6849
+ const f = await orgPlanActivationFixture();
6850
+ let app = await f.open();
6851
+ try {
6852
+ const authorId = await createComposedSession(app);
6853
+ const planPath = join(f.workspacePath, '.gestalt', 'activation.org');
6854
+ await writeFile(planPath, state === 'TODO' ? autopilotPlanText().replace('* WIP', '* TODO') : autopilotPlanText());
6855
+ for (let opened = 0; opened < 2; opened++) {
6856
+ const view = await app.inject({
6857
+ method: 'PUT',
6858
+ url: `/api/sessions/${authorId}/plan`,
6859
+ payload: { planName: '.gestalt/activation.org' },
6860
+ });
6861
+ expect(view.statusCode, view.body).toBe(200);
6862
+ expect((await app.inject(`/api/sessions/${authorId}`)).json()).toMatchObject({
6863
+ lastOrgPlan: { attached: true, supervision: false },
6864
+ autopilot: { enabled: false },
6865
+ });
6866
+ await f.prepare(app);
6867
+ expect(f.requests('turn/start')).toHaveLength(0);
6868
+ expect(f.database((db) => db.prepare('SELECT count(*) AS n FROM org_plan_launches').get())).toEqual({ n: 0 });
6869
+ }
6870
+ // A deliberate Execute must report the occupied workspace and release
6871
+ // its unpublished claim, rather than poisoning all subsequent retries.
6872
+ const busyInput = await f.prepare(app);
6873
+ const busy = await app.inject({
6874
+ method: 'POST',
6875
+ url: '/api/plans/execute',
6876
+ payload: busyInput,
6877
+ });
6878
+ expect(busy.statusCode, busy.body).toBe(409);
6879
+ expect(busy.json()).toMatchObject({
6880
+ kind: 'blocked',
6881
+ code: 'WORKSPACE_BUSY',
6882
+ existingSessionId: authorId,
6883
+ });
6884
+ expect(f.requests('turn/start')).toHaveLength(0);
6885
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(1);
6886
+ await app.close();
6887
+ await rm(planStatusDirectoryPath(f.workspacePath, authorId), {
6888
+ recursive: true,
6889
+ force: true,
6890
+ });
6891
+ app = await f.open();
6892
+ await app.listen({ host: '127.0.0.1', port: 0 });
6893
+ expect((await app.inject(`/api/sessions/${authorId}`)).json()).toMatchObject({
6894
+ lastOrgPlan: { attached: true, supervision: false },
6895
+ autopilot: { enabled: false },
6896
+ });
6897
+ expect(f.requests('turn/start')).toHaveLength(0);
6898
+ const input = await f.prepare(app);
6899
+ const execute = await app.inject({
6900
+ method: 'POST',
6901
+ url: '/api/plans/execute',
6902
+ payload: input,
6903
+ });
6904
+ expect(execute.json()).toMatchObject({
6905
+ kind: 'started',
6906
+ bootstrap: { kind: 'accepted' },
6907
+ });
6908
+ expect(f.requests('turn/start')).toHaveLength(1);
6909
+ const supervisorId = execute.json().session.id;
6910
+ expect(supervisorId).not.toBe(authorId);
6911
+ expect((await app.inject(`/api/sessions/${authorId}`)).json().autopilot.enabled).toBe(false);
6912
+ }
6913
+ finally {
6914
+ await app.close();
6915
+ }
6916
+ });
6917
+ it.each(['authoring-start', 'resync'])('executes a draft retained through %s in one new supervisor, including after restart', async (reason) => {
6918
+ const f = await orgPlanActivationFixture();
6919
+ let app = await f.open();
6920
+ try {
6921
+ const authorId = await createComposedSession(app);
6922
+ const planPath = join(f.workspacePath, '.gestalt', 'activation.org');
6923
+ await writeFile(planPath, autopilotPlanText().replace('* WIP', '* TODO'));
6924
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(f.workspacePath, authorId), planPath), JSON.stringify({
6925
+ schemaVersion: 1,
6926
+ planPath,
6927
+ reason,
6928
+ updatedAt: new Date().toISOString(),
6929
+ }));
6930
+ await expect
6931
+ .poll(async () => (await app.inject(`/api/sessions/${authorId}`)).json().lastOrgPlan)
6932
+ .toMatchObject({ attached: true, path: planPath });
6933
+ await f.prepare(app);
6934
+ // Existing installations retained authoring attachments without an execution role.
6935
+ f.database((db) => db
6936
+ .prepare("UPDATE relay_sessions SET last_org_plan_json=json_remove(last_org_plan_json,'$.supervision') WHERE id=?")
6937
+ .run(authorId));
6938
+ await app.close();
6939
+ app = await f.open();
6940
+ await app.listen({ host: '127.0.0.1', port: 0 });
6941
+ const payload = await f.prepare(app);
6942
+ expect((await app.inject(`/api/sessions/${authorId}`)).json()).toMatchObject({
6943
+ lastOrgPlan: { attached: true, supervision: false },
6944
+ autopilot: { enabled: false },
6945
+ });
6946
+ const results = await Promise.all(['first', 'second'].map(async (launchId) => (await app.inject({
6947
+ method: 'POST',
6948
+ url: '/api/plans/execute',
6949
+ payload: { ...payload, launchId },
6950
+ })).json()));
6951
+ const started = results.find((result) => result.kind === 'started');
6952
+ expect(started).toBeDefined();
6953
+ expect(started.session.id).not.toBe(authorId);
6954
+ expect(results.find((result) => result.kind === 'blocked')).toMatchObject({
6955
+ code: 'ACTIVE_SUPERVISION',
6956
+ });
6957
+ expect((await app.inject('/api/sessions')).json()).toHaveLength(2);
6958
+ expect(f.requests('turn/start')).toHaveLength(1);
6959
+ // The author cannot acquire a second writer by publishing a late execution signal.
6960
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(f.workspacePath, authorId), planPath), JSON.stringify({
6961
+ schemaVersion: 1,
6962
+ planPath,
6963
+ reason: 'supervision-start',
6964
+ updatedAt: new Date().toISOString(),
6965
+ }));
6966
+ await expect
6967
+ .poll(() => f.database((db) => db
6968
+ .prepare("SELECT json_extract(payload_json,'$.reason') AS reason FROM session_events WHERE session_id=? AND type='plan.updated' ORDER BY sequence DESC LIMIT 1")
6969
+ .get(authorId)))
6970
+ .toEqual({ reason: 'supervision-start' });
6971
+ await expect
6972
+ .poll(async () => (await app.inject(`/api/sessions/${authorId}`)).json().lastOrgPlan)
6973
+ .toMatchObject({ attached: true, supervision: false });
6974
+ expect((await app.inject(`/api/sessions/${authorId}`)).json().autopilot.enabled).toBe(false);
6975
+ expect((await app.inject({
6976
+ method: 'PUT',
6977
+ url: `/api/sessions/${authorId}/autopilot`,
6978
+ payload: { enabled: true },
6979
+ })).statusCode).toBe(409);
6980
+ await writeFile(planStatusFilePath(planStatusDirectoryPath(f.workspacePath, started.session.id), planPath), JSON.stringify({
6981
+ schemaVersion: 1,
6982
+ planPath,
6983
+ reason: 'supervision-start',
6984
+ updatedAt: new Date().toISOString(),
6985
+ }));
6986
+ await expect
6987
+ .poll(async () => (await app.inject(`/api/sessions/${started.session.id}`)).json().lastOrgPlan)
6988
+ .toMatchObject({ attached: true, supervision: true });
6989
+ await app.inject({
6990
+ method: 'PUT',
6991
+ url: `/api/sessions/${started.session.id}/autopilot`,
6992
+ payload: { enabled: false },
6993
+ });
6994
+ await app.close();
6995
+ app = await f.open();
6996
+ await app.listen({ host: '127.0.0.1', port: 0 });
6997
+ expect((await app.inject(`/api/sessions/${started.session.id}`)).json().lastOrgPlan).toMatchObject({ attached: true, supervision: true });
6998
+ expect((await app.inject({
6999
+ method: 'POST',
7000
+ url: '/api/plans/prepare',
7001
+ payload: payload.reference,
7002
+ })).json()).toMatchObject({
7003
+ code: 'ACTIVE_SUPERVISION',
7004
+ existingSessionId: started.session.id,
7005
+ });
7006
+ }
7007
+ finally {
7008
+ await app.close();
7009
+ }
7010
+ });
6823
7011
  it('retains an authored plan without starting supervision', async () => {
6824
7012
  const root = await mkdtemp(join(tmpdir(), 'gestalt-mobile-root-'));
6825
7013
  const dataDir = await mkdtemp(join(tmpdir(), 'gestalt-mobile-state-'));
@@ -6846,6 +7034,7 @@ describe('production composition', () => {
6846
7034
  const sessionId = await createComposedSession(app);
6847
7035
  await installAutopilotPlan(app, sessionId, workspacePath, 'authored-only', 'TODO', 'authoring-start');
6848
7036
  expect((await app.inject(`/api/sessions/${sessionId}`)).json()).toMatchObject({
7037
+ lastOrgPlan: { attached: true, supervision: false },
6849
7038
  autopilot: { enabled: false, state: 'disabled' },
6850
7039
  });
6851
7040
  expect(handles.flatMap((handle) => handle.requests.filter((request) => request.method === 'turn/start'))).toHaveLength(0);
@@ -57,6 +57,8 @@ import { SqliteAuthorizationStore } from './platform/auth/sqlite-authorization-s
57
57
  import { SimpleWebAuthnAdapter } from './platform/auth/simple-webauthn-adapter.js';
58
58
  import { authorizationSessionId, authorizedDeviceId } from './features/auth/domain/identifiers.js';
59
59
  import { SqliteSessionRepository } from './platform/persistence/sqlite-session-repository.js';
60
+ import { SqliteWorkspaceLifecycle } from './platform/persistence/sqlite-workspace-lifecycle.js';
61
+ import { FilesystemWorkspaceForget } from './platform/scratch/filesystem-workspace-forget.js';
60
62
  import { SqliteEventJournal } from './platform/persistence/sqlite-event-journal.js';
61
63
  import { SqlitePendingInteractionStore } from './platform/persistence/sqlite-pending-interaction-store.js';
62
64
  import { SqliteIdempotencyStore } from './platform/persistence/sqlite-idempotency-store.js';
@@ -99,6 +101,7 @@ import { ManagedPlaywright } from './platform/codex/managed-playwright.js';
99
101
  import { isManagedPlaywrightCall } from '../shared/contracts/managed-playwright.js';
100
102
  import { compileSkillOverride } from './features/skills/model/skill-profile.js';
101
103
  import { SupervisedPlanRegistry } from './features/plans/application/supervised-plan-registry.js';
104
+ import { planAttachmentSupervision } from './features/plans/application/plan-attachment-supervision.js';
102
105
  import { prepareOrgPlanSupervision } from './features/plans/application/prepare-org-plan-supervision.js';
103
106
  import { startOrgPlanSupervision, OrgPlanSessionNotPublished, } from './features/plans/application/start-org-plan-supervision.js';
104
107
  import { SqliteOrgPlanLaunchStore } from './platform/persistence/sqlite-org-plan-launch-store.js';
@@ -154,7 +157,7 @@ export async function composeRelayApp(options) {
154
157
  database.close();
155
158
  throw error;
156
159
  }
157
- const sessions = new SqliteSessionRepository(database);
160
+ const sessions = new SqliteSessionRepository(database, new SqliteWorkspaceLifecycle(database));
158
161
  const forgetOperations = new SqliteForgetOperationStore(database);
159
162
  // Only sessions found while opening the relay database belong to a previous
160
163
  // process. A listen hook can run after a new session has already started in
@@ -188,6 +191,10 @@ export async function composeRelayApp(options) {
188
191
  const supervisorOwnership = (sessionId) => {
189
192
  const identity = supervisedPlans.identity(sessionId) ?? autopilotStore.find(sessionId)?.planIdentity;
190
193
  const owner = identity ? takeoverStore.owner(identity) : null;
194
+ const path = sessions.find(sessionId)?.lastOrgPlan?.path;
195
+ const launchOwner = path ? orgPlanLaunches.owner(path) : null;
196
+ if (!owner && launchOwner && launchOwner.sessionId !== sessionId)
197
+ return 'transferring';
191
198
  return !owner
192
199
  ? 'owned'
193
200
  : owner.sessionId !== sessionId
@@ -521,7 +528,13 @@ export async function composeRelayApp(options) {
521
528
  const debugHome = options.homeDirectory ?? homedir();
522
529
  const debugWorkspace = new SelfDebugWorkspace(join(debugHome, '.gestalt', 'self-debug'), join(process.env.CODEX_HOME ?? join(debugHome, '.codex'), 'agents', 'org-plan-executor.toml'), databasePath);
523
530
  const homeDirectory = options.homeDirectory ?? homedir();
524
- const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id));
531
+ const sessionScratch = new FilesystemSessionScratch((id) => forgetOperations.assertAvailable(id), ({ id }) => {
532
+ forgetOperations.assertAvailable(id);
533
+ const current = sessions.find(id);
534
+ if (!current)
535
+ throw new Error('SESSION_NOT_FOUND');
536
+ sessions.save(RelaySession.rehydrate(current).beginRecovery(new Date().toISOString()).snapshot, true);
537
+ });
525
538
  // Constructing the manager is cheap (no spawn until `ensure`); building it
526
539
  // before the model catalog lets the catalog reuse the gestalt-owned servers.
527
540
  const kimiManager = options.kimiServerManager ??
@@ -946,6 +959,9 @@ export async function composeRelayApp(options) {
946
959
  const occurredAt = new Date().toISOString();
947
960
  const session = sessions.find(sessionId);
948
961
  if (session) {
962
+ const execution = autopilotStore.find(sessionId);
963
+ const launchOwner = orgPlanLaunches.owner(update.planPath);
964
+ const takeoverOwner = takeoverStore.owner(update.identity);
949
965
  const updated = {
950
966
  ...session,
951
967
  lastOrgPlan: {
@@ -953,6 +969,10 @@ export async function composeRelayApp(options) {
953
969
  title: update.plan.title,
954
970
  path: update.planPath,
955
971
  attached: true,
972
+ supervision: (takeoverOwner
973
+ ? takeoverOwner.sessionId === sessionId
974
+ : !launchOwner || launchOwner.sessionId === sessionId) &&
975
+ planAttachmentSupervision(session.lastOrgPlan, update, execution?.planIdentity === update.identity && !!execution.supervision),
956
976
  },
957
977
  updatedAt: occurredAt,
958
978
  };
@@ -1547,6 +1567,7 @@ export async function composeRelayApp(options) {
1547
1567
  /** Routes a session to the runtime owning its provider's llm service. */
1548
1568
  const ownerRuntime = (session) => session.provider === 'kimi' ? kimiRuntime : runtime;
1549
1569
  const scratchCleanup = new FilesystemScratchCleanup();
1570
+ const workspaceForget = new FilesystemWorkspaceForget(database);
1550
1571
  const cleanTmp = new CleanSessionScratch({
1551
1572
  sessions: () => sessions.list(),
1552
1573
  knownWorkspacePaths: async () => [root, ...sessions.knownWorkspacePaths()],
@@ -1568,7 +1589,7 @@ export async function composeRelayApp(options) {
1568
1589
  await ownerRuntime(session)?.releaseForForget(session);
1569
1590
  await playwright.waitForRelease(session.id);
1570
1591
  },
1571
- clean: (session, operationId) => scratchCleanup.cleanSession(session, () => {
1592
+ clean: (session, operationId) => workspaceForget.clean(session, operationId, () => {
1572
1593
  const operation = forgetOperations.find(session.id);
1573
1594
  return operation?.operationId === operationId && operation.phase === 'cleaning';
1574
1595
  }, () => sessions.list()),
@@ -1770,12 +1791,13 @@ export async function composeRelayApp(options) {
1770
1791
  }
1771
1792
  : undefined,
1772
1793
  releaseWriter: runtime || kimiRuntime
1773
- ? (id) => {
1794
+ ? async (id) => {
1774
1795
  providerRecovery.cancel(id);
1775
1796
  dismissPendingInteractions(id, new Date().toISOString());
1776
1797
  const session = sessions.find(id);
1777
1798
  const owner = session ? ownerRuntime(session) : null;
1778
- return owner ? owner.release(id) : Promise.resolve();
1799
+ if (owner && session)
1800
+ await owner.releaseForForget(session);
1779
1801
  }
1780
1802
  : undefined,
1781
1803
  onStarted: (session) => {
@@ -1857,9 +1879,14 @@ export async function composeRelayApp(options) {
1857
1879
  ['reserved', 'creating'].includes(pending.phase);
1858
1880
  if (pending && !reclaimableLaunchOwner(pending) && !ownUnpublished)
1859
1881
  return sessions.find(pending.sessionId) ? { sessionId: pending.sessionId } : {};
1860
- const owner = sessions
1861
- .list()
1862
- .find((session) => session.lastOrgPlan?.attached && session.lastOrgPlan.path === canonicalPath);
1882
+ const identity = createHash('sha256').update(canonicalPath).digest('hex');
1883
+ const owner = sessions.list().find((session) => {
1884
+ if (!session.lastOrgPlan?.attached || session.lastOrgPlan.path !== canonicalPath)
1885
+ return false;
1886
+ const execution = autopilotStore.find(session.id);
1887
+ return (session.lastOrgPlan.supervision !== false ||
1888
+ (execution?.planIdentity === identity && !!execution.supervision));
1889
+ });
1863
1890
  return owner ? { sessionId: owner.id } : null;
1864
1891
  },
1865
1892
  }, expectedRevision, skillProfile);
@@ -2276,7 +2303,9 @@ export async function composeRelayApp(options) {
2276
2303
  activity.dispose(id);
2277
2304
  const session = sessions.find(id);
2278
2305
  const owner = session ? ownerRuntime(session) : null;
2279
- return owner ? owner.release(id) : Promise.resolve();
2306
+ if (session && owner)
2307
+ await owner.releaseForForget(session);
2308
+ await playwright.waitForRelease(id);
2280
2309
  }
2281
2310
  : undefined,
2282
2311
  replyInteraction: runtime || kimiRuntime
@@ -2339,7 +2368,7 @@ export async function composeRelayApp(options) {
2339
2368
  const result = await workspacePlanCatalog.read(session.workspacePath, planName);
2340
2369
  if (result.kind === 'available') {
2341
2370
  const planPath = resolve(session.workspacePath, ...planName.split('/'));
2342
- await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update));
2371
+ await planStatusSource.attach(session, planPath, (update) => acceptPlanUpdate(id, update), 'display-open');
2343
2372
  }
2344
2373
  return result;
2345
2374
  },
@@ -0,0 +1,27 @@
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
+ /** Displaying a draft is not an execution claim. Keep established claims across updates. */
7
+ export function planAttachmentSupervision(previous, update, retainedSupervision) {
8
+ const sameAttachment = previous?.attached && previous.path === update.planPath;
9
+ const progressed = (steps) => steps.some((step) => step.state !== 'TODO' ||
10
+ step.reviewStatus === 'REVIEWED' ||
11
+ !!step.measurement?.startedAt ||
12
+ progressed(step.children));
13
+ if (!!(sameAttachment && previous.supervision === true) ||
14
+ retainedSupervision ||
15
+ update.reason === 'supervision-start' ||
16
+ update.reason === 'work-start' ||
17
+ update.reason === 'checkpoint' ||
18
+ !!update.reason?.match(/^(?:l2:|review:|measure:)/))
19
+ return true;
20
+ if (update.reason === 'display-open' ||
21
+ update.reason === 'authoring-start' ||
22
+ (sameAttachment && previous.supervision === false))
23
+ return false;
24
+ return (progressed(update.plan.steps) ||
25
+ // Unknown legacy publications cannot prove that a previous supervisor was only authoring.
26
+ !!(sameAttachment && previous.supervision === undefined && update.reason === null));
27
+ }
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { createHash } from 'node:crypto';
7
+ import { WorkspaceSessionConflict } from '../../sessions/application/workspace-conflict.js';
7
8
  import { orgPlanLaunchRequestSchema, } from '../../../../shared/contracts/org-plan-execution.js';
8
9
  import { fingerprintTurnInput, } from '../../sessions/start-turn/use-case.js';
9
10
  /** One public application boundary, including durable ownership and retry rules. */
@@ -149,6 +150,15 @@ async function continueLaunch(record, deps) {
149
150
  }
150
151
  catch (error) {
151
152
  session = deps.sessions.find(record.sessionId);
153
+ if (!session && error instanceof WorkspaceSessionConflict) {
154
+ deps.launches.revokePublication(record, deps.sessions);
155
+ return {
156
+ kind: 'blocked',
157
+ code: 'WORKSPACE_BUSY',
158
+ reason: error.message,
159
+ existingSessionId: error.sessionId,
160
+ };
161
+ }
152
162
  if (session)
153
163
  deps.launches.save({ ...record, phase: 'session' }, 'creating');
154
164
  else if (error instanceof OrgPlanSessionNotPublished) {
@@ -19,7 +19,7 @@ export function registerExecuteOrgPlan(app, deps) {
19
19
  ? 409
20
20
  : 400
21
21
  : result.kind === 'blocked' &&
22
- ['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION'].includes(result.code)
22
+ ['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION', 'WORKSPACE_BUSY'].includes(result.code)
23
23
  ? 409
24
24
  : 200;
25
25
  return reply.code(status).send(result);
@@ -0,0 +1,19 @@
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 class WorkspaceSessionConflict extends Error {
7
+ code;
8
+ sessionId;
9
+ statusCode = 409;
10
+ constructor(code, sessionId) {
11
+ super(code === 'SESSION_WORKSPACE_BUSY'
12
+ ? 'A session is already running in this workspace. Open that session or stop it first.'
13
+ : code === 'SESSION_NESTED_WORKSPACE'
14
+ ? 'Forget the session whose workspace is inside this temporary directory first.'
15
+ : 'This workspace is being forgotten. Retry when cleanup finishes.');
16
+ this.code = code;
17
+ this.sessionId = sessionId;
18
+ }
19
+ }
@@ -10,6 +10,13 @@ export function registerForgetSession(app, deps) {
10
10
  const operation = await deps.forget(id);
11
11
  if (!operation)
12
12
  return reply.code(404).send({ code: 'SESSION_NOT_FOUND' });
13
+ if (operation.phase === 'failed' && operation.blockingSessionId)
14
+ return reply.code(409).send({
15
+ code: 'SESSION_NESTED_WORKSPACE',
16
+ sessionId: operation.blockingSessionId,
17
+ detail: 'Forget the contained workspace session first, then retry.',
18
+ operation,
19
+ });
13
20
  if (operation.phase !== 'completed')
14
21
  return reply.code(503).send({ code: 'SESSION_FORGET_FAILED', operation });
15
22
  return reply.code(204).send();
@@ -3,6 +3,7 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
6
7
  export class ForgetSession {
7
8
  deps;
8
9
  pending = new Map();
@@ -37,6 +38,7 @@ export class ForgetSession {
37
38
  sessionId: id,
38
39
  phase,
39
40
  updatedAt: this.deps.now(),
41
+ ...(operation.scratchRetained ? { scratchRetained: true } : {}),
40
42
  });
41
43
  this.deps.changed(operation);
42
44
  return operation;
@@ -53,7 +55,8 @@ export class ForgetSession {
53
55
  failureCode = 'SESSION_CLEANUP_FAILED';
54
56
  if (advance('cleaning').phase === 'completed')
55
57
  return operation;
56
- await this.deps.clean(session, operation.operationId);
58
+ const cleanup = await this.deps.clean(session, operation.operationId);
59
+ operation = { ...operation, scratchRetained: cleanup === 'retained' ? true : undefined };
57
60
  failureCode = 'SESSION_FORGET_FAILED';
58
61
  if (advance('finalizing').phase === 'completed')
59
62
  return operation;
@@ -61,12 +64,15 @@ export class ForgetSession {
61
64
  this.deps.changed(operation);
62
65
  return operation;
63
66
  }
64
- catch {
67
+ catch (error) {
65
68
  operation = this.deps.operations.update({
66
69
  ...operation,
67
70
  phase: 'failed',
68
71
  failureCode,
69
72
  updatedAt: this.deps.now(),
73
+ ...(error instanceof WorkspaceSessionConflict
74
+ ? { blockingSessionId: error.sessionId }
75
+ : {}),
70
76
  });
71
77
  this.deps.changed(operation);
72
78
  return operation;
@@ -134,6 +134,7 @@ export function registerSessionRoutes(app, deps) {
134
134
  registerRestoreSession(app, {
135
135
  find: sessions.find,
136
136
  restore: sessions.restore,
137
+ close: sessions.close,
137
138
  save: sessions.save,
138
139
  ownsWriter: sessions.ownsWriter,
139
140
  idempotency: sessions.idempotency,
@@ -3,6 +3,7 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
6
7
  import { idempotencyKey } from '../../../platform/http/idempotency.js';
7
8
  import { RelaySession, relayOwnsWriter } from '../model/relay-session.js';
8
9
  import { canRestore } from './use-case.js';
@@ -32,12 +33,20 @@ export function registerRestoreSession(app, deps) {
32
33
  try {
33
34
  restored = await deps.restore(session);
34
35
  }
35
- catch {
36
+ catch (error) {
37
+ try {
38
+ await deps.close?.(id);
39
+ }
40
+ catch {
41
+ return reply.code(502).send({ code: 'RESTORE_FAILED' });
42
+ }
36
43
  // The pre-I/O recovery marker must never strand a saved session: keep
37
44
  // its original thread and inactive state available for a later Open.
38
45
  deps.save(staleWriter
39
46
  ? RelaySession.rehydrate(session).stop(new Date().toISOString()).snapshot
40
47
  : session);
48
+ if (error instanceof WorkspaceSessionConflict)
49
+ throw error;
41
50
  return reply.code(502).send({ code: 'RESTORE_FAILED' });
42
51
  }
43
52
  const response = 'session' in restored
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { createHash } from 'node:crypto';
7
+ import { WorkspaceSessionConflict } from '../application/workspace-conflict.js';
7
8
  import { RelaySession } from '../model/relay-session.js';
8
9
  import { WriterAcquisitionError, writerAcquisitionProblem, } from '../application/writer-acquisition.js';
9
10
  /** Ordinary turn acceptance, shared by HTTP and application callers with one serialization boundary. */
@@ -203,7 +204,8 @@ async function cleanupAcquiredWriter(deps, acquired, original) {
203
204
  await deps.releaseWriter?.(acquired.id);
204
205
  }
205
206
  catch {
206
- // Process loss is already a valid release outcome.
207
+ // Keep the workspace reservation when shutdown could not be confirmed.
208
+ return;
207
209
  }
208
210
  try {
209
211
  deps.save(original);
@@ -222,6 +224,16 @@ async function ensureWriter(deps, session) {
222
224
  return await deps.ensureWriter(session);
223
225
  }
224
226
  catch (error) {
227
+ if (error instanceof WorkspaceSessionConflict)
228
+ return {
229
+ statusCode: 409,
230
+ body: JSON.stringify({
231
+ code: error.code,
232
+ detail: error.message,
233
+ sessionId: error.sessionId,
234
+ retryable: true,
235
+ }),
236
+ };
225
237
  if (error instanceof WriterAcquisitionError &&
226
238
  error.kind === 'writerBusy' &&
227
239
  session.state !== 'stopped')