@myrialabs/clopen 0.4.37 → 0.4.38

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 (101) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/http/integration-hooks.ts +42 -0
  28. package/backend/http/notes-images.test.ts +228 -0
  29. package/backend/http/notes-images.ts +196 -0
  30. package/backend/index.ts +9 -0
  31. package/backend/integrations/accounts.ts +229 -0
  32. package/backend/integrations/health.ts +146 -0
  33. package/backend/integrations/index.ts +36 -0
  34. package/backend/integrations/projections/index.ts +120 -0
  35. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  36. package/backend/integrations/projections/mcp-projector.ts +159 -0
  37. package/backend/integrations/projections/types.ts +51 -0
  38. package/backend/integrations/registry/define.ts +38 -0
  39. package/backend/integrations/registry/index.ts +56 -0
  40. package/backend/integrations/registry/providers/context7.ts +44 -0
  41. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  42. package/backend/integrations/registry/providers/github.ts +78 -0
  43. package/backend/integrations/registry/types.ts +96 -0
  44. package/backend/integrations/webhooks/gateway.ts +160 -0
  45. package/backend/integrations/webhooks/verify.ts +65 -0
  46. package/backend/mcp/README.md +25 -3
  47. package/backend/mcp/external/config.ts +35 -1
  48. package/backend/mcp/index.ts +1 -1
  49. package/backend/mcp/internal/config.ts +1 -1
  50. package/backend/notes/access.test.ts +82 -0
  51. package/backend/notes/access.ts +27 -0
  52. package/backend/notes/storage.test.ts +77 -0
  53. package/backend/notes/storage.ts +114 -0
  54. package/backend/permissions/service.ts +2 -2
  55. package/backend/profiles/service.ts +1 -1
  56. package/backend/projects/project-cleanup.ts +6 -0
  57. package/backend/work/bindings.ts +124 -0
  58. package/backend/work/index.ts +42 -0
  59. package/backend/work/prompts.ts +150 -0
  60. package/backend/work/providers/github/actions-logs.ts +180 -0
  61. package/backend/work/providers/github/adapter.test.ts +88 -0
  62. package/backend/work/providers/github/adapter.ts +1255 -0
  63. package/backend/work/providers/github/client.ts +280 -0
  64. package/backend/work/providers/github/list-range.test.ts +158 -0
  65. package/backend/work/providers/github/token-kind.test.ts +42 -0
  66. package/backend/work/pull-requests.ts +242 -0
  67. package/backend/work/registry.ts +27 -0
  68. package/backend/work/service.ts +436 -0
  69. package/backend/work/start-work.test.ts +71 -0
  70. package/backend/work/start-work.ts +232 -0
  71. package/backend/work/types.ts +180 -0
  72. package/backend/ws/files/clipboard.ts +78 -0
  73. package/backend/ws/files/index.ts +5 -0
  74. package/backend/ws/git/diff-budget.ts +70 -11
  75. package/backend/ws/index.ts +11 -1
  76. package/backend/ws/integrations/crud.ts +219 -0
  77. package/backend/ws/integrations/index.ts +22 -0
  78. package/backend/ws/mcp/crud.ts +25 -1
  79. package/backend/ws/notes/index.ts +278 -0
  80. package/backend/ws/profiles/crud.ts +1 -1
  81. package/backend/ws/work/actions.ts +206 -0
  82. package/backend/ws/work/context.ts +51 -0
  83. package/backend/ws/work/crud.ts +347 -0
  84. package/backend/ws/work/index.ts +17 -0
  85. package/backend/ws/work/pull-requests.ts +177 -0
  86. package/backend/ws/work/schemas.ts +226 -0
  87. package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
  88. package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
  89. package/dist/assets/main-D2IOjftb.css +1 -0
  90. package/dist/assets/main-DM-tHKbW.js +1152 -0
  91. package/dist/index.html +2 -2
  92. package/package.json +1 -1
  93. package/shared/constants/engine-tools.ts +1 -1
  94. package/shared/constants/tool-icons.ts +33 -0
  95. package/shared/types/database/schema.ts +41 -0
  96. package/shared/types/integrations.ts +140 -0
  97. package/shared/types/stores/settings.ts +8 -0
  98. package/shared/types/work.ts +426 -0
  99. package/shared/utils/logger.ts +3 -0
  100. package/dist/assets/main-DLqolBI2.css +0 -1
  101. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,269 @@
