gestalt-mobile 0.68.4 → 0.68.6

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 (35) hide show
  1. package/README.md +15 -4
  2. package/dist/client/assets/index-Dl5gXKZh.js +183 -0
  3. package/dist/client/index.html +1 -1
  4. package/dist/server/server/composition.contracts.js +232 -12
  5. package/dist/server/server/composition.js +111 -29
  6. package/dist/server/server/features/plans/application/plan-attachment-supervision.js +3 -1
  7. package/dist/server/server/features/plans/application/prepare-org-plan-supervision.js +18 -10
  8. package/dist/server/server/features/plans/application/start-org-plan-supervision.js +23 -4
  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/application/writer-acquisition.js +7 -0
  12. package/dist/server/server/features/sessions/forget-session/endpoint.js +7 -0
  13. package/dist/server/server/features/sessions/forget-session/use-case.js +8 -2
  14. package/dist/server/server/features/sessions/register-routes.js +1 -0
  15. package/dist/server/server/features/sessions/restore-session/endpoint.js +10 -1
  16. package/dist/server/server/features/sessions/start-session/endpoint.js +8 -0
  17. package/dist/server/server/features/sessions/start-turn/use-case.js +13 -1
  18. package/dist/server/server/platform/codex/error-code.js +2 -2
  19. package/dist/server/server/platform/codex/protocol-compatibility.js +7 -24
  20. package/dist/server/server/platform/codex/session-runtime.js +18 -0
  21. package/dist/server/server/platform/http/problem-handler.js +9 -0
  22. package/dist/server/server/platform/kimi/kimi-session-runtime.js +5 -0
  23. package/dist/server/server/platform/persistence/migrate.js +17 -0
  24. package/dist/server/server/platform/persistence/sqlite-event-journal.js +6 -2
  25. package/dist/server/server/platform/persistence/sqlite-forget-operation-store.js +38 -6
  26. package/dist/server/server/platform/persistence/sqlite-org-plan-launch-store.js +43 -16
  27. package/dist/server/server/platform/persistence/sqlite-session-repository.js +29 -7
  28. package/dist/server/server/platform/persistence/sqlite-workspace-lifecycle.js +59 -0
  29. package/dist/server/server/platform/plans/filesystem-plan-status-source.js +2 -2
  30. package/dist/server/server/platform/scratch/filesystem-session-scratch.js +3 -1
  31. package/dist/server/server/platform/scratch/filesystem-workspace-forget.js +123 -0
  32. package/dist/server/shared/contracts/org-plan-execution.js +1 -1
  33. package/dist/server/shared/contracts/plan-signal.js +2 -1
  34. package/package.json +1 -1
  35. package/dist/client/assets/index-CKyExrMf.js +0 -183
