@myrialabs/clopen 0.4.34 → 0.4.36

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 (125) hide show
  1. package/backend/artifacts/sync.test.ts +63 -0
  2. package/backend/artifacts/sync.ts +56 -3
  3. package/backend/auth/permissions.ts +7 -0
  4. package/backend/containers/actions.ts +316 -0
  5. package/backend/containers/disk-usage.test.ts +68 -0
  6. package/backend/containers/disk-usage.ts +170 -0
  7. package/backend/containers/logs.ts +335 -0
  8. package/backend/containers/monitor.ts +410 -0
  9. package/backend/containers/parse.test.ts +599 -0
  10. package/backend/containers/parse.ts +905 -0
  11. package/backend/containers/port-index.test.ts +91 -0
  12. package/backend/containers/port-index.ts +198 -0
  13. package/backend/containers/prune-job.test.ts +148 -0
  14. package/backend/containers/prune-job.ts +129 -0
  15. package/backend/containers/pty-backend.ts +337 -0
  16. package/backend/containers/pty.ts +114 -0
  17. package/backend/containers/runtime.ts +218 -0
  18. package/backend/containers/scan.ts +293 -0
  19. package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
  20. package/backend/database/migrations/index.ts +7 -0
  21. package/backend/database/queries/index.ts +1 -0
  22. package/backend/database/queries/session-queries.ts +50 -11
  23. package/backend/database/queries/worktree-queries.ts +148 -0
  24. package/backend/engine/adapters/opencode/server.ts +389 -83
  25. package/backend/engine/adapters/opencode/stream.ts +14 -14
  26. package/backend/engine/hot-reload.ts +25 -10
  27. package/backend/files/file-watcher.test.ts +105 -0
  28. package/backend/files/file-watcher.ts +80 -10
  29. package/backend/git/git-service.test.ts +33 -0
  30. package/backend/git/git-service.ts +7 -3
  31. package/backend/git/nested-repos.test.ts +292 -1
  32. package/backend/git/nested-repos.ts +330 -17
  33. package/backend/host/metrics.test.ts +110 -0
  34. package/backend/host/metrics.ts +235 -0
  35. package/backend/{ports → host}/runner.ts +19 -10
  36. package/backend/index.ts +16 -4
  37. package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
  38. package/backend/ports/attribute.test.ts +3 -2
  39. package/backend/ports/attribute.ts +6 -45
  40. package/backend/ports/kill.ts +1 -1
  41. package/backend/ports/monitor.ts +1 -1
  42. package/backend/ports/processes.ts +1 -1
  43. package/backend/ports/scan-host.ts +77 -8
  44. package/backend/ports/scan.test.ts +1 -1
  45. package/backend/ports/scan.ts +1 -1
  46. package/backend/ports/ssh-lineage.ts +1 -1
  47. package/backend/preview/browser/browser-pool.ts +81 -0
  48. package/backend/preview/browser/browser-preview-service.ts +142 -32
  49. package/backend/preview/browser/browser-tab-manager.ts +350 -113
  50. package/backend/preview/browser/browser-video-capture.ts +84 -31
  51. package/backend/preview/browser/types.ts +9 -0
  52. package/backend/projects/project-cleanup.integration.test.ts +1 -1
  53. package/backend/projects/project-cleanup.ts +7 -1
  54. package/backend/projects/shell-ownership.ts +65 -0
  55. package/backend/snapshot/snapshot-service.ts +6 -2
  56. package/backend/terminal/ptykit.ts +35 -6
  57. package/backend/utils/ws.ts +21 -1
  58. package/backend/worktrees/clone.ts +222 -0
  59. package/backend/worktrees/index.ts +29 -0
  60. package/backend/worktrees/merge.test.ts +93 -0
  61. package/backend/worktrees/merge.ts +232 -0
  62. package/backend/worktrees/paths.test.ts +60 -0
  63. package/backend/worktrees/paths.ts +60 -0
  64. package/backend/worktrees/resolve.ts +67 -0
  65. package/backend/worktrees/service.ts +315 -0
  66. package/backend/worktrees/tree.ts +59 -0
  67. package/backend/ws/access.ts +18 -0
  68. package/backend/ws/artifacts/generate.ts +2 -2
  69. package/backend/ws/chat/stream.ts +9 -2
  70. package/backend/ws/containers/actions.ts +156 -0
  71. package/backend/ws/containers/index.ts +43 -0
  72. package/backend/ws/containers/list.ts +146 -0
  73. package/backend/ws/containers/logs.ts +43 -0
  74. package/backend/ws/containers/tunnel.ts +101 -0
  75. package/backend/ws/files/panel-state-scope.test.ts +102 -0
  76. package/backend/ws/files/path-access.test.ts +93 -1
  77. package/backend/ws/files/path-access.ts +54 -5
  78. package/backend/ws/files/read.ts +15 -10
  79. package/backend/ws/files/search.ts +7 -7
  80. package/backend/ws/files/state.ts +70 -8
  81. package/backend/ws/files/watch.ts +16 -14
  82. package/backend/ws/git/branch-name.ts +3 -3
  83. package/backend/ws/git/branch.ts +15 -15
  84. package/backend/ws/git/commit-message.ts +3 -3
  85. package/backend/ws/git/commit.ts +17 -17
  86. package/backend/ws/git/conflict.ts +10 -10
  87. package/backend/ws/git/diff.ts +9 -9
  88. package/backend/ws/git/ignored.ts +9 -9
  89. package/backend/ws/git/log.ts +6 -4
  90. package/backend/ws/git/remote.ts +43 -43
  91. package/backend/ws/git/staging.ts +16 -16
  92. package/backend/ws/git/status.ts +47 -37
  93. package/backend/ws/index.ts +6 -0
  94. package/backend/ws/message-rate-limiter.test.ts +45 -0
  95. package/backend/ws/message-rate-limiter.ts +34 -3
  96. package/backend/ws/preview/access.ts +11 -3
  97. package/backend/ws/projects/index.ts +5 -1
  98. package/backend/ws/projects/info.test.ts +54 -0
  99. package/backend/ws/projects/info.ts +398 -0
  100. package/backend/ws/sessions/crud.ts +21 -6
  101. package/backend/ws/snapshot/restore.ts +11 -14
  102. package/backend/ws/ssh/connections.ts +8 -0
  103. package/backend/ws/system/device-info.ts +70 -96
  104. package/backend/ws/worktrees/crud.ts +187 -0
  105. package/backend/ws/worktrees/index.ts +33 -0
  106. package/backend/ws/worktrees/transfer.ts +88 -0
  107. package/dist/assets/{index-vW2RpdHu.js → index-Bg-SUCFg.js} +1 -1
  108. package/dist/assets/{index-gGTMFUa8.js → index-Cz4YpHVi.js} +1 -1
  109. package/dist/assets/main-9G7IpQpK.css +1 -0
  110. package/dist/assets/main-BofFsH8E.js +1085 -0
  111. package/dist/index.html +2 -2
  112. package/dist/manifest.json +9 -2
  113. package/package.json +1 -1
  114. package/shared/types/containers/container.ts +366 -0
  115. package/shared/types/containers/index.ts +5 -0
  116. package/shared/types/database/schema.ts +26 -0
  117. package/shared/types/host/index.ts +18 -0
  118. package/shared/types/ports/port.ts +47 -9
  119. package/shared/utils/logger.ts +3 -0
  120. package/shared/utils/workspace-scope.test.ts +80 -0
  121. package/shared/utils/workspace-scope.ts +57 -0
  122. package/shared/utils/ws-client.ts +92 -17
  123. package/shared/utils/ws-server.ts +83 -16
  124. package/dist/assets/main-CYCMEbXB.css +0 -1
  125. package/dist/assets/main-ZCojSzvW.js +0 -1060