1
+ import { getDatabase } from '../index';
2
+ import type {
3
+ Note,
4
+ NoteCollection,
5
+ NoteImage,
6
+ NoteScope,
7
+ NoteWithImages
8
+ } from '$shared/types/database/schema';
9
+
10
+ const MAX_CONTENT_LENGTH = 200_000;
11
+ const MAX_NAME_LENGTH = 120;
12
+
13
+ /** Name given to the collection created on demand for a scope that has none. */
14
+ export const DEFAULT_COLLECTION_NAME = 'General';
15
+
16
+ function nowIso(): string {
17
+ return new Date().toISOString();
18
+ }
19
+
20
+ /**
21
+ * Attach each note's images in one round trip.
22
+ *
23
+ * Querying per note turns a collection list into 1 + N statements, which is what
24
+ * a project with a few dozen notes pays on every panel open and every switch.
25
+ */
26
+ function attachImages(notes: Note[]): NoteWithImages[] {
27
+ if (notes.length === 0) return [];
28
+ const db = getDatabase();
29
+ const placeholders = notes.map(() => '?').join(', ');
30
+ const rows = db
31
+ .prepare(
32
+ `SELECT * FROM note_images WHERE note_id IN (${placeholders}) ORDER BY created_at ASC`
33
+ )
34
+ .all(...notes.map((n) => n.id)) as NoteImage[];
35
+ const byNote = new Map<string, NoteImage[]>();
36
+ for (const row of rows) {
37
+ const bucket = byNote.get(row.note_id);
38
+ if (bucket) bucket.push(row);
39
+ else byNote.set(row.note_id, [row]);
40
+ }
41
+ return notes.map((note) => ({ ...note, images: byNote.get(note.id) ?? [] }));
42
+ }
43
+
44
+ export const noteCollectionQueries = {
45
+ /**
46
+ * Every collection in a scope.
47
+ *
48
+ * `projectId` is required for the `project` scope and ignored for `global`,
49
+ * matching the CHECK constraint on the table.
50
+ */
51
+ listByScope(scope: NoteScope, projectId?: string | null): NoteCollection[] {
52
+ const db = getDatabase();
53
+ if (scope === 'global') {
54
+ return db
55
+ .prepare("SELECT * FROM note_collections WHERE scope = 'global' ORDER BY name COLLATE NOCASE ASC")
56
+ .all() as NoteCollection[];
57
+ }
58
+ if (!projectId) return [];
59
+ return db
60
+ .prepare(
61
+ "SELECT * FROM note_collections WHERE scope = 'project' AND project_id = ? ORDER BY name COLLATE NOCASE ASC"
62
+ )
63
+ .all(projectId) as NoteCollection[];
64
+ },
65
+
66
+ getById(id: string): NoteCollection | null {
67
+ const db = getDatabase();
68
+ return db.prepare('SELECT * FROM note_collections WHERE id = ?').get(id) as NoteCollection | null;
69
+ },
70
+
71
+ /** The collection a note lives in — the note's only source of permissions. */
72
+ getForNote(noteId: string): NoteCollection | null {
73
+ const db = getDatabase();
74
+ return db
75
+ .prepare(
76
+ `SELECT c.* FROM note_collections c
77
+ JOIN notes n ON n.collection_id = c.id
78
+ WHERE n.id = ?`
79
+ )
80
+ .get(noteId) as NoteCollection | null;
81
+ },
82
+
83
+ create(params: {
84
+ name: string;
85
+ scope: NoteScope;
86
+ projectId?: string | null;
87
+ createdBy?: string | null;
88
+ }): NoteCollection {
89
+ const db = getDatabase();
90
+ const id = crypto.randomUUID();
91
+ const now = nowIso();
92
+ const name = params.name.trim().slice(0, MAX_NAME_LENGTH) || DEFAULT_COLLECTION_NAME;
93
+ // The table's CHECK rejects the mismatched pair; normalising here keeps a
94
+ // stray projectId on a global collection from becoming a constraint error.
95
+ const projectId = params.scope === 'project' ? (params.projectId ?? null) : null;
96
+ db.prepare(
97
+ `INSERT INTO note_collections (id, name, scope, project_id, created_by, created_at, updated_at)
98
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
99
+ ).run(id, name, params.scope, projectId, params.createdBy ?? null, now, now);
100
+ return {
101
+ id,
102
+ name,
103
+ scope: params.scope,
104
+ project_id: projectId,
105
+ created_by: params.createdBy ?? null,
106
+ created_at: now,
107
+ updated_at: now
108
+ };
109
+ },
110
+
111
+ /**
112
+ * The collection a new note should land in when the caller named none.
113
+ *
114
+ * Created on first use rather than seeded up front: a scope nobody has taken
115
+ * a note in should not carry an empty collection, and there is no migration
116
+ * that could have seeded one for a project created later.
117
+ */
118
+ ensureDefault(scope: NoteScope, projectId: string | null, createdBy: string | null): NoteCollection {
119
+ const existing = noteCollectionQueries.listByScope(scope, projectId);
120
+ if (existing.length > 0) return existing[0];
121
+ return noteCollectionQueries.create({
122
+ name: DEFAULT_COLLECTION_NAME,
123
+ scope,
124
+ projectId,
125
+ createdBy
126
+ });
127
+ },
128
+
129
+ rename(id: string, name: string): NoteCollection | null {
130
+ const db = getDatabase();
131
+ const existing = noteCollectionQueries.getById(id);
132
+ if (!existing) return null;
133
+ const trimmed = name.trim().slice(0, MAX_NAME_LENGTH);
134
+ if (!trimmed) return existing;
135
+ const now = nowIso();
136
+ db.prepare('UPDATE note_collections SET name = ?, updated_at = ? WHERE id = ?').run(trimmed, now, id);
137
+ return { ...existing, name: trimmed, updated_at: now };
138
+ },
139
+
140
+ delete(id: string): void {
141
+ const db = getDatabase();
142
+ db.prepare('DELETE FROM note_collections WHERE id = ?').run(id);
143
+ },
144
+
145
+ /** Collection ids belonging to a project, for cleaning their files off disk. */
146
+ idsByProject(projectId: string): string[] {
147
+ const db = getDatabase();
148
+ const rows = db
149
+ .prepare("SELECT id FROM note_collections WHERE scope = 'project' AND project_id = ?")
150
+ .all(projectId) as { id: string }[];
151
+ return rows.map((r) => r.id);
152
+ }
153
+ };
154
+
155
+ export const noteQueries = {
156
+ listByCollection(collectionId: string): NoteWithImages[] {
157
+ const db = getDatabase();
158
+ const notes = db
159
+ .prepare('SELECT * FROM notes WHERE collection_id = ? ORDER BY updated_at DESC')
160
+ .all(collectionId) as Note[];
161
+ return attachImages(notes);
162
+ },
163
+
164
+ /** Every note across a set of collections, grouped by the caller. */
165
+ listByCollections(collectionIds: string[]): NoteWithImages[] {
166
+ if (collectionIds.length === 0) return [];
167
+ const db = getDatabase();
168
+ const placeholders = collectionIds.map(() => '?').join(', ');
169
+ const notes = db
170
+ .prepare(`SELECT * FROM notes WHERE collection_id IN (${placeholders}) ORDER BY updated_at DESC`)
171
+ .all(...collectionIds) as Note[];
172
+ return attachImages(notes);
173
+ },
174
+
175
+ getById(id: string): NoteWithImages | null {
176
+ const db = getDatabase();
177
+ const note = db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as Note | null;
178
+ if (!note) return null;
179
+ return { ...note, images: noteImageQueries.listByNote(id) };
180
+ },
181
+
182
+ getRawById(id: string): Note | null {
183
+ const db = getDatabase();
184
+ return db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as Note | null;
185
+ },
186
+
187
+ create(params: { collectionId: string; title?: string | null; content?: string; createdBy?: string | null }): Note {
188
+ const db = getDatabase();
189
+ const id = crypto.randomUUID();
190
+ const now = nowIso();
191
+ const title = params.title?.trim() || null;
192
+ const content = (params.content ?? '').slice(0, MAX_CONTENT_LENGTH);
193
+ db.prepare(
194
+ `INSERT INTO notes (id, collection_id, title, content, created_by, created_at, updated_at)
195
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
196
+ ).run(id, params.collectionId, title, content, params.createdBy ?? null, now, now);
197
+ return {
198
+ id,
199
+ collection_id: params.collectionId,
200
+ title,
201
+ content,
202
+ created_by: params.createdBy ?? null,
203
+ created_at: now,
204
+ updated_at: now
205
+ };
206
+ },
207
+
208
+ update(
209
+ id: string,
210
+ patch: { title?: string | null; content?: string; collectionId?: string }
211
+ ): Note | null {
212
+ const db = getDatabase();
213
+ const existing = db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as Note | null;
214
+ if (!existing) return null;
215
+ const now = nowIso();
216
+ const title = patch.title !== undefined ? patch.title?.trim() || null : existing.title;
217
+ const content = patch.content !== undefined ? patch.content.slice(0, MAX_CONTENT_LENGTH) : existing.content;
218
+ const collectionId = patch.collectionId ?? existing.collection_id;
219
+ db.prepare('UPDATE notes SET title = ?, content = ?, collection_id = ?, updated_at = ? WHERE id = ?').run(
220
+ title,
221
+ content,
222
+ collectionId,
223
+ now,
224
+ id
225
+ );
226
+ return { ...existing, title, content, collection_id: collectionId, updated_at: now };
227
+ },
228
+
229
+ delete(id: string): void {
230
+ const db = getDatabase();
231
+ db.prepare('DELETE FROM notes WHERE id = ?').run(id);
232
+ }
233
+ };
234
+
235
+ export const noteImageQueries = {
236
+ listByNote(noteId: string): NoteImage[] {
237
+ const db = getDatabase();
238
+ return db.prepare('SELECT * FROM note_images WHERE note_id = ? ORDER BY created_at ASC').all(noteId) as NoteImage[];
239
+ },
240
+
241
+ getById(id: string): NoteImage | null {
242
+ const db = getDatabase();
243
+ return db.prepare('SELECT * FROM note_images WHERE id = ?').get(id) as NoteImage | null;
244
+ },
245
+
246
+ create(params: { noteId: string; fileName: string; mimeType: string; size: number; storagePath: string }): NoteImage {
247
+ const db = getDatabase();
248
+ const id = crypto.randomUUID();
249
+ const now = nowIso();
250
+ db.prepare(
251
+ `INSERT INTO note_images (id, note_id, file_name, mime_type, size, storage_path, created_at)
252
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
253
+ ).run(id, params.noteId, params.fileName, params.mimeType, params.size, params.storagePath, now);
254
+ return {
255
+ id,
256
+ note_id: params.noteId,
257
+ file_name: params.fileName,
258
+ mime_type: params.mimeType,
259
+ size: params.size,
260
+ storage_path: params.storagePath,
261
+ created_at: now
262
+ };
263
+ },
264
+
265
+ delete(id: string): void {
266
+ const db = getDatabase();
267
+ db.prepare('DELETE FROM note_images WHERE id = ?').run(id);
268
+ }
269
+ };
@@ -2,7 +2,7 @@
2
2
  * Profile Queries
3
3
  *
4
4
  * CRUD for reusable Profiles (Settings → Profiles) — named bundles that
5
- * reference existing artifacts (Skills, Commands, Subagents, MCP Connectors) by
5
+ * reference existing artifacts (Skills, Commands, Subagents, Integrations) by
6
6
  * their stable slug. The `profiles` table holds only the bundle metadata; the
7
7
  * `profile_items` table holds the (artifact_type, ref) references. Neither
8
8
  * duplicates artifact data — see migration 050.
@@ -1,7 +1,18 @@
1
1
  import { getDatabase } from '../index';
2
+ import { openRow, sealFor } from '../crypto';
2
3
  import type { DBSshConnectionRow } from '$shared/types/database/schema';
3
4
  import type { SshAuthMethod, SshConnection, SshConnectionInput } from '$shared/types/ssh';
4
5
 
6
+ // Password, private key and passphrase are sealed at rest (see
7
+ // backend/database/crypto). Reads open them before anything else touches the
8
+ // row, so the dialler and the panel are unchanged.
9
+ const TABLE = 'ssh_connections';
10
+
11
+ /** Open the sealed columns on a row straight out of SQLite. */
12
+ function openConnectionRow<T extends DBSshConnectionRow | null>(row: T): T {
13
+ return (row ? openRow(TABLE, row) : row) as T;
14
+ }
15
+
5
16
  function rowToConnection(row: DBSshConnectionRow): SshConnection {
6
17
  return {
7
18
  id: row.id,
@@ -57,7 +68,7 @@ function preserveExistingSecret(patchValue: string | undefined, existingValue: s
57
68
 
58
69
  function getRowById(id: string): DBSshConnectionRow | null {
59
70
  const db = getDatabase();
60
- return db.prepare('SELECT * FROM ssh_connections WHERE id = ?').get(id) as DBSshConnectionRow | null;
71
+ return openConnectionRow(db.prepare('SELECT * FROM ssh_connections WHERE id = ?').get(id) as DBSshConnectionRow | null);
61
72
  }
62
73
 
63
74
  /**
@@ -100,10 +111,10 @@ function insertConnection(input: SshConnectionInput, ownerUserId: string | null)
100
111
  input.port ?? 22,
101
112
  input.username,
102
113
  input.authMethod ?? 'password',
103
- input.password || null,
104
- input.privateKey || null,
114
+ sealFor(TABLE, 'password', input.password || null),
115
+ sealFor(TABLE, 'private_key', input.privateKey || null),
105
116
  input.privateKeyPath || null,
106
- input.passphrase || null,
117
+ sealFor(TABLE, 'passphrase', input.passphrase || null),
107
118
  input.agentSocket || null,
108
119
  input.jumpConnectionId || null,
109
120
  input.initialPath || null,
@@ -135,7 +146,7 @@ export const sshConnectionQueries = {
135
146
  ORDER BY (last_used_at IS NULL), last_used_at DESC, created_at DESC
136
147
  `).all(userId)) as DBSshConnectionRow[];
137
148
 
138
- return rows.map((row) => redactConnectionSecrets(rowToConnection(row)));
149
+ return rows.map((row) => redactConnectionSecrets(rowToConnection(openConnectionRow(row))));
139
150
  },
