@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,22 @@
1
+ /**
2
+ * Integrations Router
3
+ *
4
+ * Connect, reconfigure and disconnect third-party accounts. What an integration
5
+ * DOES is not here — that lives in the surface that owns the work.
6
+ */
7
+
8
+ import { t } from 'elysia';
9
+ import { createRouter } from '$shared/utils/ws-server';
10
+ import { integrationsCrudHandler } from './crud';
11
+
12
+ export const integrationsRouter = createRouter()
13
+ .merge(integrationsCrudHandler)
14
+ /**
15
+ * Broadcast after any account mutation. The hub also shows connectors, whose
16
+ * rows a projection creates and removes, so a client that only watched its
17
+ * own request would miss a connector appearing because someone else
18
+ * connected an account.
19
+ */
20
+ .emit('integrations:changed', t.Object({
21
+ accountId: t.Optional(t.String())
22
+ }));
@@ -25,7 +25,8 @@ import {
25
25
  completeAuthorization,
26
26
  getValidAccessToken,
27
27
  parseMcpConfig,
28
- parseToolOverrides
28
+ parseToolOverrides,
29
+ getEngineConfigsForServer
29
30
  } from '$backend/mcp';
30
31
 
31
32
  const TRANSPORT_SCHEMA = t.Union([t.Literal('stdio'), t.Literal('http'), t.Literal('sse')]);
@@ -325,4 +326,27 @@ export const mcpCrudHandler = createRouter()
325
326
  mcpServerQueries.remove(data.id);
326
327
  debug.log('mcp', `🗑️ Uninstalled external MCP server: ${existing.slug}`);
327
328
  return { success: true };
329
+ })
330
+ /**
331
+ * What each engine is actually handed for this server.
332
+ *
333
+ * Not the same thing as the stored row: every external server reaches an
334
+ * engine as a Streamable-HTTP remote pointing at Clopen's own proxy, so
335
+ * showing the row and labelling it "the engine's config" would mislead.
336
+ * Returned as a JSON string per engine because the shapes differ by SDK and
337
+ * the UI only ever prints them.
338
+ */
339
+ .http('mcp:engine-config', {
340
+ data: t.Object({ id: t.Number() }),
341
+ response: t.Object({ configs: t.Record(t.String(), t.String()) })
342
+ }, async ({ data }) => {
343
+ debug.log('path', `mcp:engine-config ${data.id}`);
344
+ const existing = mcpServerQueries.getById(data.id);
345
+ if (!existing) throw new Error('MCP server not found');
346
+
347
+ const configs = Object.fromEntries(
348
+ Object.entries(getEngineConfigsForServer(existing.slug))
349
+ .map(([engine, config]) => [engine, JSON.stringify(config, null, 2)])
350
+ );
351
+ return { configs };
328
352
  });
@@ -39,9 +39,8 @@ import { getMemoryReadiness } from '$backend/memory/readiness';
39
39
  import { reconcileVectorIndex } from '$backend/memory/indexer';
40
40
  import { ensureEmbeddingArtifact, embedder, vectorCache } from '$backend/memory/embedding';
41
41
  import type { EngineType } from '$shared/types/unified';
42
- import type { GraphNodeKind, GraphScope, GraphSource } from '$shared/types/memory';
42
+ import type { GraphScope, GraphSource } from '$shared/types/memory';
43
43
 
44
- const KIND = t.Union([t.Literal('episodic'), t.Literal('structural')]);
45
44
  const SCOPE = t.Union([t.Literal('session'), t.Literal('project'), t.Literal('global')]);
46
45
  const SOURCE = t.Union([t.Literal('agent'), t.Literal('user')]);
