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
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { ORG_PLAN_CAPABILITIES } from '../plans/org-plan-capabilities.js';
7
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
7
8
  import { readExecutorConfiguration } from './executor-configuration.js';
8
9
  import { decodeCodexPolicyCatalog } from './codex-model-catalog.js';
9
10
  import { RelaySession, } from '../../features/sessions/model/relay-session.js';
@@ -170,6 +171,7 @@ export class CodexSessionRuntime {
170
171
  childTopologyReads = new Map();
171
172
  writerAcquisitions = new Map();
172
173
  liveResources = new Map();
174
+ confirmedWorkspaceReleases = new Set();
173
175
  resourceCreations = new Map();
174
176
  resourceReleases = new Map();
175
177
  /** Current runtime observations only; durable workspace selection is never rewritten. */
@@ -238,7 +240,9 @@ export class CodexSessionRuntime {
238
240
  }
239
241
  /** Forget requires actual release, including resources still starting or already closing. */
240
242
  async releaseForForget(session) {
243
+ let observedResource = false;
241
244
  for (const resource of this.liveResources.get(session.id) ?? []) {
245
+ observedResource = true;
242
246
  resource.beginExplicitShutdown();
243
247
  if (resource.active) {
244
248
  if (session.activeTurnId)
@@ -282,11 +286,14 @@ export class CodexSessionRuntime {
282
286
  ...[this.writerAcquisitions.get(session.id)].filter((item) => item !== undefined),
283
287
  ]);
284
288
  for (const resource of this.liveResources.get(session.id) ?? []) {
289
+ observedResource = true;
285
290
  resource.beginExplicitShutdown();
286
291
  resource.dispose();
287
292
  await this.confirmResourceRelease(resource, true);
288
293
  }
289
294
  this.retrieval?.release?.(session.id);
295
+ if (observedResource && !this.liveResources.get(session.id)?.size)
296
+ this.confirmedWorkspaceReleases.add(session.id);
290
297
  }
291
298
  confirmResourceRelease(resource, strict = false) {
292
299
  const prior = this.resourceReleases.get(resource);
@@ -563,6 +570,8 @@ export class CodexSessionRuntime {
563
570
  return { session: restored.session, replacementCreated: restored.replacementCreated };
564
571
  }
565
572
  catch (error) {
573
+ if (error instanceof WorkspaceSessionConflict)
574
+ throw error;
566
575
  throw classifyWriterAcquisitionFailure(error);
567
576
  }
568
577
  }
@@ -587,6 +596,13 @@ export class CodexSessionRuntime {
587
596
  }
588
597
  /** Stops the previous root's actor tree without transferring its native collaboration namespace. */
589
598
  async quiesceForTakeover(session, recordedProcesses = [], executor) {
599
+ // A user-confirmed Close already quiesced this root. Reopening it solely
600
+ // for takeover would conflict with the incoming workspace's running slot.
601
+ if (session.desiredState === 'stopped' &&
602
+ this.confirmedWorkspaceReleases.has(session.id) &&
603
+ !this.liveResources.get(session.id)?.size &&
604
+ !recordedProcesses.some((claim) => ['running', 'detached-active'].includes(claim.state)))
605
+ return true;
590
606
  let expired = false;
591
607
  let timer;
592
608
  try {
@@ -1448,6 +1464,8 @@ export class CodexSessionRuntime {
1448
1464
  return task;
1449
1465
  }
1450
1466
  async createResourceInner(session) {
1467
+ this.scratch?.reserveRuntime?.(session);
1468
+ this.confirmedWorkspaceReleases.delete(session.id);
1451
1469
  const deadline = xerjDeadline();
1452
1470
  const lease = this.planStatusSource
1453
1471
  ? await this.planStatusSource.open({ id: session.id, workspacePath: session.workspacePath }, (update) => this.onPlanStatus?.(session.id, update))
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { problem as createProblem } from './problem.js';
7
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
7
8
  export function registerProblemHandler(app, serveSpa = false) {
8
9
  app.setNotFoundHandler((request, reply) => {
9
10
  if (serveSpa && request.method === 'GET' && !request.url.startsWith('/api/')) {
@@ -20,6 +21,14 @@ export function registerProblemHandler(app, serveSpa = false) {
20
21
  return reply.code(404).type('application/problem+json').send(problem);
21
22
  });
22
23
  app.setErrorHandler((error, _request, reply) => {
24
+ if (error instanceof WorkspaceSessionConflict)
25
+ return reply
26
+ .code(409)
27
+ .type('application/problem+json')
28
+ .send({
29
+ ...createProblem(error.code, 409, error.message, true),
30
+ sessionId: error.sessionId,
31
+ });
23
32
  if (typeof error === 'object' &&
24
33
  error !== null &&
25
34
  'code' in error &&
@@ -4,6 +4,7 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { createHash, randomUUID } from 'node:crypto';
7
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
7
8
  import { setTimeout as delay } from 'node:timers/promises';
8
9
  import { RelaySession, } from '../../features/sessions/model/relay-session.js';
9
10
  import { normalizeSkillProfileName, } from '../../features/skills/model/skill-profile.js';
@@ -45,6 +46,7 @@ export class KimiSessionRuntime {
45
46
  };
46
47
  }
47
48
  async start(session, now) {
49
+ this.input.scratch?.reserveRuntime?.(session);
48
50
  const handle = await this.ensureServer(session);
49
51
  const created = (await handle.client.post('/api/v1/sessions', {
50
52
  metadata: { cwd: session.workspacePath },
@@ -260,6 +262,8 @@ export class KimiSessionRuntime {
260
262
  return { session: restored.session, replacementCreated: restored.replacementCreated };
261
263
  }
262
264
  catch (error) {
265
+ if (error instanceof WorkspaceSessionConflict)
266
+ throw error;
263
267
  throw classifyWriterAcquisitionFailure(error);
264
268
  }
265
269
  }
@@ -327,6 +331,7 @@ export class KimiSessionRuntime {
327
331
  }
328
332
  /** Attaches to the durable kimi session recorded on the relay snapshot. */
329
333
  async attachExisting(session) {
334
+ this.input.scratch?.reserveRuntime?.(session);
330
335
  if (!session.threadId)
331
336
  throw new Error('KIMI_THREAD_ID_MISSING');
332
337
  const handle = await this.ensureServer(session);
@@ -53,6 +53,23 @@ export function migrate(database) {
53
53
  CREATE TRIGGER IF NOT EXISTS forget_fence_update BEFORE UPDATE ON relay_sessions
54
54
  WHEN EXISTS (SELECT 1 FROM session_forget_operations WHERE session_id = NEW.id)
55
55
  BEGIN SELECT RAISE(IGNORE); END;`);
56
+ const forgetColumns = database
57
+ .prepare('PRAGMA table_info(session_forget_operations)')
58
+ .all();
59
+ if (!forgetColumns.some((column) => column.name === 'scratch_retained'))
60
+ database.exec('ALTER TABLE session_forget_operations ADD COLUMN scratch_retained INTEGER NOT NULL DEFAULT 0');
61
+ database.exec(`CREATE TABLE IF NOT EXISTS workspace_forget_locks (
62
+ workspace_path TEXT PRIMARY KEY,
63
+ session_id TEXT NOT NULL,
64
+ operation_id TEXT NOT NULL UNIQUE
65
+ );`);
66
+ if (!forgetColumns.some((column) => column.name === 'blocking_session_id'))
67
+ database.exec('ALTER TABLE session_forget_operations ADD COLUMN blocking_session_id TEXT');
68
+ const workspaceLockColumns = database
69
+ .prepare('PRAGMA table_info(workspace_forget_locks)')
70
+ .all();
71
+ if (!workspaceLockColumns.some((column) => column.name === 'retired_path'))
72
+ database.exec('ALTER TABLE workspace_forget_locks ADD COLUMN retired_path TEXT');
56
73
  database.exec(`CREATE TABLE IF NOT EXISTS scratch_known_workspaces (
57
74
  workspace_path TEXT PRIMARY KEY
58
75
  ); INSERT OR IGNORE INTO scratch_known_workspaces (workspace_path)
@@ -64,8 +64,12 @@ export class SqliteEventJournal {
64
64
  this.db.exec('BEGIN IMMEDIATE');
65
65
  try {
66
66
  const row = this.db
67
- .prepare('SELECT next_sequence AS sequence FROM relay_sessions WHERE id = ?')
68
- .get(sessionId);
67
+ // Forget fences roster writes, including the sequence counter. Allocate
68
+ // above the durable journal tail as well, including already-stuck rows.
69
+ .prepare(`SELECT MAX(next_sequence, COALESCE(
70
+ (SELECT MAX(sequence) + 1 FROM session_events WHERE session_id = ?), 1
71
+ )) AS sequence FROM relay_sessions WHERE id = ?`)
72
+ .get(sessionId, sessionId);
69
73
  if (!row)
70
74
  throw new Error('SESSION_NOT_FOUND');
71
75
  const inserted = this.db
@@ -4,6 +4,8 @@
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
6
  import { randomUUID } from 'node:crypto';
7
+ import { canonicalSessionWorkspace } from './sqlite-workspace-lifecycle.js';
8
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
7
9
  export class SqliteForgetOperationStore {
8
10
  db;
9
11
  constructor(db) {
@@ -20,6 +22,8 @@ export class SqliteForgetOperationStore {
20
22
  phase: row.phase,
21
23
  updatedAt: row.updated_at,
22
24
  ...(row.failure_code ? { failureCode: row.failure_code } : {}),
25
+ ...(row.scratch_retained ? { scratchRetained: true } : {}),
26
+ ...(row.blocking_session_id ? { blockingSessionId: row.blocking_session_id } : {}),
23
27
  }
24
28
  : null;
25
29
  }
@@ -33,18 +37,43 @@ export class SqliteForgetOperationStore {
33
37
  .all().map((row) => row.session_id);
34
38
  }
35
39
  begin(id) {
36
- this.db
37
- .prepare(`INSERT INTO session_forget_operations (session_id, operation_id, phase, updated_at)
40
+ this.db.exec('SAVEPOINT begin_forget');
41
+ try {
42
+ this.db
43
+ .prepare(`INSERT INTO session_forget_operations (session_id, operation_id, phase, updated_at)
38
44
  SELECT id, ?, 'stopping', ? FROM relay_sessions WHERE id = ?
39
45
  ON CONFLICT(session_id) DO NOTHING`)
40
- .run(randomUUID(), new Date().toISOString(), id);
41
- return this.find(id);
46
+ .run(randomUUID(), new Date().toISOString(), id);
47
+ const operation = this.find(id);
48
+ if (operation && operation.phase !== 'completed') {
49
+ const session = this.db
50
+ .prepare('SELECT workspace_path FROM relay_sessions WHERE id=?')
51
+ .get(id);
52
+ if (!session)
53
+ throw new Error('SESSION_NOT_FOUND');
54
+ const path = canonicalSessionWorkspace(session.workspace_path);
55
+ this.db
56
+ .prepare('INSERT INTO workspace_forget_locks(workspace_path,session_id,operation_id) VALUES(?,?,?) ON CONFLICT(workspace_path) DO NOTHING')
57
+ .run(path, id, operation.operationId);
58
+ const lock = this.db
59
+ .prepare('SELECT session_id, operation_id FROM workspace_forget_locks WHERE workspace_path=?')
60
+ .get(path);
61
+ if (lock.operation_id !== operation.operationId)
62
+ throw new WorkspaceSessionConflict('SESSION_WORKSPACE_CLEANING', lock.session_id);
63
+ }
64
+ this.db.exec('RELEASE begin_forget');
65
+ return operation;
66
+ }
67
+ catch (error) {
68
+ this.db.exec('ROLLBACK TO begin_forget; RELEASE begin_forget');
69
+ throw error;
70
+ }
42
71
  }
43
72
  update(operation) {
44
73
  this.db
45
- .prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?
74
+ .prepare(`UPDATE session_forget_operations SET phase = ?, updated_at = ?, failure_code = ?, scratch_retained = ?, blocking_session_id = ?
46
75
  WHERE session_id = ? AND operation_id = ? AND phase != 'completed'`)
47
- .run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.sessionId, operation.operationId);
76
+ .run(operation.phase, operation.updatedAt, operation.failureCode ?? null, operation.scratchRetained ? 1 : 0, operation.blockingSessionId ?? null, operation.sessionId, operation.operationId);
48
77
  return this.find(operation.sessionId);
49
78
  }
50
79
  finalize(operation) {
@@ -56,6 +85,9 @@ export class SqliteForgetOperationStore {
56
85
  throw new Error('SESSION_FORGET_OPERATION_CHANGED');
57
86
  this.db.prepare('DELETE FROM relay_sessions WHERE id = ?').run(operation.sessionId);
58
87
  this.update({ ...operation, phase: 'completed' });
88
+ this.db
89
+ .prepare('DELETE FROM workspace_forget_locks WHERE operation_id=?')
90
+ .run(operation.operationId);
59
91
  this.db.exec('COMMIT');
60
92
  return this.find(operation.sessionId);
61
93
  }
@@ -3,18 +3,40 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
+ import { canonicalSessionWorkspace, } from './sqlite-workspace-lifecycle.js';
6
7
  import { createEffectiveSkillSelection, createSessionExecutionPolicy, } from '../../features/sessions/model/relay-session.js';
7
8
  export class SqliteSessionRepository {
8
9
  db;
9
- constructor(db) {
10
+ workspaceLifecycle;
11
+ constructor(db, workspaceLifecycle) {
10
12
  this.db = db;
13
+ this.workspaceLifecycle = workspaceLifecycle;
11
14
  }
12
- save(session) {
13
- this.db
14
- .prepare('INSERT INTO relay_sessions (id,workspace_id,workspace_path,provider,profile,model,branch,sandbox,approval_policy,thread_id,state,desired_state,active_turn_id,protocol_version,attention_tool_capability,failure_count,effective_skill_selection_json,last_org_plan_json,model_settings_json,self_debug_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET workspace_id=excluded.workspace_id,workspace_path=excluded.workspace_path,provider=excluded.provider,profile=excluded.profile,model=excluded.model,branch=excluded.branch,sandbox=excluded.sandbox,approval_policy=excluded.approval_policy,thread_id=excluded.thread_id,state=excluded.state,desired_state=excluded.desired_state,active_turn_id=excluded.active_turn_id,protocol_version=excluded.protocol_version,attention_tool_capability=excluded.attention_tool_capability,failure_count=excluded.failure_count,effective_skill_selection_json=excluded.effective_skill_selection_json,last_org_plan_json=excluded.last_org_plan_json,model_settings_json=excluded.model_settings_json,self_debug_json=excluded.self_debug_json,updated_at=excluded.updated_at')
15
- .run(session.id, session.workspaceId, session.workspacePath, session.provider, session.profile, session.model ?? null, session.branch ?? null, session.executionPolicy?.sandbox ?? null, session.executionPolicy?.approvalPolicy ?? null, session.threadId, session.state, session.desiredState, session.activeTurnId, session.protocolVersion, session.attentionToolCapability ?? null, session.failureCount, session.effectiveSkillSelection === undefined
16
- ? null
17
- : JSON.stringify(session.effectiveSkillSelection), session.lastOrgPlan === undefined ? null : JSON.stringify(session.lastOrgPlan), session.modelSettings === undefined ? null : JSON.stringify(session.modelSettings), session.selfDebug ? JSON.stringify(session.selfDebug) : null, session.createdAt, session.updatedAt);
15
+ save(session, requireAdmission = false) {
16
+ const nested = this.db.isTransaction;
17
+ this.db.exec(nested ? 'SAVEPOINT save_session' : 'BEGIN IMMEDIATE');
18
+ try {
19
+ // A Forget tombstone takes precedence over admission and late status writes.
20
+ if (this.db
21
+ .prepare('SELECT 1 FROM session_forget_operations WHERE session_id=?')
22
+ .get(session.id)) {
23
+ this.db.exec(nested ? 'RELEASE save_session' : 'COMMIT');
24
+ return;
25
+ }
26
+ this.workspaceLifecycle?.assertSave(session, requireAdmission);
27
+ this.db
28
+ .prepare('INSERT INTO relay_sessions (id,workspace_id,workspace_path,provider,profile,model,branch,sandbox,approval_policy,thread_id,state,desired_state,active_turn_id,protocol_version,attention_tool_capability,failure_count,effective_skill_selection_json,last_org_plan_json,model_settings_json,self_debug_json,created_at,updated_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(id) DO UPDATE SET workspace_id=excluded.workspace_id,workspace_path=excluded.workspace_path,provider=excluded.provider,profile=excluded.profile,model=excluded.model,branch=excluded.branch,sandbox=excluded.sandbox,approval_policy=excluded.approval_policy,thread_id=excluded.thread_id,state=excluded.state,desired_state=excluded.desired_state,active_turn_id=excluded.active_turn_id,protocol_version=excluded.protocol_version,attention_tool_capability=excluded.attention_tool_capability,failure_count=excluded.failure_count,effective_skill_selection_json=excluded.effective_skill_selection_json,last_org_plan_json=excluded.last_org_plan_json,model_settings_json=excluded.model_settings_json,self_debug_json=excluded.self_debug_json,updated_at=excluded.updated_at')
29
+ .run(session.id, session.workspaceId, this.workspaceLifecycle
30
+ ? canonicalSessionWorkspace(session.workspacePath)
31
+ : session.workspacePath, session.provider, session.profile, session.model ?? null, session.branch ?? null, session.executionPolicy?.sandbox ?? null, session.executionPolicy?.approvalPolicy ?? null, session.threadId, session.state, session.desiredState, session.activeTurnId, session.protocolVersion, session.attentionToolCapability ?? null, session.failureCount, session.effectiveSkillSelection === undefined
32
+ ? null
33
+ : JSON.stringify(session.effectiveSkillSelection), session.lastOrgPlan === undefined ? null : JSON.stringify(session.lastOrgPlan), session.modelSettings === undefined ? null : JSON.stringify(session.modelSettings), session.selfDebug ? JSON.stringify(session.selfDebug) : null, session.createdAt, session.updatedAt);
34
+ this.db.exec(nested ? 'RELEASE save_session' : 'COMMIT');
35
+ }
36
+ catch (error) {
37
+ this.db.exec(nested ? 'ROLLBACK TO save_session; RELEASE save_session' : 'ROLLBACK');
38
+ throw error;
39
+ }
18
40
  }
19
41
  find(id) {
20
42
  const row = this.db.prepare('SELECT * FROM relay_sessions WHERE id = ?').get(id);
@@ -0,0 +1,59 @@
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 { realpathSync } from 'node:fs';
7
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
8
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
9
+ export function canonicalSessionWorkspace(path) {
10
+ if (!isAbsolute(path))
11
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
12
+ try {
13
+ return realpathSync(path);
14
+ }
15
+ catch (error) {
16
+ if (error.code === 'ENOENT')
17
+ return resolve(path);
18
+ throw error;
19
+ }
20
+ }
21
+ export function workspaceContains(root, path) {
22
+ const suffix = relative(root, path);
23
+ return (suffix === '' || (!isAbsolute(suffix) && suffix !== '..' && !suffix.startsWith(`..${sep}`)));
24
+ }
25
+ /** Called inside the repository's write transaction, before publication or native startup. */
26
+ export class SqliteWorkspaceLifecycle {
27
+ db;
28
+ constructor(db) {
29
+ this.db = db;
30
+ }
31
+ assertSave(session, requireAdmission = false) {
32
+ const path = canonicalSessionWorkspace(session.workspacePath);
33
+ const prior = this.db
34
+ .prepare('SELECT workspace_path,state,desired_state FROM relay_sessions WHERE id=?')
35
+ .get(session.id);
36
+ const running = session.desiredState === 'active' && !['stopped', 'released'].includes(session.state);
37
+ const alreadyRunning = prior &&
38
+ canonicalSessionWorkspace(prior.workspace_path) === path &&
39
+ prior.desired_state === 'active' &&
40
+ !['stopped', 'released'].includes(prior.state);
41
+ if (!prior ||
42
+ canonicalSessionWorkspace(prior.workspace_path) !== path ||
43
+ (running && (!alreadyRunning || requireAdmission))) {
44
+ for (const lock of this.db.prepare('SELECT * FROM workspace_forget_locks').all()) {
45
+ if (path === lock.workspace_path ||
46
+ workspaceContains(join(lock.workspace_path, 'tmp'), path))
47
+ throw new WorkspaceSessionConflict('SESSION_WORKSPACE_CLEANING', lock.session_id);
48
+ }
49
+ }
50
+ if (!running || (alreadyRunning && !requireAdmission))
51
+ return;
52
+ for (const other of this.db
53
+ .prepare("SELECT id,workspace_path FROM relay_sessions WHERE id != ? AND desired_state='active' AND state NOT IN ('stopped','released')")
54
+ .all(session.id)) {
55
+ if (canonicalSessionWorkspace(other.workspace_path) === path)
56
+ throw new WorkspaceSessionConflict('SESSION_WORKSPACE_BUSY', other.id);
57
+ }
58
+ }
59
+ }
@@ -42,8 +42,8 @@ export class FilesystemPlanStatusSource {
42
42
  await lease.start();
43
43
  return lease;
44
44
  }
45
- /** Explicit attachments use the same durable publication and watchers as helper updates. */
46
- async attach(session, requestedPath, listener, reason = 'supervision-start') {
45
+ /** Viewing retains a durable display attachment; execution needs an explicit start signal. */
46
+ async attach(session, requestedPath, listener, reason = 'display-open') {
47
47
  const [planPath, workspacePath] = await Promise.all([
48
48
  this.planReadFilesystem.realpath(requestedPath),
49
49
  this.planReadFilesystem.realpath(session.workspacePath),
@@ -36,9 +36,11 @@ function validateMarker(value, expected) {
36
36
  }
37
37
  export class FilesystemSessionScratch {
38
38
  assertAvailable;
39
+ reserveRuntime;
39
40
  pending = new Map();
40
- constructor(assertAvailable = () => { }) {
41
+ constructor(assertAvailable = () => { }, reserveRuntime) {
41
42
  this.assertAvailable = assertAvailable;
43
+ this.reserveRuntime = reserveRuntime;
42
44
  }
43
45
  /** A live process claim remains protected across relay crashes and other servers. */
44
46
  async borrow(session) {
@@ -0,0 +1,123 @@
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 { lstatSync, mkdirSync, realpathSync, renameSync } from 'node:fs';
7
+ import { lstat, rm } from 'node:fs/promises';
8
+ import { join } from 'node:path';
9
+ import { WorkspaceSessionConflict } from '../../features/sessions/application/workspace-conflict.js';
10
+ import { canonicalSessionWorkspace, workspaceContains, } from '../persistence/sqlite-workspace-lifecycle.js';
11
+ /** Final Forget owns the entire selected workspace's explicitly disposable tmp directory. */
12
+ export class FilesystemWorkspaceForget {
13
+ db;
14
+ constructor(db) {
15
+ this.db = db;
16
+ }
17
+ async clean(session, operationId, authorized, knownSessions) {
18
+ const workspace = canonicalSessionWorkspace(session.workspacePath);
19
+ const others = knownSessions().filter((other) => other.id !== session.id);
20
+ if (others.some((other) => canonicalSessionWorkspace(other.workspacePath) === workspace))
21
+ return 'retained';
22
+ const temporary = join(workspace, 'tmp');
23
+ for (const other of others) {
24
+ if (workspaceContains(temporary, canonicalSessionWorkspace(other.workspacePath)))
25
+ throw new WorkspaceSessionConflict('SESSION_NESTED_WORKSPACE', other.id);
26
+ }
27
+ const retired = this.retire(session, operationId, workspace, temporary, authorized);
28
+ if (retired)
29
+ await rm(retired, { recursive: true, force: true, maxRetries: 3 });
30
+ // A non-cooperating external publisher must not turn retained files into a
31
+ // successful final Forget. New Mobile starts remain durably fenced.
32
+ try {
33
+ await lstat(temporary);
34
+ }
35
+ catch (error) {
36
+ if (error.code === 'ENOENT')
37
+ return;
38
+ throw error;
39
+ }
40
+ throw new Error('SESSION_CLEANUP_FAILED');
41
+ }
42
+ retire(session, operationId, workspace, temporary, authorized) {
43
+ // The short synchronous transaction atomically checks authority and moves
44
+ // tmp out of the allocation namespace. Duplicate/restarted requests can
45
+ // delete only this operation's retired path, never a later session's tmp.
46
+ this.db.exec('BEGIN IMMEDIATE');
47
+ try {
48
+ const lock = this.db
49
+ .prepare('SELECT retired_path FROM workspace_forget_locks WHERE workspace_path=? AND operation_id=?')
50
+ .get(workspace, operationId);
51
+ if (!lock || !authorized())
52
+ throw new Error('SESSION_FORGET_OPERATION_CHANGED');
53
+ if (lock.retired_path !== null) {
54
+ if (lock.retired_path !== '' &&
55
+ lock.retired_path !== join(workspace, '.gestalt', 'forgotten-tmp', operationId))
56
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
57
+ this.db.exec('COMMIT');
58
+ return lock.retired_path;
59
+ }
60
+ if (!/^[0-9a-f-]{36}$/.test(operationId))
61
+ throw new Error('SESSION_FORGET_OPERATION_CHANGED');
62
+ const directory = (path) => {
63
+ const info = lstatSync(path);
64
+ if (!info.isDirectory() ||
65
+ info.isSymbolicLink() ||
66
+ realpathSync(path) !== path ||
67
+ (process.getuid && info.uid !== process.getuid()))
68
+ throw new Error('SESSION_SCRATCH_UNSAFE_PATH');
69
+ };
70
+ let retired = '';
71
+ try {
72
+ directory(workspace);
73
+ directory(temporary);
74
+ const metadata = join(workspace, '.gestalt');
75
+ const staging = join(metadata, 'forgotten-tmp');
76
+ for (const path of [metadata, staging]) {
77
+ try {
78
+ mkdirSync(path, { mode: 0o700 });
79
+ }
80
+ catch (error) {
81
+ if (error.code !== 'EEXIST')
82
+ throw error;
83
+ }
84
+ directory(path);
85
+ }
86
+ retired = join(staging, operationId);
87
+ try {
88
+ lstatSync(retired);
89
+ throw new Error('SESSION_SCRATCH_BUSY');
90
+ }
91
+ catch (error) {
92
+ if (error.code !== 'ENOENT')
93
+ throw error;
94
+ }
95
+ renameSync(temporary, retired);
96
+ }
97
+ catch (error) {
98
+ if (error.code !== 'ENOENT')
99
+ throw error;
100
+ // A crash between rename and commit leaves the exact durable operation's
101
+ // private retirement directory. Recover it without touching a new tmp.
102
+ const candidate = join(workspace, '.gestalt', 'forgotten-tmp', operationId);
103
+ try {
104
+ directory(candidate);
105
+ retired = candidate;
106
+ }
107
+ catch (missing) {
108
+ if (missing.code !== 'ENOENT')
109
+ throw missing;
110
+ }
111
+ }
112
+ this.db
113
+ .prepare('UPDATE workspace_forget_locks SET retired_path=? WHERE operation_id=?')
114
+ .run(retired, operationId);
115
+ this.db.exec('COMMIT');
116
+ return retired;
117
+ }
118
+ catch (error) {
119
+ this.db.exec('ROLLBACK');
120
+ throw error;
121
+ }
122
+ }
123
+ }
@@ -24,7 +24,7 @@ export const orgPlanLaunchConflictSchema = z.discriminatedUnion('kind', [
24
24
  z
25
25
  .object({
26
26
  kind: z.literal('blocked'),
27
- code: z.enum(['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION']),
27
+ code: z.enum(['CONTEXT_CHANGED', 'ACTIVE_SUPERVISION', 'WORKSPACE_BUSY']),
28
28
  reason: z.string().min(1),
29
29
  existingSessionId: identity.optional(),
30
30
  })
@@ -3,9 +3,10 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- /** Every reason published by the bundled org-plan helper. */
6
+ /** Helper publications and Mobile's display-only attachment signal. */
7
7
  export const planSignalReasons = [
8
8
  'authoring-start',
9
+ 'display-open',
9
10
  'work-start',
10
11
  'checkpoint',
11
12
  'update',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gestalt-mobile",
3
- "version": "0.68.3",
3
+ "version": "0.68.5",
4
4
  "description": "Mobile-first web relay for durable Codex development sessions",
5
5
  "keywords": [
6
6
  "codex",