140
151
 
141
152
  getForUser(id: string, userId: string, isAdmin: boolean): SshConnection | null {
@@ -203,9 +214,9 @@ export const sshConnectionQueries = {
203
214
  push('jump_connection_id', jumpConnectionId);
204
215
  }
205
216
 
206
- if (patch.password !== undefined) push('password', preserveExistingSecret(patch.password, existing.password));
207
- if (patch.privateKey !== undefined) push('private_key', preserveExistingSecret(patch.privateKey, existing.private_key));
208
- if (patch.passphrase !== undefined) push('passphrase', preserveExistingSecret(patch.passphrase, existing.passphrase));
217
+ if (patch.password !== undefined) push('password', sealFor(TABLE, 'password', preserveExistingSecret(patch.password, existing.password)));
218
+ if (patch.privateKey !== undefined) push('private_key', sealFor(TABLE, 'private_key', preserveExistingSecret(patch.privateKey, existing.private_key)));
219
+ if (patch.passphrase !== undefined) push('passphrase', sealFor(TABLE, 'passphrase', preserveExistingSecret(patch.passphrase, existing.passphrase)));
209
220
 
210
221
  push('updated_at', new Date().toISOString());
211
222
 
@@ -0,0 +1,210 @@
1
+ /**
2
+ * Issues & PRs surface queries — bindings and work links.
3
+ *
4
+ * Neither table holds a secret, so nothing here goes through the crypto layer:
5
+ * a locator is `owner/repo` and the config is a behaviour flag. The credential
6
+ * that reaches the provider always comes from `integration_accounts`.
7
+ *
8
+ * Nothing about a work item itself is stored. See migration 074 for why: the
9
+ * provider is the truthful answer for titles, bodies and comments, and the only
10
+ * fact that cannot be re-derived is which worktree someone opened for it.
11
+ */
12
+
13
+ import { getDatabase } from '../index';
14
+ import type { WorkBindingConfig, WorkItemKind } from '$shared/types/work';
15
+ import { DEFAULT_BINDING_CONFIG } from '$shared/types/work';
16
+
17
+ export interface WorkBindingRow {
18
+ project_id: string;
19
+ account_id: string;
20
+ locator: string;
21
+ detected: number;
22
+ default_branch: string | null;
23
+ config_json: string;
24
+ created_at: string;
25
+ updated_at: string;
26
+ }
27
+
28
+ export interface WorkLinkRow {
29
+ id: string;
30
+ project_id: string;
31
+ account_id: string;
32
+ item_kind: WorkItemKind;
33
+ item_identifier: string;
34
+ item_title: string | null;
35
+ item_url: string | null;
36
+ worktree_id: string | null;
37
+ session_id: string | null;
38
+ branch: string | null;
39
+ created_at: string;
40
+ }
41
+
42
+ /**
43
+ * Parse the stored config over the defaults.
44
+ *
45
+ * Merging rather than replacing is deliberate: a config written before a new
46
+ * option existed must not read back with that option `undefined`, because the
47
+ * two places that consume it (`transitionOnStartWork`, `branchTemplate`) treat
48
+ * undefined and null differently and one of them would start naming branches
49
+ * `undefined-...`.
50
+ */
51
+ export function parseBindingConfig(raw: string | null): WorkBindingConfig {
52
+ if (!raw) return { ...DEFAULT_BINDING_CONFIG };
53
+ try {
54
+ const parsed = JSON.parse(raw) as Partial<WorkBindingConfig> | null;
55
+ return { ...DEFAULT_BINDING_CONFIG, ...(parsed ?? {}) };
56
+ } catch {
57
+ return { ...DEFAULT_BINDING_CONFIG };
58
+ }
59
+ }
60
+
61
+ export const workBindingQueries = {
62
+ getForProject(projectId: string): WorkBindingRow[] {
63
+ const db = getDatabase();
64
+ return db.prepare(
65
+ `SELECT * FROM work_bindings WHERE project_id = ?`
66
+ ).all(projectId) as WorkBindingRow[];
67
+ },
68
+
69
+ get(projectId: string, accountId: string): WorkBindingRow | null {
70
+ const db = getDatabase();
71
+ return db.prepare(
72
+ `SELECT * FROM work_bindings WHERE project_id = ? AND account_id = ?`
73
+ ).get(projectId, accountId) as WorkBindingRow | null;
74
+ },
75
+
76
+ upsert(input: {
77
+ projectId: string;
78
+ accountId: string;
79
+ locator: string;
80
+ detected: boolean;
81
+ defaultBranch?: string | null;
82
+ config?: WorkBindingConfig;
83
+ }): WorkBindingRow {
84
+ const db = getDatabase();
85
+ const now = new Date().toISOString();
86
+ const existing = this.get(input.projectId, input.accountId);
87
+
88
+ db.prepare(`
89
+ INSERT INTO work_bindings (
90
+ project_id, account_id, locator, detected, default_branch, config_json, created_at, updated_at
91
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
92
+ ON CONFLICT (project_id, account_id) DO UPDATE SET
93
+ locator = excluded.locator,
94
+ detected = excluded.detected,
95
+ default_branch = excluded.default_branch,
96
+ config_json = excluded.config_json,
97
+ updated_at = excluded.updated_at
98
+ `).run(
99
+ input.projectId,
100
+ input.accountId,
101
+ input.locator,
102
+ input.detected ? 1 : 0,
103
+ input.defaultBranch ?? existing?.default_branch ?? null,
104
+ JSON.stringify(input.config ?? parseBindingConfig(existing?.config_json ?? null)),
105
+ existing?.created_at ?? now,
106
+ now
107
+ );
108
+
109
+ return this.get(input.projectId, input.accountId)!;
110
+ },
111
+
112
+ /**
113
+ * Cache the default branch discovered by an API call.
114
+ *
115
+ * Separate from `upsert` so a background lookup cannot clobber a locator the
116
+ * user changed while it was in flight.
117
+ */
118
+ setDefaultBranch(projectId: string, accountId: string, branch: string): void {
119
+ const db = getDatabase();
120
+ db.prepare(
121
+ `UPDATE work_bindings SET default_branch = ?, updated_at = ? WHERE project_id = ? AND account_id = ?`
122
+ ).run(branch, new Date().toISOString(), projectId, accountId);
123
+ },
124
+
125
+ remove(projectId: string, accountId: string): void {
126
+ const db = getDatabase();
127
+ db.prepare(
128
+ `DELETE FROM work_bindings WHERE project_id = ? AND account_id = ?`
129
+ ).run(projectId, accountId);
130
+ }
131
+ };
132
+
133
+ export const workLinkQueries = {
134
+ getForProject(projectId: string): WorkLinkRow[] {
135
+ const db = getDatabase();
136
+ return db.prepare(
137
+ `SELECT * FROM work_links WHERE project_id = ? ORDER BY created_at DESC`
138
+ ).all(projectId) as WorkLinkRow[];
139
+ },
140
+
141
+ getByItem(
142
+ projectId: string,
143
+ accountId: string,
144
+ itemKind: WorkItemKind,
145
+ itemIdentifier: string
146
+ ): WorkLinkRow | null {
147
+ const db = getDatabase();
148
+ return db.prepare(`
149
+ SELECT * FROM work_links
150
+ WHERE project_id = ? AND account_id = ? AND item_kind = ? AND item_identifier = ?
151
+ `).get(projectId, accountId, itemKind, itemIdentifier) as WorkLinkRow | null;
152
+ },
153
+
154
+ /** Which item this branch was started from. The PR composer's whole lookup. */
155
+ getByBranch(projectId: string, branch: string): WorkLinkRow | null {
156
+ const db = getDatabase();
157
+ return db.prepare(`
158
+ SELECT * FROM work_links
159
+ WHERE project_id = ? AND branch = ?
160
+ ORDER BY created_at DESC LIMIT 1
161
+ `).get(projectId, branch) as WorkLinkRow | null;
162
+ },
163
+
164
+ upsert(input: {
165
+ projectId: string;
166
+ accountId: string;
167
+ itemKind: WorkItemKind;
168
+ itemIdentifier: string;
169
+ itemTitle?: string | null;
170
+ itemUrl?: string | null;
171
+ worktreeId?: string | null;
172
+ sessionId?: string | null;
173
+ branch?: string | null;
174
+ }): WorkLinkRow {
175
+ const db = getDatabase();
176
+ const now = new Date().toISOString();
177
+
178
+ db.prepare(`
179
+ INSERT INTO work_links (
180
+ id, project_id, account_id, item_kind, item_identifier,
181
+ item_title, item_url, worktree_id, session_id, branch, created_at
182
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
183
+ ON CONFLICT (project_id, account_id, item_kind, item_identifier) DO UPDATE SET
184
+ item_title = excluded.item_title,
185
+ item_url = excluded.item_url,
186
+ worktree_id = excluded.worktree_id,
187
+ session_id = excluded.session_id,
188
+ branch = excluded.branch
189
+ `).run(
190
+ crypto.randomUUID(),
191
+ input.projectId,
192
+ input.accountId,
193
+ input.itemKind,
194
+ input.itemIdentifier,
195
+ input.itemTitle ?? null,
196
+ input.itemUrl ?? null,
197
+ input.worktreeId ?? null,
198
+ input.sessionId ?? null,
199
+ input.branch ?? null,
200
+ now
201
+ );
202
+
203
+ return this.getByItem(input.projectId, input.accountId, input.itemKind, input.itemIdentifier)!;
204
+ },
205
+
206
+ remove(id: string): void {
207
+ const db = getDatabase();
208
+ db.prepare(`DELETE FROM work_links WHERE id = ?`).run(id);
209
+ }
210
+ };
@@ -5,7 +5,7 @@
5
5
  The adapters stream chat; **artifacts** are the reusable "extensions" the user
6
6
  manages in **Settings → Artifacts & Access** that shape what each engine sees and
7
7
  may do during that stream — Skills, Commands, Subagents, Instructions,
8
- Permissions, Profiles, and Connectors (MCP).
8
+ Permissions, Profiles, and Integrations (MCP).
9
9
 
10
10
  They are a **separate subsystem** (`backend/artifacts/` + one module per feature)
11
11
  that meets the adapter layer at exactly one seam: `backend/engine/artifact-sync.ts`,
@@ -21,7 +21,7 @@ each exposes a different native surface.
21
21
 
22
22
  | Menu (UI) | Backend module | WS router | Materialized as |
23
23
  |------------------|-------------------------|----------------------------|-----------------|
24
- | Connectors (MCP) | `backend/mcp/` | `backend/ws/mcp/` | config object + `/mcp/ext/<slug>` bridge — **not** a file artifact (see §8.5) |
24
+ | Integrations | `backend/mcp/` + `backend/integrations/` | `backend/ws/mcp/` + `backend/ws/integrations/` | config object + `/mcp/ext/<slug>` bridge — **not** a file artifact (see §8.5) |
25
25
  | Skills | `backend/skills/` | `backend/ws/skills/` | `folder-md` in a native dir, or synthetic preamble |
26
26
  | Commands | `backend/commands/` | `backend/ws/commands/` | `single-md` in a native dir, or synthetic preamble |
27
27
  | Subagents | `backend/subagents/` | `backend/ws/subagents/` | `single-md` in a native dir, or synthetic preamble |
@@ -101,14 +101,27 @@ reliably re-read per turn — the prompt is the one genuinely per-session channe
101
101
  | **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime check** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter runs at whichever surface fires for every tool call — for Claude a `PreToolUse` hook, since `bypassPermissions` auto-approves before `canUseTool` is consulted. The matrix only describes the optional on-disk file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`); its `deny` rules do bite even under `bypassPermissions`, an allowlist has no on-disk equivalent |
102
102
  | **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Commands-only profile never disables every Skill |
103
103
 
104
- ### 8.5 Connectors (MCP)
104
+ ### 8.5 Integrations (MCP + connected accounts)
105
105
 
106
- MCP is part of Artifacts & Access in the UI but is **not** part of this file
107
- framework — it has its own subsystem. MCP servers are config objects composed
108
- per engine and proxied through the `/mcp/ext/<slug>` bridge, so forcing them
109
- through a file writer/detector would be a mis-fit; the `'mcp'` slot in
110
- `ArtifactType` exists only for future extensibility. Profiles can still reference
111
- MCP connectors as bundle items (§8.4).
106
+ Integrations sit under Artifacts & Access in the UI but are **not** part of this
107
+ file framework — they have their own subsystem. MCP servers are config objects
108
+ composed per engine and proxied through the `/mcp/ext/<slug>` bridge, so forcing
109
+ them through a file writer/detector would be a mis-fit; the `'mcp'` slot in
110
+ `ArtifactType` exists only for future extensibility. Profiles can still
111
+ reference connectors as bundle items (§8.4).
112
+
113
+ Two modules, one menu:
114
+
115
+ - `backend/mcp/` — the protocol: install, proxy, per-engine tool exposure,
116
+ MCP-level OAuth.
117
+ - `backend/integrations/` — the connected account and its credential (sealed at
118
+ rest, see `backend/database/crypto/`). An account with the `agent-tools`
119
+ capability **projects** an `mcp_servers` row; other capabilities project onto
120
+ other surfaces, or onto none yet.
121
+
122
+ Nothing on the adapter path can tell a projected row from a hand-installed one,
123
+ which is the point: this layer stays off the path MCP config already flows
124
+ through.
112
125
 
113
126
  For MCP's own architecture — internal `defineServer()` tools, the OAuth client,
114
127
  the remote HTTP bridge, per-engine config, and tool overrides — see