47
46
  const EPISODIC_SUBKIND = t.Union([
@@ -55,16 +54,14 @@ const EPISODIC_SUBKIND = t.Union([
55
54
 
56
55
  const NODE = t.Object({
57
56
  id: t.String(),
58
- kind: t.String(),
59
57
  subkind: t.String(),
60
58
  scope: t.String(),
61
59
  projectId: t.Union([t.String(), t.Null()]),
62
60
  sessionId: t.Union([t.String(), t.Null()]),
63
61
  label: t.String(),
64
62
  body: t.String(),
65
- path: t.Union([t.String(), t.Null()]),
66
- symbol: t.Union([t.String(), t.Null()]),
67
- language: t.Union([t.String(), t.Null()]),
63
+ /** Repo-relative paths this memory claims something about; see migration 076. */
64
+ relatedPaths: t.Optional(t.Array(t.String())),
68
65
  digest: t.String(),
69
66
  confidence: t.Number(),
70
67
  weight: t.Number(),
@@ -94,7 +91,6 @@ const MEMORY_MODEL = t.Object({
94
91
 
95
92
  const CONFIG = t.Object({
96
93
  enabled: t.Boolean(),
97
- recordCode: t.Boolean(),
98
94
  recordMemories: t.Boolean(),
99
95
  autoRecall: t.Boolean(),
100
96
  model: t.Union([MEMORY_MODEL, t.Null()])
@@ -171,7 +167,6 @@ export const memoryCrudHandler = createRouter()
171
167
  .http('memory:graph', {
172
168
  data: t.Object({
173
169
  projectIds: t.Optional(t.Array(t.String())),
174
- kinds: t.Optional(t.Array(KIND)),
175
170
  subkinds: t.Optional(t.Array(t.String())),
176
171
  scopes: t.Optional(t.Array(SCOPE)),
177
172
  sources: t.Optional(t.Array(SOURCE)),
@@ -193,7 +188,6 @@ export const memoryCrudHandler = createRouter()
193
188
  level: t.String(),
194
189
  nodes: t.Array(t.Object({
195
190
  id: t.String(),
196
- kind: t.String(),
197
191
  subkind: t.String(),
198
192
  scope: t.String(),
199
193
  label: t.String(),
@@ -248,7 +242,6 @@ export const memoryCrudHandler = createRouter()
248
242
  debug.log('path', 'memory:graph');
249
243
  return buildGraphView({
250
244
  projectIds: scopeForRole(conn, data.projectIds),
251
- kinds: data.kinds as GraphNodeKind[] | undefined,
252
245
  subkinds: data.subkinds,
253
246
  scopes: data.scopes as GraphScope[] | undefined,
254
247
  sources: data.sources as GraphSource[] | undefined,
@@ -273,7 +266,6 @@ export const memoryCrudHandler = createRouter()
273
266
  data: t.Object({
274
267
  query: t.String(),
275
268
  projectIds: t.Optional(t.Array(t.String())),
276
- kinds: t.Optional(t.Array(KIND)),
277
269
  subkinds: t.Optional(t.Array(t.String())),
278
270
  sources: t.Optional(t.Array(SOURCE)),
279
271
  limit: t.Optional(t.Number()),
@@ -303,7 +295,6 @@ export const memoryCrudHandler = createRouter()
303
295
  const result = retrieve({
304
296
  query: data.query,
305
297
  projectIds: scopeForRole(conn, data.projectIds),
306
- kinds: data.kinds as GraphNodeKind[] | undefined,
307
298
  subkinds: data.subkinds,
308
299
  sources: data.sources as GraphSource[] | undefined,
309
300
  limit: data.limit ?? 20,
@@ -330,8 +321,6 @@ export const memoryCrudHandler = createRouter()
330
321
  response: t.Object({
331
322
  nodes: t.Number(),
332
323
  edges: t.Number(),
333
- episodic: t.Number(),
334
- structural: t.Number(),
335
324
  vectors: t.Number(),
336
325
  byScope: t.Object({ session: t.Number(), project: t.Number(), global: t.Number() }),
337
326
  byProject: t.Array(t.Object({ projectId: t.Union([t.String(), t.Null()]), count: t.Number() })),
@@ -659,7 +648,7 @@ export const memoryCrudHandler = createRouter()
659
648
  .http('memory:save-config', {
660
649
  data: t.Object({
661
650
  enabled: t.Optional(t.Boolean()),
662
- recordCode: t.Optional(t.Boolean()),
651
+
663
652
  recordMemories: t.Optional(t.Boolean()),
664
653
  autoRecall: t.Optional(t.Boolean()),
665
654
  model: t.Optional(t.Union([MEMORY_MODEL, t.Null()]))
@@ -669,7 +658,6 @@ export const memoryCrudHandler = createRouter()
669
658
  debug.log('path', 'memory:save-config');
670
659
  return setMemoryConfig({
671
660
  ...(data.enabled !== undefined && { enabled: data.enabled }),
672
- ...(data.recordCode !== undefined && { recordCode: data.recordCode }),
673
661
  ...(data.recordMemories !== undefined && { recordMemories: data.recordMemories }),
674
662
  ...(data.autoRecall !== undefined && { autoRecall: data.autoRecall }),
675
663
  ...(data.model !== undefined && {
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Notes Router
3
+ *
4
+ * Notes live in collections, and a collection carries the scope: `project`
5
+ * (members of that project) or `global` (every signed-in user). Permissions are
6
+ * resolved through the collection on every route — a note id is never treated
7
+ * as a capability on its own.
8
+ *
9
+ * Writes broadcast `notes:changed` to whoever can see the collection, the same
10
+ * way worktrees do: a note another member just created is invisible until the
11
+ * next reload without it. The event carries ids only — a note holds up to
12
+ * 200 KB, so fanning the list out on every autosave would put megabytes on the
13
+ * socket per keystroke of a long note.
14
+ */
15
+
16
+ import { t } from 'elysia';
17
+ import { createRouter } from '$shared/utils/ws-server';
18
+ import type { WSConnection } from '$shared/utils/ws-server';
19
+ import type { NoteCollection } from '$shared/types/database/schema';
20
+ import { ws as wsServer } from '../../utils/ws';
21
+ import { requireProjectAccess } from '../access';
22
+ import {
23
+ noteQueries,
24
+ noteCollectionQueries,
25
+ noteImageQueries
26
+ } from '../../database/queries/note-queries';
27
+ import { canAccessCollection } from '../../notes/access';
28
+ import { removeCollectionFiles, removeNoteFiles, resolveNoteImagePath } from '../../notes/storage';
29
+ import { unlink } from 'node:fs/promises';
30
+
31
+ const scopeSchema = t.Union([t.Literal('project'), t.Literal('global')]);
32
+
33
+ const collectionSchema = t.Object({
34
+ id: t.String(),
35
+ name: t.String(),
36
+ scope: scopeSchema,
37
+ project_id: t.Union([t.String(), t.Null()]),
38
+ created_by: t.Union([t.String(), t.Null()]),
39
+ created_at: t.String(),
40
+ updated_at: t.String()
41
+ });
42
+
43
+ const noteSchema = t.Object({
44
+ id: t.String(),
45
+ collection_id: t.String(),
46
+ title: t.Union([t.String(), t.Null()]),
47
+ content: t.String(),
48
+ created_by: t.Union([t.String(), t.Null()]),
49
+ created_at: t.String(),
50
+ updated_at: t.String(),
51
+ images: t.Array(
52
+ t.Object({
53
+ id: t.String(),
54
+ note_id: t.String(),
55
+ file_name: t.String(),
56
+ mime_type: t.String(),
57
+ size: t.Number(),
58
+ storage_path: t.String(),
59
+ created_at: t.String()
60
+ })
61
+ )
62
+ });
63
+
64
+ /** Resolve a collection and refuse the call unless this connection may see it. */
65
+ function requireCollection(conn: WSConnection, collectionId: string): NoteCollection {
66
+ const collection = noteCollectionQueries.getById(collectionId);
67
+ // Same answer for "does not exist" and "not yours", so the id space cannot be
68
+ // probed for which collections are real.
69
+ if (!collection) throw new Error('Access denied');
70
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
71
+ throw new Error('Access denied');
72
+ }
73
+ return collection;
74
+ }
75
+
76
+ /** Resolve the collection a note belongs to, subject to the same check. */
77
+ function requireNoteCollection(conn: WSConnection, noteId: string): NoteCollection {
78
+ const collection = noteCollectionQueries.getForNote(noteId);
79
+ if (!collection) throw new Error('Access denied');
80
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
81
+ throw new Error('Access denied');
82
+ }
83
+ return collection;
84
+ }
85
+
86
+ /** Check the caller may write into `scope` before anything is created there. */
87
+ function requireScope(conn: WSConnection, scope: 'project' | 'global', projectId: string | null): void {
88
+ if (scope === 'project') {
89
+ if (!projectId) throw new Error('projectId is required for the project scope');
90
+ requireProjectAccess(conn, projectId);
91
+ return;
92
+ }
93
+ // Global is instance-wide; the only requirement is a signed-in connection,
94
+ // which getUserId asserts.
95
+ wsServer.getUserId(conn);
96
+ }
97
+
98
+ /**
99
+ * Tell everyone who can see this collection that its contents moved.
100
+ *
101
+ * A project collection reaches the project room; a global one reaches every
102
+ * connection, because that is exactly the set of people allowed to read it.
103
+ */
104
+ function broadcast(collection: NoteCollection): void {
105
+ const payload = {
106
+ collectionId: collection.id,
107
+ scope: collection.scope,
108
+ projectId: collection.project_id
109
+ };
110
+ if (collection.scope === 'project' && collection.project_id) {
111
+ wsServer.emit.project(collection.project_id, 'notes:changed', payload);
112
+ } else {
113
+ wsServer.emit.global('notes:changed', payload);
114
+ }
115
+ }
116
+
117
+ export const notesRouter = createRouter()
118
+ // ---- Collections ----
119
+
120
+ .http('notes:list', {
121
+ data: t.Object({
122
+ scope: scopeSchema,
123
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
124
+ }),
125
+ response: t.Object({
126
+ collections: t.Array(collectionSchema),
127
+ notes: t.Array(noteSchema)
128
+ })
129
+ }, async ({ data, conn }) => {
130
+ const projectId = data.projectId ?? null;
131
+ requireScope(conn, data.scope, projectId);
132
+ const collections = noteCollectionQueries.listByScope(data.scope, projectId);
133
+ return {
134
+ collections,
135
+ notes: noteQueries.listByCollections(collections.map((c) => c.id))
136
+ };
137
+ })
138
+
139
+ .http('notes:create-collection', {
140
+ data: t.Object({
141
+ name: t.String({ minLength: 1 }),
142
+ scope: scopeSchema,
143
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
144
+ }),
145
+ response: t.Object({ collection: collectionSchema })
146
+ }, async ({ data, conn }) => {
147
+ const projectId = data.scope === 'project' ? (data.projectId ?? null) : null;
148
+ requireScope(conn, data.scope, projectId);
149
+ const collection = noteCollectionQueries.create({
150
+ name: data.name,
151
+ scope: data.scope,
152
+ projectId,
153
+ createdBy: wsServer.getUserId(conn)
154
+ });
155
+ broadcast(collection);
156
+ return { collection };
157
+ })
158
+
159
+ .http('notes:rename-collection', {
160
+ data: t.Object({ id: t.String({ minLength: 1 }), name: t.String({ minLength: 1 }) }),
161
+ response: t.Object({ collection: t.Union([collectionSchema, t.Null()]) })
162
+ }, async ({ data, conn }) => {
163
+ const collection = requireCollection(conn, data.id);
164
+ const renamed = noteCollectionQueries.rename(collection.id, data.name);
165
+ if (renamed) broadcast(renamed);
166
+ return { collection: renamed };
167
+ })
168
+
169
+ .http('notes:delete-collection', {
170
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
171
+ response: t.Object({ ok: t.Boolean() })
172
+ }, async ({ data, conn }) => {
173
+ const collection = requireCollection(conn, data.id);
174
+ // Notes and image rows cascade with the collection; the files they point
175
+ // at do not, so the whole collection directory goes with them.
176
+ noteCollectionQueries.delete(collection.id);
177
+ await removeCollectionFiles(collection.id);
178
+ broadcast(collection);
179
+ return { ok: true };
180
+ })
181
+
182
+ // ---- Notes ----
183
+
184
+ .http('notes:get', {
185
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
186
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
187
+ }, async ({ data, conn }) => {
188
+ requireNoteCollection(conn, data.id);
189
+ return { note: noteQueries.getById(data.id) };
190
+ })
191
+
192
+ .http('notes:create', {
193
+ data: t.Object({
194
+ // Either an explicit collection, or a scope whose default collection is
195
+ // created on first use.
196
+ collectionId: t.Optional(t.String()),
197
+ scope: t.Optional(scopeSchema),
198
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
199
+ title: t.Optional(t.Union([t.String(), t.Null()])),
200
+ content: t.Optional(t.String())
201
+ }),
202
+ response: t.Object({ note: noteSchema })
203
+ }, async ({ data, conn }) => {
204
+ const userId = wsServer.getUserId(conn);
205
+ let collection: NoteCollection;
206
+ if (data.collectionId) {
207
+ collection = requireCollection(conn, data.collectionId);
208
+ } else {
209
+ const scope = data.scope ?? 'project';
210
+ const projectId = scope === 'project' ? (data.projectId ?? null) : null;
211
+ requireScope(conn, scope, projectId);
212
+ collection = noteCollectionQueries.ensureDefault(scope, projectId, userId);
213
+ }
214
+ const note = noteQueries.create({
215
+ collectionId: collection.id,
216
+ title: data.title ?? null,
217
+ content: data.content ?? '',
218
+ createdBy: userId
219
+ });
220
+ broadcast(collection);
221
+ return { note: { ...note, images: [] } };
222
+ })
223
+
224
+ .http('notes:update', {
225
+ data: t.Object({
226
+ id: t.String({ minLength: 1 }),
227
+ title: t.Optional(t.Union([t.String(), t.Null()])),
228
+ content: t.Optional(t.String()),
229
+ collectionId: t.Optional(t.String())
230
+ }),
231
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
232
+ }, async ({ data, conn }) => {
233
+ const from = requireNoteCollection(conn, data.id);
234
+ // Moving a note is only allowed between collections the caller can already
235
+ // see, otherwise a move would be a way to read or plant one they cannot.
236
+ const to = data.collectionId ? requireCollection(conn, data.collectionId) : from;
237
+ const updated = noteQueries.update(data.id, {
238
+ title: data.title,
239
+ content: data.content,
240
+ collectionId: data.collectionId
241
+ });
242
+ if (!updated) return { note: null };
243
+ broadcast(from);
244
+ if (to.id !== from.id) broadcast(to);
245
+ return { note: noteQueries.getById(data.id) };
246
+ })
247
+
248
+ .http('notes:delete', {
249
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
250
+ response: t.Object({ ok: t.Boolean() })
251
+ }, async ({ data, conn }) => {
252
+ const collection = requireNoteCollection(conn, data.id);
253
+ noteQueries.delete(data.id);
254
+ await removeNoteFiles(collection.id, data.id);
255
+ broadcast(collection);
256
+ return { ok: true };
257
+ })
258
+
259
+ .http('notes:delete-image', {
260
+ data: t.Object({ imageId: t.String({ minLength: 1 }) }),
261
+ response: t.Object({ ok: t.Boolean() })
262
+ }, async ({ data, conn }) => {
263
+ const img = noteImageQueries.getById(data.imageId);
264
+ if (!img) return { ok: true };
265
+ const collection = requireNoteCollection(conn, img.note_id);
266
+ const absolute = resolveNoteImagePath(img.storage_path);
267
+ if (absolute) await unlink(absolute).catch(() => {});
268
+ noteImageQueries.delete(data.imageId);
269
+ broadcast(collection);
270
+ return { ok: true };
271
+ })
272
+
273
+ // Collaborative broadcast events (Server → Client)
274
+ .emit('notes:changed', t.Object({
275
+ collectionId: t.String(),
276
+ scope: scopeSchema,
277
+ projectId: t.Union([t.String(), t.Null()])
278
+ }));
@@ -7,7 +7,7 @@
7
7
  * - profiles:available / project-default (non-admin)
8
8
  *
9
9
  * A Profile bundles references to existing artifacts (Skills, Commands,
10
- * Subagents, MCP Connectors) by slug plus an optional per-engine allow/deny
10
+ * Subagents, Integrations) by slug plus an optional per-engine allow/deny
11
11
  * overlay. Nothing is duplicated — see `backend/profiles`. Admin gating lives in
12
12
  * `backend/auth/permissions.ts`; the picker/default-read routes stay non-admin
13
13
  * (choosing a profile for a session is a run choice like the model).