@@ -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')
@@ -3,8 +3,8 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export function protocolErrorCode(installed, expected) {
6
+ export function protocolErrorCode(installed) {
7
7
  if (!installed)
8
8
  return 'CODEX_NOT_FOUND';
9
- return installed === expected ? null : 'CODEX_PROTOCOL_MISMATCH';
9
+ return null;
10
10
  }
@@ -3,28 +3,11 @@
3
3
  * Designed by Denis Roio <jaromil@dyne.org>
4
4
  * SPDX-License-Identifier: AGPL-3.0-or-later
5
5
  */
6
- export function protocolCompatibility(installedVersion, protocolVersion) {
7
- if (!installedVersion)
8
- return { compatible: false, code: 'CODEX_NOT_FOUND' };
9
- const installed = parseCoreVersion(installedVersion);
10
- const expected = protocolVersion ? parseCoreVersion(protocolVersion) : undefined;
11
- // 0.x is pre-1.0: the minor is the core wire contract. Patch releases and
12
- // newer compatible minors are accepted only within a small forward window;
13
- // optional APIs are negotiated independently at runtime.
14
- if (!installed || !expected || !coreCompatible(installed, expected))
15
- return { compatible: false, code: 'CODEX_PROTOCOL_MISMATCH' };
16
- return { compatible: true };
17
- }
18
- function parseCoreVersion(value) {
19
- const match = /\b(\d+)\.(\d+)(?:\.(\d+))?\b/.exec(value);
20
- if (!match)
21
- return undefined;
22
- return { major: Number(match[1]), minor: Number(match[2]) };
23
- }
24
- function coreCompatible(installed, expected) {
25
- if (installed.major !== expected.major)
26
- return false;
27
- if (installed.major !== 0)
28
- return installed.minor === expected.minor;
29
- return installed.minor >= expected.minor && installed.minor <= expected.minor + 4;
6
+ import { protocolErrorCode } from './error-code.js';
7
+ /** Retain the public health flag without using version text as admission policy.
8
+ * Runtime operations and capability checks establish actual protocol support.
9
+ */
10
+ export function protocolCompatibility(installedVersion) {
11
+ const code = protocolErrorCode(installedVersion);
12
+ return code ? { compatible: false, code } : { compatible: true };
30
13
  }
@@ -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,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 { relative, isAbsolute } from 'node:path';
6
7
  export class SqliteOrgPlanLaunchStore {
7
8
  db;
8
9
  #operations = new Map();
@@ -22,19 +23,40 @@ export class SqliteOrgPlanLaunchStore {
22
23
  .prepare('SELECT record_json FROM org_plan_launches WHERE session_id=?')
23
24
  .get(sessionId));
24
25
  }
26
+ workspaceOwner(workspacePath) {
27
+ const records = this.db
28
+ .prepare('SELECT record_json FROM org_plan_launches WHERE canonical_path IS NOT NULL')
29
+ .all();
30
+ for (const row of records) {
31
+ const record = decode(row);
32
+ const overlaps = (parent, child) => {
33
+ const path = relative(parent, child);
34
+ return path === '' || (path !== '..' && !path.startsWith('../') && !isAbsolute(path));
35
+ };
36
+ if (overlaps(record.context.workspace.path, workspacePath) ||
37
+ overlaps(workspacePath, record.context.workspace.path))
38
+ return record;
39
+ }
40
+ return null;
41
+ }
25
42
  reserve(record) {
26
- const inserted = this.db
27
- .prepare('INSERT OR IGNORE INTO org_plan_launches (launch_id,canonical_path,session_id,phase,record_json) VALUES (?,?,?,?,?)')
28
- .run(record.launchId, record.canonicalPath, record.sessionId, record.phase, JSON.stringify(record));
29
- if (inserted.changes === 1)
30
- return { kind: 'reserved', record };
31
- const existing = this.find(record.launchId);
32
- if (existing)
33
- return { kind: 'existing', record: existing };
34
- const owner = this.owner(record.canonicalPath);
35
- if (!owner)
36
- throw new Error('ORG_PLAN_RESERVATION_CONFLICT');
37
- return { kind: 'owned', record: owner };
43
+ return this.activationTransaction(() => {
44
+ const existing = this.find(record.launchId);
45
+ if (existing)
46
+ return { kind: 'existing', record: existing };
47
+ const workspaceOwner = this.workspaceOwner(record.context.workspace.path);
48
+ if (workspaceOwner)
49
+ return { kind: 'owned', record: workspaceOwner };
50
+ const inserted = this.db
51
+ .prepare('INSERT OR IGNORE INTO org_plan_launches (launch_id,canonical_path,session_id,phase,record_json) VALUES (?,?,?,?,?)')
52
+ .run(record.launchId, record.canonicalPath, record.sessionId, record.phase, JSON.stringify(record));
53
+ if (inserted.changes === 1)
54
+ return { kind: 'reserved', record };
55
+ const owner = this.owner(record.canonicalPath);
56
+ if (!owner)
57
+ throw new Error('ORG_PLAN_RESERVATION_CONFLICT');
58
+ return { kind: 'owned', record: owner };
59
+ });
38
60
  }
39
61
  save(record, expected) {
40
62
  return (this.db
@@ -47,10 +69,15 @@ export class SqliteOrgPlanLaunchStore {
47
69
  .run(record.launchId, record.sessionId, record.canonicalPath);
48
70
  }
49
71
  acquireOwner(record) {
50
- this.db
51
- .prepare('UPDATE OR IGNORE org_plan_launches SET canonical_path=? WHERE launch_id=? AND session_id=? AND canonical_path IS NULL')
52
- .run(record.canonicalPath, record.launchId, record.sessionId);
53
- return this.owner(record.canonicalPath)?.launchId === record.launchId;
72
+ return this.activationTransaction(() => {
73
+ const owner = this.workspaceOwner(record.context.workspace.path);
74
+ if (owner && owner.launchId !== record.launchId)
75
+ return false;
76
+ this.db
77
+ .prepare('UPDATE OR IGNORE org_plan_launches SET canonical_path=? WHERE launch_id=? AND session_id=? AND canonical_path IS NULL')
78
+ .run(record.canonicalPath, record.launchId, record.sessionId);
79
+ return this.owner(record.canonicalPath)?.launchId === record.launchId;
80
+ });
54
81
  }
55
82
  publishSession(record, candidate, sessions) {
56
83
  this.db.exec('BEGIN IMMEDIATE');
@@ -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) {