@@ -0,0 +1,293 @@
1
+ /**
2
+ * Containers — one host, one scan, one table.
3
+ *
4
+ * Held per watched host so the runtime probe and the image/volume catalogue
5
+ * survive between ticks. That is what keeps a live panel down to a single
6
+ * command per tick: the container list is what changes second to second, while
7
+ * images and volumes change when someone builds or prunes, and re-reading them
8
+ * every tick would triple the cost of the view for an answer that is almost
9
+ * always identical.
10
+ */
11
+
12
+ import type {
13
+ ContainerEntry,
14
+ ContainerImageEntry,
15
+ ContainerLimitation,
16
+ ContainerNetworkEntry,
17
+ ContainerScanResult,
18
+ ContainerVolumeEntry
19
+ } from '$shared/types/containers';
20
+ import type { CommandRunner, ProbePlatform } from '../host/runner';
21
+ import {
22
+ containerArgv,
23
+ detectRuntime,
24
+ forgetRuntime,
25
+ limitationFor,
26
+ looksLikeRuntimeFailure,
27
+ tryRun
28
+ } from './runtime';
29
+ import {
30
+ linkUsage,
31
+ parseDockerImages,
32
+ parseDockerNetworks,
33
+ parseDockerPs,
34
+ parseDockerVolumes,
35
+ parseMounts,
36
+ parseNetworkMembership,
37
+ parsePodmanImages,
38
+ parsePodmanNetworks,
39
+ parsePodmanPs,
40
+ parsePodmanVolumes
41
+ } from './parse';
42
+ import { debug } from '$shared/utils/logger';
43
+ import { CONTAINER_TIMEOUTS } from '$shared/types/containers';
44
+
45
+ /** How long the image and volume lists are reused before being read again. */
46
+ const CATALOG_TTL_MS = 15_000;
47
+
48
+ /** Running first, then everything that could be started, then the wreckage. */
49
+ const STATE_ORDER: Record<ContainerEntry['state'], number> = {
50
+ running: 0,
51
+ paused: 1,
52
+ restarting: 2,
53
+ created: 3,
54
+ exited: 4,
55
+ removing: 5,
56
+ dead: 6,
57
+ unknown: 7
58
+ };
59
+
60
+ interface Catalog {
61
+ images: ContainerImageEntry[];
62
+ volumes: ContainerVolumeEntry[];
63
+ networks: ContainerNetworkEntry[];
64
+ limitations: ContainerLimitation[];
65
+ readAt: number;
66
+ }
67
+
68
+ export class HostContainerScanner {
69
+ private catalog: Catalog | null = null;
70
+ /**
71
+ * A scan already running. Callers join it rather than starting a second one:
72
+ * a remote scan can outlast the poll interval, and two in flight would double
73
+ * the SSH channels for the same answer.
74
+ */
75
+ private inFlight: Promise<ContainerScanResult> | null = null;
76
+
77
+ constructor(
78
+ private readonly hostId: string,
79
+ private readonly hostName: string,
80
+ private readonly runner: CommandRunner,
81
+ private readonly platform: ProbePlatform
82
+ ) {}
83
+
84
+ /** Read this host, joining a scan already in progress rather than racing it. */
85
+ async scan(now = Date.now()): Promise<ContainerScanResult> {
86
+ if (this.inFlight) return this.inFlight;
87
+ this.inFlight = this.runScan(now).finally(() => {
88
+ this.inFlight = null;
89
+ });
90
+ return this.inFlight;
91
+ }
92
+
93
+ private empty(
94
+ scannedAt: string,
95
+ limitations: ContainerLimitation[],
96
+ error: string | null = null
97
+ ): ContainerScanResult {
98
+ return {
99
+ hostId: this.hostId,
100
+ scannedAt,
101
+ runtime: null,
102
+ runtimeVersion: null,
103
+ runtimeProblem: 'none',
104
+ entries: [],
105
+ images: [],
106
+ volumes: [],
107
+ networks: [],
108
+ limitations,
109
+ error
110
+ };
111
+ }
112
+
113
+ private async runScan(now: number): Promise<ContainerScanResult> {
114
+ const scannedAt = new Date(now).toISOString();
115
+
116
+ const info = await detectRuntime(this.hostId, this.runner, this.platform, now);
117
+ if (info.problem !== 'none' || !info.runtime) {
118
+ const message = limitationFor(info, this.hostName);
119
+ return {
120
+ ...this.empty(scannedAt, message ? [{ code: problemCode(info.problem), message }] : []),
121
+ runtimeProblem: info.problem
122
+ };
123
+ }
124
+
125
+ const runtime = info.runtime;
126
+ const listing = await tryRun(
127
+ this.runner,
128
+ containerArgv(runtime, this.platform, [
129
+ 'ps',
130
+ '--all',
131
+ '--no-trunc',
132
+ '--format',
133
+ runtime === 'docker' ? '{{json .}}' : 'json'
134
+ ]),
135
+ CONTAINER_TIMEOUTS.list
136
+ );
137
+
138
+ if (listing.code !== 0) {
139
+ // The runtime answered `version` and then refused to list: it went away
140
+ // between the two, so the cached "this host has docker" must go too.
141
+ if (looksLikeRuntimeFailure(listing)) forgetRuntime(this.hostId);
142
+ const reason = listing.stderr.trim() || listing.stdout.trim() || `exit status ${listing.code}`;
143
+ return {
144
+ ...this.empty(scannedAt, [], reason),
145
+ runtime,
146
+ runtimeVersion: info.version
147
+ };
148
+ }
149
+
150
+ const entries =
151
+ runtime === 'docker'
152
+ ? parseDockerPs(listing.stdout, this.hostId)
153
+ : parsePodmanPs(listing.stdout, this.hostId);
154
+
155
+ entries.sort(
156
+ (a, b) =>
157
+ STATE_ORDER[a.state] - STATE_ORDER[b.state] ||
158
+ (a.composeProject ?? '').localeCompare(b.composeProject ?? '') ||
159
+ a.name.localeCompare(b.name)
160
+ );
161
+
162
+ const catalog = await this.readCatalog(runtime, now);
163
+ linkUsage(
164
+ entries,
165
+ catalog.images,
166
+ catalog.volumes,
167
+ parseMounts(listing.stdout, runtime),
168
+ catalog.networks,
169
+ parseNetworkMembership(listing.stdout, runtime)
170
+ );
171
+
172
+ return {
173
+ hostId: this.hostId,
174
+ scannedAt,
175
+ runtime,
176
+ runtimeVersion: info.version,
177
+ runtimeProblem: 'none',
178
+ entries,
179
+ images: catalog.images,
180
+ volumes: catalog.volumes,
181
+ networks: catalog.networks,
182
+ limitations: catalog.limitations,
183
+ error: null
184
+ };
185
+ }
186
+
187
+ /**
188
+ * Images, volumes and networks, re-read only when the cached set has aged
189
+ * out. A failure here degrades those tabs and nothing else — the container
190
+ * list is the point of the view and must not disappear because `volume ls`
191
+ * did.
192
+ */
193
+ private async readCatalog(runtime: 'docker' | 'podman', now: number): Promise<Catalog> {
194
+ if (this.catalog && now - this.catalog.readAt < CATALOG_TTL_MS) return this.catalog;
195
+
196
+ const limitations: ContainerLimitation[] = [];
197
+ const format = runtime === 'docker' ? '{{json .}}' : 'json';
198
+
199
+ const imagesResult = await tryRun(
200
+ this.runner,
201
+ containerArgv(runtime, this.platform, ['images', '--format', format]),
202
+ CONTAINER_TIMEOUTS.list
203
+ );
204
+ let images: ContainerImageEntry[] = this.catalog?.images ?? [];
205
+ if (imagesResult.code === 0) {
206
+ images =
207
+ runtime === 'docker'
208
+ ? parseDockerImages(imagesResult.stdout)
209
+ : parsePodmanImages(imagesResult.stdout);
210
+ } else {
211
+ debug.log('containers', `images unavailable on ${this.hostName}:`, imagesResult.stderr);
212
+ limitations.push({
213
+ code: 'images-unavailable',
214
+ message: `${this.hostName} did not return an image list${
215
+ imagesResult.stderr.trim() ? `: ${imagesResult.stderr.trim().split('\n')[0]}` : '.'
216
+ }`
217
+ });
218
+ }
219
+
220
+ const volumesResult = await tryRun(
221
+ this.runner,
222
+ containerArgv(runtime, this.platform, ['volume', 'ls', '--format', format]),
223
+ CONTAINER_TIMEOUTS.list
224
+ );
225
+ let volumes: ContainerVolumeEntry[] = this.catalog?.volumes ?? [];
226
+ if (volumesResult.code === 0) {
227
+ volumes =
228
+ runtime === 'docker'
229
+ ? parseDockerVolumes(volumesResult.stdout)
230
+ : parsePodmanVolumes(volumesResult.stdout);
231
+ } else {
232
+ debug.log('containers', `volumes unavailable on ${this.hostName}:`, volumesResult.stderr);
233
+ limitations.push({
234
+ code: 'volumes-unavailable',
235
+ message: `${this.hostName} did not return a volume list${
236
+ volumesResult.stderr.trim() ? `: ${volumesResult.stderr.trim().split('\n')[0]}` : '.'
237
+ }`
238
+ });
239
+ }
240
+
241
+ const networksResult = await tryRun(
242
+ this.runner,
243
+ containerArgv(runtime, this.platform, ['network', 'ls', '--format', format]),
244
+ CONTAINER_TIMEOUTS.list
245
+ );
246
+ let networks: ContainerNetworkEntry[] = this.catalog?.networks ?? [];
247
+ if (networksResult.code === 0) {
248
+ networks =
249
+ runtime === 'docker'
250
+ ? parseDockerNetworks(networksResult.stdout)
251
+ : parsePodmanNetworks(networksResult.stdout);
252
+ } else {
253
+ debug.log('containers', `networks unavailable on ${this.hostName}:`, networksResult.stderr);
254
+ limitations.push({
255
+ code: 'networks-unavailable',
256
+ message: `${this.hostName} did not return a network list${
257
+ networksResult.stderr.trim() ? `: ${networksResult.stderr.trim().split('\n')[0]}` : '.'
258
+ }`
259
+ });
260
+ }
261
+
262
+ images.sort(
263
+ (a, b) => Number(a.dangling) - Number(b.dangling) || a.repository.localeCompare(b.repository)
264
+ );
265
+ volumes.sort((a, b) => a.name.localeCompare(b.name));
266
+ // The runtime's own networks last: they are furniture, not something the
267
+ // user made, and they can never be acted on.
268
+ networks.sort(
269
+ (a, b) => Number(a.predefined) - Number(b.predefined) || a.name.localeCompare(b.name)
270
+ );
271
+
272
+ this.catalog = { images, volumes, networks, limitations, readAt: now };
273
+ return this.catalog;
274
+ }
275
+
276
+ /** Force the next scan to re-read images and volumes, after an action. */
277
+ invalidateCatalog(): void {
278
+ this.catalog = null;
279
+ }
280
+ }
281
+
282
+ function problemCode(
283
+ problem: 'none' | 'not-installed' | 'daemon-unreachable' | 'permission-denied'
284
+ ): ContainerLimitation['code'] {
285
+ switch (problem) {
286
+ case 'not-installed':
287
+ return 'no-runtime';
288
+ case 'permission-denied':
289
+ return 'permission-denied';
290
+ default:
291
+ return 'daemon-unreachable';
292
+ }
293
+ }
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Migration: Worktrees — isolated copies of a project that sessions can run in.
3
+ * Purpose: let several tasks run in parallel without touching the main tree.
4
+ */
5
+
6
+ import type { DatabaseConnection } from '$shared/types/database/connection';
7
+ import { debug } from '$shared/utils/logger';
8
+
9
+ export const description = 'Create worktrees table and bind chat sessions to a worktree';
10
+
11
+ export const up = (db: DatabaseConnection): void => {
12
+ debug.log('migration', '📋 Creating worktrees table...');
13
+
14
+ // `base_tree` is the merge base: a TreeMap (relative path → blob hash) of the
15
+ // main tree captured when the worktree was cloned. Apply/sync compare against
16
+ // it, so it must survive restarts — hence a column rather than memory.
17
+ db.exec(`
18
+ CREATE TABLE IF NOT EXISTS worktrees (
19
+ id TEXT PRIMARY KEY,
20
+ project_id TEXT NOT NULL REFERENCES projects(id) ON DELETE CASCADE,
21
+ name TEXT NOT NULL,
22
+ slug TEXT NOT NULL,
23
+ path TEXT NOT NULL,
24
+ status TEXT NOT NULL DEFAULT 'active'
25
+ CHECK (status IN ('active','applied','archived')),
26
+ clone_mode TEXT NOT NULL DEFAULT 'copy'
27
+ CHECK (clone_mode IN ('reflink','copy')),
28
+ base_tree TEXT NOT NULL,
29
+ created_by TEXT,
30
+ created_at TEXT NOT NULL,
31
+ last_opened_at TEXT,
32
+ last_applied_at TEXT
33
+ )
34
+ `);
35
+
36
+ db.exec(`
37
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_project_slug
38
+ ON worktrees(project_id, slug)
39
+ `);
40
+
41
+ db.exec(`
42
+ CREATE INDEX IF NOT EXISTS idx_worktrees_project
43
+ ON worktrees(project_id)
44
+ `);
45
+
46
+ debug.log('migration', '📋 Binding chat sessions to worktrees...');
47
+
48
+ // NULL = the session runs in the main project tree.
49
+ db.exec(`ALTER TABLE chat_sessions ADD COLUMN worktree_id TEXT`);
50
+
51
+ db.exec(`
52
+ CREATE INDEX IF NOT EXISTS idx_chat_sessions_worktree
53
+ ON chat_sessions(worktree_id)
54
+ `);
55
+
56
+ debug.log('migration', '✅ Worktrees ready');
57
+ };
58
+
59
+ export const down = (db: DatabaseConnection): void => {
60
+ debug.log('migration', '🗑️ Dropping worktrees...');
61
+ db.exec('DROP INDEX IF EXISTS idx_chat_sessions_worktree');
62
+ db.exec('DROP INDEX IF EXISTS idx_worktrees_project');
63
+ db.exec('DROP INDEX IF EXISTS idx_worktrees_project_slug');
64
+ db.exec('DROP TABLE IF EXISTS worktrees');
65
+ debug.warn('migration', '⚠️ chat_sessions.worktree_id remains (SQLite drop-column)');
66
+ debug.log('migration', '✅ Worktrees rollback completed');
67
+ };
@@ -68,6 +68,7 @@ import * as migration066 from './066_create_memory_graph';
68
68
  import * as migration067 from './067_add_memory_graph_layout';
