@myrialabs/clopen 0.4.37 → 0.4.39

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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Tests for the note query layer.
3
+ *
4
+ * The scope of a note is the scope of its collection and nothing else, so the
5
+ * cases that matter are the ones where those two could drift apart: a global
6
+ * collection must never carry a project id, a project collection must always
7
+ * carry one, and the cascade has to reach notes and images through it.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase, closeDatabase } from '../index';
14
+ import { projectQueries } from './project-queries';
15
+ import {
16
+ noteQueries,
17
+ noteCollectionQueries,
18
+ noteImageQueries,
19
+ DEFAULT_COLLECTION_NAME
20
+ } from './note-queries';
21
+
22
+ let projectId: string;
23
+ let collectionId: string;
24
+
25
+ function makeProject(name: string): string {
26
+ return projectQueries.create({
27
+ name,
28
+ // `projects.path` is unique, so a fixed path collides with whatever an
29
+ // earlier run left behind in the test data dir.
30
+ path: `/tmp/${name}-${randomUUID()}`,
31
+ created_at: new Date().toISOString(),
32
+ last_opened_at: new Date().toISOString()
33
+ }).id;
34
+ }
35
+
36
+ beforeAll(async () => {
37
+ await initializeDatabase();
38
+ projectId = makeProject('note-query-test');
39
+ collectionId = noteCollectionQueries.create({
40
+ name: 'General',
41
+ scope: 'project',
42
+ projectId
43
+ }).id;
44
+ });
45
+
46
+ afterAll(() => {
47
+ // Global collections outlive every project, so this suite cleans up its own.
48
+ for (const c of noteCollectionQueries.listByScope('global')) noteCollectionQueries.delete(c.id);
49
+ projectQueries.deleteProject(projectId);
50
+ closeDatabase();
51
+ });
52
+
53
+ describe('noteCollectionQueries', () => {
54
+ it('drops a project id handed to a global collection instead of failing the CHECK', () => {
55
+ const global = noteCollectionQueries.create({
56
+ name: 'Runbooks',
57
+ scope: 'global',
58
+ projectId
59
+ });
60
+ expect(global.scope).toBe('global');
61
+ expect(global.project_id).toBeNull();
62
+ noteCollectionQueries.delete(global.id);
63
+ });
64
+
65
+ it('keeps each scope’s collections out of the other’s list', () => {
66
+ const global = noteCollectionQueries.create({ name: 'Shared', scope: 'global' });
67
+
68
+ const projectIds = noteCollectionQueries.listByScope('project', projectId).map((c) => c.id);
69
+ const globalIds = noteCollectionQueries.listByScope('global').map((c) => c.id);
70
+
71
+ expect(projectIds).toContain(collectionId);
72
+ expect(projectIds).not.toContain(global.id);
73
+ expect(globalIds).toContain(global.id);
74
+ expect(globalIds).not.toContain(collectionId);
75
+
76
+ noteCollectionQueries.delete(global.id);
77
+ });
78
+
79
+ it('does not leak one project’s collections into another’s', () => {
80
+ const otherId = makeProject('note-query-other');
81
+ expect(noteCollectionQueries.listByScope('project', otherId)).toEqual([]);
82
+ projectQueries.deleteProject(otherId);
83
+ });
84
+
85
+ it('resolves the collection a note belongs to, which is where its access comes from', () => {
86
+ const note = noteQueries.create({ collectionId, content: 'body' });
87
+ expect(noteCollectionQueries.getForNote(note.id)?.id).toBe(collectionId);
88
+ noteQueries.delete(note.id);
89
+ });
90
+
91
+ it('returns null for a note that does not exist rather than a stray collection', () => {
92
+ expect(noteCollectionQueries.getForNote('missing-note')).toBeNull();
93
+ });
94
+
95
+ it('creates a default collection on first use, then reuses it', () => {
96
+ const emptyProject = makeProject('note-query-default');
97
+ const first = noteCollectionQueries.ensureDefault('project', emptyProject, null);
98
+ expect(first.name).toBe(DEFAULT_COLLECTION_NAME);
99
+ expect(noteCollectionQueries.ensureDefault('project', emptyProject, null).id).toBe(first.id);
100
+ projectQueries.deleteProject(emptyProject);
101
+ });
102
+
103
+ it('cascades its notes away when deleted', () => {
104
+ const doomed = noteCollectionQueries.create({ name: 'Doomed', scope: 'project', projectId });
105
+ const note = noteQueries.create({ collectionId: doomed.id, content: 'bye' });
106
+ noteCollectionQueries.delete(doomed.id);
107
+ expect(noteQueries.getRawById(note.id)).toBeNull();
108
+ });
109
+ });
110
+
111
+ describe('noteQueries', () => {
112
+ it('attaches each note its own images and nothing else', () => {
113
+ const withImages = noteQueries.create({ collectionId, content: 'has images' });
114
+ const withoutImages = noteQueries.create({ collectionId, content: 'no images' });
115
+
116
+ for (const name of ['a.png', 'b.png']) {
117
+ noteImageQueries.create({
118
+ noteId: withImages.id,
119
+ fileName: name,
120
+ mimeType: 'image/png',
121
+ size: 1,
122
+ storagePath: `notes/${collectionId}/${withImages.id}/${name}`
123
+ });
124
+ }
125
+
126
+ const byId = new Map(noteQueries.listByCollection(collectionId).map((n) => [n.id, n]));
127
+ expect(byId.get(withImages.id)?.images.map((i) => i.file_name).sort()).toEqual(['a.png', 'b.png']);
128
+ expect(byId.get(withoutImages.id)?.images).toEqual([]);
129
+
130
+ noteQueries.delete(withImages.id);
131
+ noteQueries.delete(withoutImages.id);
132
+ });
133
+
134
+ it('lists across several collections in one call', () => {
135
+ const other = noteCollectionQueries.create({ name: 'Specs', scope: 'project', projectId });
136
+ const a = noteQueries.create({ collectionId, content: 'a' });
137
+ const b = noteQueries.create({ collectionId: other.id, content: 'b' });
138
+
139
+ expect(noteQueries.listByCollections([collectionId, other.id]).map((n) => n.id).sort()).toEqual(
140
+ [a.id, b.id].sort()
141
+ );
142
+ // An empty set must not turn into "every note in the database".
143
+ expect(noteQueries.listByCollections([])).toEqual([]);
144
+
145
+ noteCollectionQueries.delete(other.id);
146
+ noteQueries.delete(a.id);
147
+ });
148
+
149
+ it('truncates oversized content on create and on update', () => {
150
+ const note = noteQueries.create({ collectionId, content: 'x'.repeat(250_000) });
151
+ expect(note.content.length).toBe(200_000);
152
+ expect(noteQueries.getById(note.id)?.content.length).toBe(200_000);
153
+
154
+ expect(noteQueries.update(note.id, { content: 'y'.repeat(250_000) })?.content.length).toBe(200_000);
155
+ noteQueries.delete(note.id);
156
+ });
157
+
158
+ it('leaves untouched fields alone when the patch omits them', () => {
159
+ const note = noteQueries.create({ collectionId, title: 'Keep me', content: 'original' });
160
+ const updated = noteQueries.update(note.id, { content: 'replaced' });
161
+ expect(updated?.title).toBe('Keep me');
162
+ expect(updated?.content).toBe('replaced');
163
+ expect(updated?.collection_id).toBe(collectionId);
164
+ noteQueries.delete(note.id);
165
+ });
166
+
167
+ it('moves a note between collections, which is what changes who can read it', () => {
168
+ const target = noteCollectionQueries.create({ name: 'Moved', scope: 'global' });
169
+ const note = noteQueries.create({ collectionId, content: 'travelling' });
170
+
171
+ expect(noteQueries.update(note.id, { collectionId: target.id })?.collection_id).toBe(target.id);
172
+ expect(noteCollectionQueries.getForNote(note.id)?.scope).toBe('global');
173
+
174
+ noteCollectionQueries.delete(target.id);
175
+ });
176
+
177
+ it('cascades image rows away with the note', () => {
178
+ const note = noteQueries.create({ collectionId, content: 'doomed' });
179
+ const image = noteImageQueries.create({
180
+ noteId: note.id,
181
+ fileName: 'c.png',
182
+ mimeType: 'image/png',
183
+ size: 3,
184
+ storagePath: `notes/${collectionId}/${note.id}/c.png`
185
+ });
186
+
187
+ noteQueries.delete(note.id);
188
+ expect(noteImageQueries.getById(image.id)).toBeNull();
189
+ });
190
+ });
@@ -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