69
69
  import * as migration068 from './068_create_engine_config_revision';
70
70
  import * as migration069 from './069_create_ssh_client_tables';
71
+ import * as migration070 from './070_create_worktrees_table';
71
72
 
72
73
  // Export all migrations in order
73
74
  export const migrations = [
@@ -484,6 +485,12 @@ export const migrations = [
484
485
  description: migration069.description,
485
486
  up: migration069.up,
486
487
  down: migration069.down
488
+ },
489
+ {
490
+ id: '070',
491
+ description: migration070.description,
492
+ up: migration070.up,
493
+ down: migration070.down
487
494
  }
488
495
  ];
489
496
 
@@ -5,6 +5,7 @@ export { messageQueries } from './message-queries';
5
5
  export { settingsQueries } from './settings-queries';
6
6
  export { dbUtils } from './utils-queries';
7
7
  export { snapshotQueries } from './snapshot-queries';
8
+ export { worktreeQueries } from './worktree-queries';
8
9
  export { checkpointQueries } from './checkpoint-queries';
9
10
  export { engineQueries } from './engine-queries';
10
11
  export { authQueries } from './auth-queries';
@@ -41,8 +41,8 @@ export const sessionQueries = {
41
41
  const newSession = { id, ...session };
42
42
 
43
43
  db.prepare(`
44
- INSERT INTO chat_sessions (id, project_id, title, engine, head_session_id, head_message_id, started_at, ended_at)
45
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)
44
+ INSERT INTO chat_sessions (id, project_id, title, engine, head_session_id, head_message_id, started_at, ended_at, worktree_id)
45
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
46
46
  `).run(
47
47
  id,
48
48
  session.project_id,
@@ -51,7 +51,8 @@ export const sessionQueries = {
51
51
  session.head_session_id || null,
52
52
  session.head_message_id || null,
53
53
  session.started_at,
54
- session.ended_at || null
54
+ session.ended_at || null,
55
+ session.worktree_id || null
55
56
  );
56
57
 
57
58
  return newSession;
@@ -104,6 +105,14 @@ export const sessionQueries = {
104
105
  },
105
106
 
106
107
  /** Persist the active profile for a session (NULL clears it). */
108
+ /** Bind a session to a worktree; null puts it back on the main project tree. */
109
+ setWorktree(id: string, worktreeId: string | null): void {
110
+ const db = getDatabase();
111
+ db.prepare(`
112
+ UPDATE chat_sessions SET worktree_id = ? WHERE id = ?
113
+ `).run(worktreeId, id);
114
+ },
115
+
107
116
  updateProfile(id: string, profileId: number | null): void {
108
117
  const db = getDatabase();
109
118
  db.prepare(`
@@ -440,14 +449,37 @@ export const sessionQueries = {
440
449
  * Get the active shared session for a project
441
450
  * Returns the most recent session that hasn't ended
442
451
  */
443
- getActiveSessionForProject(projectId: string): ChatSession | null {
452
+ /**
453
+ * Most recent active session, optionally restricted to one worktree.
454
+ * `worktreeId` undefined means "any"; null means "the main tree only".
455
+ */
456
+ getActiveSessionForProject(projectId: string, worktreeId?: string | null): ChatSession | null {
444
457
  const db = getDatabase();
458
+
459
+ if (worktreeId === undefined) {
460
+ return db.prepare(`
461
+ SELECT * FROM chat_sessions
462
+ WHERE project_id = ? AND ended_at IS NULL
463
+ ORDER BY started_at DESC
464
+ LIMIT 1
465
+ `).get(projectId) as ChatSession | null;
466
+ }
467
+
468
+ if (worktreeId === null) {
469
+ return db.prepare(`
470
+ SELECT * FROM chat_sessions
471
+ WHERE project_id = ? AND ended_at IS NULL AND worktree_id IS NULL
472
+ ORDER BY started_at DESC
473
+ LIMIT 1
474
+ `).get(projectId) as ChatSession | null;
475
+ }
476
+
445
477
  return db.prepare(`
446
- SELECT * FROM chat_sessions
447
- WHERE project_id = ? AND ended_at IS NULL
478
+ SELECT * FROM chat_sessions
479
+ WHERE project_id = ? AND ended_at IS NULL AND worktree_id = ?
448
480
  ORDER BY started_at DESC
449
481
  LIMIT 1
450
- `).get(projectId) as ChatSession | null;
482
+ `).get(projectId, worktreeId) as ChatSession | null;
451
483
  },
452
484
 
453
485
  /**
@@ -468,10 +500,16 @@ export const sessionQueries = {
468
500
  * When forceNew=true, creates a new session WITHOUT ending existing ones
469
501
  * (multiple sessions can be active in parallel).
470
502
  */
471
- getOrCreateSharedSession(projectId: string, projectName: string, forceNew: boolean = false): ChatSession {
503
+ getOrCreateSharedSession(
504
+ projectId: string,
505
+ projectName: string,
506
+ forceNew: boolean = false,
507
+ worktreeId: string | null = null
508
+ ): ChatSession {
472
509
  if (!forceNew) {
473
- // Return most recent active session if exists
474
- const activeSession = this.getActiveSessionForProject(projectId);
510
+ // Reuse only within the same tree — a session bound to a worktree is
511
+ // not a substitute for one on main, and vice versa.
512
+ const activeSession = this.getActiveSessionForProject(projectId, worktreeId);
475
513
  if (activeSession) {
476
514
  return activeSession;
477
515
  }
@@ -484,7 +522,8 @@ export const sessionQueries = {
484
522
  title: `Shared Chat - ${projectName} (${new Date().toLocaleString()})`,
485
523
  started_at: now,
486
524
  ended_at: undefined,
487
- head_session_id: undefined
525
+ head_session_id: undefined,
526
+ worktree_id: worktreeId
488
527
  });
489
528
  },
490
529
 
@@ -0,0 +1,148 @@
1
+ /**
2
+ * Database queries for worktrees — isolated project copies that sessions run in.
3
+ */
4
+
5
+ import type { Worktree, WorktreeCloneMode, WorktreeStatus } from '$shared/types/database/schema';
6
+ import type { TreeMap } from '../../snapshot/blob-store';
7
+ import { getDatabase } from '../index';
8
+
9
+ export const worktreeQueries = {
10
+ getByProjectId(projectId: string): Worktree[] {
11
+ const db = getDatabase();
12
+ return db.prepare(`
13
+ SELECT * FROM worktrees
14
+ WHERE project_id = ?
15
+ ORDER BY created_at DESC
16
+ `).all(projectId) as Worktree[];
17
+ },
18
+
19
+ getById(id: string): Worktree | null {
20
+ const db = getDatabase();
21
+ return db.prepare(`SELECT * FROM worktrees WHERE id = ?`).get(id) as Worktree | null;
22
+ },
23
+
24
+ getByPath(worktreePath: string): Worktree | null {
25
+ const db = getDatabase();
26
+ return db.prepare(`SELECT * FROM worktrees WHERE path = ?`).get(worktreePath) as Worktree | null;
27
+ },
28
+
29
+ getBySlug(projectId: string, slug: string): Worktree | null {
30
+ const db = getDatabase();
31
+ return db.prepare(`
32
+ SELECT * FROM worktrees WHERE project_id = ? AND slug = ?
33
+ `).get(projectId, slug) as Worktree | null;
34
+ },
35
+
36
+ create(input: {
37
+ project_id: string;
38
+ name: string;
39
+ slug: string;
40
+ path: string;
41
+ clone_mode: WorktreeCloneMode;
42
+ base_tree: TreeMap;
43
+ created_by?: string | null;
44
+ }): Worktree {
45
+ const db = getDatabase();
46
+ const id = crypto.randomUUID();
47
+ const now = new Date().toISOString();
48
+
49
+ const worktree: Worktree = {
50
+ id,
51
+ project_id: input.project_id,
52
+ name: input.name,
53
+ slug: input.slug,
54
+ path: input.path,
55
+ status: 'active',
56
+ clone_mode: input.clone_mode,
57
+ base_tree: JSON.stringify(input.base_tree),
58
+ created_by: input.created_by ?? null,
59
+ created_at: now,
60
+ last_opened_at: now,
61
+ last_applied_at: null
62
+ };
63
+
64
+ db.prepare(`
65
+ INSERT INTO worktrees (
66
+ id, project_id, name, slug, path, status, clone_mode,
67
+ base_tree, created_by, created_at, last_opened_at, last_applied_at
68
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
69
+ `).run(
70
+ worktree.id,
71
+ worktree.project_id,
72
+ worktree.name,
73
+ worktree.slug,
74
+ worktree.path,
75
+ worktree.status,
76
+ worktree.clone_mode,
77
+ worktree.base_tree,
78
+ worktree.created_by,
79
+ worktree.created_at,
80
+ worktree.last_opened_at
81
+ );
82
+
83
+ return worktree;
84
+ },
85
+
86
+ rename(id: string, name: string): void {
87
+ const db = getDatabase();
88
+ db.prepare(`UPDATE worktrees SET name = ? WHERE id = ?`).run(name, id);
89
+ },
90
+
91
+ touch(id: string): void {
92
+ const db = getDatabase();
93
+ db.prepare(`UPDATE worktrees SET last_opened_at = ? WHERE id = ?`)
94
+ .run(new Date().toISOString(), id);
95
+ },
96
+
97
+ setStatus(id: string, status: WorktreeStatus): void {
98
+ const db = getDatabase();
99
+ db.prepare(`UPDATE worktrees SET status = ? WHERE id = ?`).run(status, id);
100
+ },
101
+
102
+ /** Record a successful apply and re-base the worktree onto the tree it just produced. */
103
+ markApplied(id: string, baseTree: TreeMap): void {
104
+ const db = getDatabase();
105
+ db.prepare(`
106
+ UPDATE worktrees SET status = 'applied', last_applied_at = ?, base_tree = ?
107
+ WHERE id = ?
108
+ `).run(new Date().toISOString(), JSON.stringify(baseTree), id);
109
+ },
110
+
111
+ /** Re-base without changing status — used by sync-from-main. */
112
+ updateBaseTree(id: string, baseTree: TreeMap): void {
113
+ const db = getDatabase();
114
+ db.prepare(`UPDATE worktrees SET base_tree = ? WHERE id = ?`)
115
+ .run(JSON.stringify(baseTree), id);
116
+ },
117
+
118
+ delete(id: string): void {
119
+ const db = getDatabase();
120
+ // Sessions outlive their worktree: they fall back to the main tree rather
121
+ // than disappearing with it, so only the pointer is cleared.
122
+ db.prepare(`UPDATE chat_sessions SET worktree_id = NULL WHERE worktree_id = ?`).run(id);
123
+ db.prepare(`DELETE FROM worktrees WHERE id = ?`).run(id);
124
+ },
125
+
126
+ deleteByProjectId(projectId: string): Worktree[] {
127
+ const db = getDatabase();
128
+ const worktrees = this.getByProjectId(projectId);
129
+ db.prepare(`DELETE FROM worktrees WHERE project_id = ?`).run(projectId);
130
+ return worktrees;
131
+ },
132
+
133
+ countSessions(worktreeId: string): number {
134
+ const db = getDatabase();
135
+ const row = db.prepare(`
136
+ SELECT COUNT(*) AS total FROM chat_sessions WHERE worktree_id = ?
137
+ `).get(worktreeId) as { total: number } | undefined;
138
+ return row?.total ?? 0;
139
+ },
140
+
141
+ parseBaseTree(worktree: Worktree): TreeMap {
142
+ try {
143
+ return JSON.parse(worktree.base_tree) as TreeMap;
144
+ } catch {
145
+ return {};
146
+ }
147
+ }
148
+ };