@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
@@ -30,7 +30,7 @@
30
30
  */
31
31
 
32
32
  import { getDatabase } from '$backend/database';
33
- import { graphQueries } from '$backend/database/queries/graph-queries';
33
+ import { graphQueries, normalizePath } from '$backend/database/queries/graph-queries';
34
34
  import { debug } from '$shared/utils/logger';
35
35
  import { embedder, vectorCache } from './embedding';
36
36
  import { EMBEDDING_VERSION } from './embedding/paths';
@@ -134,8 +134,8 @@ interface FilterSql {
134
134
  * How a query should be read.
135
135
  *
136
136
  * The two channels are not equally good at the two kinds of question, and which
137
- * kind a query is can be told from its surface without a model. `getByPath` and
138
- * `backend/memory/relate.ts` are identifiers: BM25 matches them exactly, while a
137
+ * kind a query is can be told from its surface without a model. `setPaths` and
138
+ * `backend/memory/invalidate.ts` are identifiers: BM25 matches them exactly, while a
139
139
  * mean-pooled static embedding of a path fragment lands in the crowded middle of
140
140
  * the space and mostly adds noise. "kenapa kita pakai SQLite" is the reverse —
141
141
  * it shares no token with the English memory that answers it, and only the vector
@@ -180,9 +180,9 @@ function buildFilter(options: RetrievalOptions, alias: string): FilterSql {
180
180
  const params: unknown[] = [];
181
181
 
182
182
  // `reach = 'anywhere'` is what a memory learned elsewhere needs to be admitted
183
- // here. Structural nodes are excluded by construction — their reach is written
184
- // as `here` on insert — so another repository's file paths can never arrive,
185
- // which is the leak the blanket project filter was originally added to stop.
183
+ // here, and it defaults to `here` — so a claim about one repository cannot
184
+ // arrive in another's results unless a model judged that it travels. That is
185
+ // the leak the blanket project filter was originally added to stop.
186
186
  const travelling = options.crossProject ? ` OR ${alias}.reach = 'anywhere'` : '';
187
187
 
188
188
  if (options.projectIds !== undefined) {
@@ -212,10 +212,6 @@ function buildFilter(options: RetrievalOptions, alias: string): FilterSql {
212
212
  where.push(`${alias}.scope IN (${options.scopes.map(() => '?').join(',')})`);
213
213
  params.push(...options.scopes);
214
214
  }
215
- if (options.kinds?.length) {
216
- where.push(`${alias}.kind IN (${options.kinds.map(() => '?').join(',')})`);
217
- params.push(...options.kinds);
218
- }
219
215
  if (options.subkinds?.length) {
220
216
  where.push(`${alias}.subkind IN (${options.subkinds.map(() => '?').join(',')})`);
221
217
  params.push(...options.subkinds);
@@ -239,14 +235,12 @@ function buildFilter(options: RetrievalOptions, alias: string): FilterSql {
239
235
  * Graph expansion reaches nodes through EDGES rather than through a query, and
240
236
  * edges deliberately cross project boundaries (that is what lets a pattern
241
237
  * proven in one repository be reused in another). Without re-checking the filter
242
- * here, one hop from a shared dependency node would pull another project's files
243
- * — and, through them, another project's memories — into a block that is about to
244
- * be injected into this project's prompt. Traversal has to obey the same scope
245
- * rules the channels do.
238
+ * here, one hop would pull another project's memories into a block that is about
239
+ * to be injected into this project's prompt. Traversal has to obey the same
240
+ * scope rules the channels do.
246
241
  */
247
242
  function makeFilterPredicate(options: RetrievalOptions): (node: GraphNode) => boolean {
248
243
  const scopes = options.scopes?.length ? new Set(options.scopes) : null;
249
- const kinds = options.kinds?.length ? new Set(options.kinds) : null;
250
244
  const subkinds = options.subkinds?.length ? new Set(options.subkinds) : null;
251
245
  const sources = options.sources?.length ? new Set(options.sources) : null;
252
246
 
@@ -255,7 +249,7 @@ function makeFilterPredicate(options: RetrievalOptions): (node: GraphNode) => bo
255
249
  return (node: GraphNode): boolean => {
256
250
  // Same admission rule as `buildFilter`, so traversal cannot reach anything
257
251
  // the channels were not allowed to return.
258
- const travels = options.crossProject === true && node.reach === 'anywhere' && node.kind === 'episodic';
252
+ const travels = options.crossProject === true && node.reach === 'anywhere';
259
253
  if (projectIds) {
260
254
  if (node.projectId !== null && !projectIds.has(node.projectId) && !travels) return false;
261
255
  } else if (options.projectId !== undefined) {
@@ -267,7 +261,6 @@ function makeFilterPredicate(options: RetrievalOptions): (node: GraphNode) => bo
267
261
  }
268
262
  if (options.sessionId && node.scope === 'session' && node.sessionId !== options.sessionId) return false;
269
263
  if (scopes && !scopes.has(node.scope)) return false;
270
- if (kinds && !kinds.has(node.kind)) return false;
271
264
  if (subkinds && !subkinds.has(node.subkind)) return false;
272
265
  if (sources && !sources.has(node.source)) return false;
273
266
  if (!options.includeArchived && node.archivedAt) return false;
@@ -588,16 +581,24 @@ function currentOf(a: GraphNode, b: GraphNode): GraphNode {
588
581
  }
589
582
 
590
583
  /**
591
- * Structural nodes for the paths the caller says it is working in.
584
+ * The memories attached to the files the caller says it is working in.
585
+ *
586
+ * Looked up rather than searched: a path is an exact key, and running it through
587
+ * BM25 would be both slower and less precise.
592
588
  *
593
- * These are looked up rather than searched: a path is an exact key, and running
594
- * it through BM25 would be both slower and less precise.
589
+ * These used to be the FILE nodes for those paths, which then had to spend a hop
590
+ * of graph expansion crossing an `about` edge to reach the memories that are the
591
+ * actual answer — and each of those file nodes also occupied a slot in the
592
+ * result that a memory could have had. The seeds are the memories themselves
593
+ * now, at hop zero.
595
594
  */
596
595
  function anchorSeeds(options: RetrievalOptions, accept: (node: GraphNode) => boolean): GraphNode[] {
597
596
  const paths = options.anchorPaths;
598
597
  if (!paths?.length || options.projectId === undefined || options.projectId === null) return [];
599
598
  try {
600
- return graphQueries.getByPaths(options.projectId, paths.slice(0, 40)).filter(accept);
599
+ return graphQueries
600
+ .nodesForPaths(options.projectId, paths.slice(0, 40).map(normalizePath))
601
+ .filter(accept);
601
602
  } catch (error) {
602
603
  debug.warn('memory', 'Anchor seeding failed', error);
603
604
  return [];
@@ -15,6 +15,7 @@ import { beforeEach, describe, expect, it, mock } from 'bun:test';
15
15
  import { Database } from 'bun:sqlite';
16
16
  import type { DatabaseConnection } from '$shared/types/database/connection';
17
17
  import * as migration066 from '$backend/database/migrations/066_create_memory_graph';
18
+ import * as migration076 from '$backend/database/migrations/076_remove_memory_code_graph';
18
19
 
19
20
  let db: Database;
20
21
 
@@ -41,7 +42,6 @@ const PROJECT = 'project-a';
41
42
 
42
43
  function memory(label: string, overrides: Record<string, unknown> = {}) {
43
44
  return graphQueries.upsert({
44
- kind: 'episodic',
45
45
  subkind: 'decision',
46
46
  projectId: PROJECT,
47
47
  label,
@@ -49,14 +49,9 @@ function memory(label: string, overrides: Record<string, unknown> = {}) {
49
49
  } as Parameters<typeof graphQueries.upsert>[0]);
50
50
  }
51
51
 
52
- function file(path: string) {
53
- return graphQueries.upsert({
54
- kind: 'structural',
55
- subkind: 'file',
56
- projectId: PROJECT,
57
- label: path,
58
- path
59
- });
52
+ /** Attach a memory to the file it claims something about. */
53
+ function about(node: { id: string }, ...paths: string[]): void {
54
+ graphQueries.setPaths(node.id, paths);
60
55
  }
61
56
 
62
57
  /** Backdate a node so age-gated behaviour can be exercised without waiting. */
@@ -72,6 +67,7 @@ beforeEach(() => {
72
67
  db = new Database(':memory:');
73
68
  db.exec('PRAGMA foreign_keys = ON');
74
69
  migration066.up(db as unknown as DatabaseConnection);
70
+ migration076.up(db as unknown as DatabaseConnection);
75
71
  // The queue's orphan sweep joins against sessions; a stub is enough here.
76
72
  db.exec(`CREATE TABLE IF NOT EXISTS chat_sessions (id TEXT PRIMARY KEY)`);
77
73
  });
@@ -186,7 +182,7 @@ describe('supersession', () => {
186
182
  graphQueries.supersede(old.id, current.id);
187
183
 
188
184
  const stats = graphQueries.stats();
189
- expect(stats.episodic).toBe(1);
185
+ expect(stats.nodes).toBe(1);
190
186
  expect(stats.superseded).toBe(1);
191
187
  expect(graphQueries.list({ projectId: PROJECT }).map(n => n.id)).not.toContain(old.id);
192
188
  });
@@ -274,7 +270,6 @@ describe('canonical entities', () => {
274
270
 
275
271
  describe('structural invalidation', () => {
276
272
  it('ages an observation about changed code but not the decision behind it', () => {
277
- const target = file('backend/chat/stream-manager.ts');
278
273
  const observation = memory('Stream manager captures the snapshot in its finally block', {
279
274
  subkind: 'observation',
280
275
  confidence: 0.9
@@ -289,10 +284,10 @@ describe('structural invalidation', () => {
289
284
  });
290
285
 
291
286
  for (const node of [observation, decision, preference]) {
292
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
287
+ about(node, 'backend/chat/stream-manager.ts');
293
288
  }
294
289
 
295
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/chat/stream-manager.ts'] });
290
+ invalidateForChanges({ changedPaths: ['backend/chat/stream-manager.ts'] });
296
291
 
297
292
  expect(graphQueries.getById(observation.id)!.confidence).toBeLessThan(0.9);
298
293
  expect(graphQueries.getById(observation.id)!.staleAt).not.toBeNull();
@@ -303,7 +298,6 @@ describe('structural invalidation', () => {
303
298
  });
304
299
 
305
300
  it('never ages a memory a person wrote or pinned', () => {
306
- const target = file('backend/a.ts');
307
301
  const authored = memory('Hand-written note about a.ts', {
308
302
  subkind: 'observation',
309
303
  confidence: 0.9,
@@ -314,45 +308,51 @@ describe('structural invalidation', () => {
314
308
  confidence: 0.9,
315
309
  pinned: true
316
310
  });
317
- for (const node of [authored, pinned]) {
318
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
319
- }
311
+ for (const node of [authored, pinned]) about(node, 'backend/a.ts');
320
312
 
321
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/a.ts'] });
313
+ invalidateForChanges({ changedPaths: ['backend/a.ts'] });
322
314
 
323
315
  expect(graphQueries.getById(authored.id)!.confidence).toBe(0.9);
324
316
  expect(graphQueries.getById(pinned.id)!.confidence).toBe(0.9);
325
317
  });
326
318
 
327
- it('retires the nodes of a file that no longer exists', () => {
328
- // Otherwise BM25 keeps offering a path that is gone, which sends an agent to
329
- // read a file that was deleted — a specific, repeatable waste of a turn.
330
- file('backend/gone.ts');
331
- graphQueries.upsert({
332
- kind: 'structural',
333
- subkind: 'symbol',
334
- projectId: PROJECT,
335
- label: 'goneHelper',
336
- path: 'backend/gone.ts',
337
- symbol: 'goneHelper'
319
+ it('ages a memory about a file that no longer exists', () => {
320
+ // Deletion is the strongest form of "the code moved underneath this", so it
321
+ // runs through the same per-subkind rates rather than a category of its own.
322
+ // The attribution itself is kept: a memory about a since-deleted module is
323
+ // still the only record of what that module taught.
324
+ const note = memory('gone.ts owned the retry loop', {
325
+ subkind: 'observation',
326
+ confidence: 0.9
338
327
  });
328
+ about(note, 'backend/gone.ts');
339
329
 
340
330
  const result = invalidateForChanges({
341
- projectId: PROJECT,
342
331
  changedPaths: [],
343
332
  deletedPaths: ['backend/gone.ts']
344
333
  });
345
334
 
346
- expect(result.archived).toBe(2);
347
- const hits = retrieve({ query: 'goneHelper', projectId: PROJECT, expandHops: 0 }).hits;
348
- expect(hits).toHaveLength(0);
335
+ expect(result.decayed).toBe(1);
336
+ expect(graphQueries.getById(note.id)!.staleAt).not.toBeNull();
337
+ expect(graphQueries.pathsOf(note.id)).toEqual(['backend/gone.ts']);
338
+ });
339
+
340
+ it('matches a changed path however the caller spelled it', () => {
341
+ // The disk diff, a model and Windows all spell the same file differently.
342
+ const note = memory('The worker pool is drained on exit', {
343
+ subkind: 'observation',
344
+ confidence: 0.9
345
+ });
346
+ about(note, 'backend/pool.ts');
347
+
348
+ invalidateForChanges({ changedPaths: ['./backend/pool.ts'] });
349
+ expect(graphQueries.getById(note.id)!.staleAt).not.toBeNull();
349
350
  });
350
351
 
351
352
  it('clears staleness when the memory is re-observed', () => {
352
- const target = file('backend/b.ts');
353
353
  const node = memory('b.ts exports a queue', { subkind: 'observation', confidence: 0.9 });
354
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
355
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['backend/b.ts'] });
354
+ about(node, 'backend/b.ts');
355
+ invalidateForChanges({ changedPaths: ['backend/b.ts'] });
356
356
  expect(graphQueries.getById(node.id)!.staleAt).not.toBeNull();
357
357
 
358
358
  // Re-extracting the same claim is the evidence that it survived the change.
@@ -419,33 +419,25 @@ describe('forgetting and deleting', () => {
419
419
  * not, which is why forgotten memories kept reappearing.
420
420
  */
421
421
  it('keeps a forgotten memory out of a neighbour walk', () => {
422
- const target = file('backend/auth.ts');
423
422
  const live = memory('Auth uses short-lived tokens');
424
423
  const forgotten = memory('Auth used to use cookies');
425
- for (const node of [live, forgotten]) {
426
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
427
- }
424
+ graphQueries.link({ srcId: live.id, dstId: forgotten.id, rel: 'supersedes' });
428
425
 
429
426
  graphQueries.archive(forgotten.id);
430
427
 
431
- const ids = graphQueries.neighbours(target.id, 1).map(n => n.node.id);
432
- expect(ids).toContain(live.id);
433
- expect(ids).not.toContain(forgotten.id);
428
+ expect(graphQueries.neighbours(live.id, 1).map(n => n.node.id)).not.toContain(forgotten.id);
434
429
  // The edge itself is untouched: this is a display rule, not a deletion.
435
430
  expect(graphQueries.edgesOf(forgotten.id)).toHaveLength(1);
436
431
  });
437
432
 
438
433
  it('keeps a superseded memory out of a neighbour walk', () => {
439
- const target = file('backend/db.ts');
440
434
  const current = memory('Storage is SQLite');
441
435
  const old = memory('Storage is Postgres');
442
- for (const node of [current, old]) {
443
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
444
- }
436
+ const related = memory('Migrations run at startup');
437
+ graphQueries.link({ srcId: related.id, dstId: old.id, rel: 'relates_to' });
445
438
  graphQueries.supersede(old.id, current.id);
446
439
 
447
- const ids = graphQueries.neighbours(target.id, 1).map(n => n.node.id);
448
- expect(ids).not.toContain(old.id);
440
+ expect(graphQueries.neighbours(related.id, 1).map(n => n.node.id)).not.toContain(old.id);
449
441
  });
450
442
 
451
443
  it('lists both the archived and the superseded as forgotten', () => {
@@ -463,13 +455,22 @@ describe('forgetting and deleting', () => {
463
455
 
464
456
  it('hard-deletes selected nodes and their edges', () => {
465
457
  const node = memory('To be deleted');
466
- const target = file('backend/x.ts');
467
- graphQueries.link({ srcId: node.id, dstId: target.id, rel: 'about' });
458
+ const other = memory('Still here');
459
+ graphQueries.link({ srcId: node.id, dstId: other.id, rel: 'relates_to' });
468
460
  graphQueries.archive(node.id);
469
461
 
470
462
  expect(graphQueries.deleteNodes([node.id])).toBe(1);
471
463
  expect(graphQueries.getById(node.id)).toBeNull();
472
- expect(graphQueries.edgesOf(target.id)).toHaveLength(0);
464
+ expect(graphQueries.edgesOf(other.id)).toHaveLength(0);
465
+ });
466
+
467
+ it('takes a deleted memory\'s path attributions with it', () => {
468
+ const node = memory('About a file');
469
+ about(node, 'src/thing.ts');
470
+ graphQueries.archive(node.id);
471
+ graphQueries.deleteNodes([node.id]);
472
+
473
+ expect(graphQueries.memoriesForPaths(['src/thing.ts'])).toHaveLength(0);
473
474
  });
474
475
 
475
476
  it('does not orphan a node whose replacement was deleted', () => {
@@ -488,7 +489,6 @@ describe('purge', () => {
488
489
  it('empties one project and leaves the others alone', () => {
489
490
  const mine = memory('Belongs to project A');
490
491
  const theirs = graphQueries.upsert({
491
- kind: 'episodic',
492
492
  subkind: 'decision',
493
493
  projectId: 'project-b',
494
494
  label: 'Belongs to project B'
@@ -504,7 +504,6 @@ describe('purge', () => {
504
504
  // Preferences and conventions were never that repository's to hold, so losing
505
505
  // them because one project was cleaned would be a surprise.
506
506
  const global = graphQueries.upsert({
507
- kind: 'episodic',
508
507
  subkind: 'preference',
509
508
  scope: 'global',
510
509
  projectId: null,
@@ -519,7 +518,6 @@ describe('purge', () => {
519
518
  it('empties everything when no project is named', () => {
520
519
  memory('Project memory');
521
520
  graphQueries.upsert({
522
- kind: 'episodic',
523
521
  subkind: 'preference',
524
522
  scope: 'global',
525
523
  projectId: null,
@@ -554,12 +552,12 @@ describe('who wrote it', () => {
554
552
  expect(edited!.label).toBe('The cache is invalidated on read');
555
553
  });
556
554
 
557
- it('leaves a hand-written memory untouched by structural decay', () => {
558
- const target = file('src/cache.ts');
555
+ it('leaves a hand-written memory untouched by staleness decay', () => {
559
556
  const mine = memory('The cache is invalidated on write', { subkind: 'observation', source: 'user' });
560
- graphQueries.link({ srcId: mine.id, dstId: target.id, rel: 'about' });
557
+ about(mine, 'src/cache.ts');
561
558
 
562
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/cache.ts'] });
559
+ invalidateForChanges({ changedPaths: ['src/cache.ts'] });
560
+ invalidateForChanges({ changedPaths: ['src/cache.ts'] });
563
561
 
564
562
  const after = graphQueries.getById(mine.id)!;
565
563
  expect(after.staleAt).toBeNull();
@@ -573,15 +571,14 @@ describe('structural decay', () => {
573
571
  // confidence by 0.82 ten times over — 0.14, below the injection floor — so an
574
572
  // ordinary afternoon silently destroyed everything known about whatever was
575
573
  // being worked on.
576
- const target = file('src/stream.ts');
577
574
  const note = memory('The stream captures its snapshot in a finally block', {
578
575
  subkind: 'observation',
579
576
  confidence: 0.9
580
577
  });
581
- graphQueries.link({ srcId: note.id, dstId: target.id, rel: 'about' });
578
+ about(note, 'src/stream.ts');
582
579
 
583
580
  for (let turn = 0; turn < 10; turn++) {
584
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
581
+ invalidateForChanges({ changedPaths: ['src/stream.ts'] });
585
582
  }
586
583
 
587
584
  const after = graphQueries.getById(note.id)!;
@@ -591,13 +588,12 @@ describe('structural decay', () => {
591
588
  });
592
589
 
593
590
  it('ages it again once the cool-off has passed', () => {
594
- const target = file('src/stream.ts');
595
591
  const note = memory('An observation about the stream', { subkind: 'observation', confidence: 0.9 });
596
- graphQueries.link({ srcId: note.id, dstId: target.id, rel: 'about' });
592
+ about(note, 'src/stream.ts');
597
593
 
598
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
594
+ invalidateForChanges({ changedPaths: ['src/stream.ts'] });
599
595
  db.prepare(`UPDATE graph_nodes SET stale_at = datetime('now', '-2 days') WHERE id = ?`).run(note.id);
600
- invalidateForChanges({ projectId: PROJECT, changedPaths: ['src/stream.ts'] });
596
+ invalidateForChanges({ changedPaths: ['src/stream.ts'] });
601
597
 
602
598
  expect(graphQueries.getById(note.id)!.confidence).toBeCloseTo(0.9 * 0.82 * 0.82, 5);
603
599
  });
@@ -641,53 +637,3 @@ describe('restoring', () => {
641
637
  expect(graphQueries.getById(b.id)!.archivedAt).toBeNull();
642
638
  });
643
639
  });
644
-
645
- describe('bounding the structural half', () => {
646
- it('removes symbols nothing refers to and nothing has touched', () => {
647
- // The structural half is what actually grows without bound — a node per
648
- // changed file, per directory and up to twenty-five per file's symbols, every
649
- // turn — and none of the episodic retention queries look at it at all.
650
- const symbol = graphQueries.upsert({
651
- kind: 'structural',
652
- subkind: 'symbol',
653
- projectId: PROJECT,
654
- label: 'forgottenHelper',
655
- path: 'src/old.ts',
656
- symbol: 'forgottenHelper'
657
- });
658
- backdate(symbol.id, 200);
659
-
660
- expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(1);
661
- expect(graphQueries.getById(symbol.id)).toBeNull();
662
- });
663
-
664
- it('spares a symbol a memory is about', () => {
665
- // Deleting it would sever the `about` edge, which is the join both halves of
666
- // the graph exist for.
667
- const symbol = graphQueries.upsert({
668
- kind: 'structural',
669
- subkind: 'symbol',
670
- projectId: PROJECT,
671
- label: 'loadBearing',
672
- path: 'src/core.ts',
673
- symbol: 'loadBearing'
674
- });
675
- const note = memory('loadBearing must stay synchronous');
676
- graphQueries.link({ srcId: note.id, dstId: symbol.id, rel: 'about' });
677
- backdate(symbol.id, 200);
678
-
679
- expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(0);
680
- expect(graphQueries.getById(symbol.id)).not.toBeNull();
681
- });
682
-
683
- it('spares file nodes, however old', () => {
684
- // A file node is what a path lookup resolves to, and `invalidate.ts` already
685
- // retires files the moment the disk says they are gone — better evidence
686
- // than age.
687
- const node = file('src/rarely-touched.ts');
688
- backdate(node.id, 400);
689
-
690
- expect(graphQueries.pruneStructural({ maxAgeDays: 120, limit: 100 })).toBe(0);
691
- expect(graphQueries.getById(node.id)).not.toBeNull();
692
- });
693
- });
@@ -98,7 +98,6 @@ export function gatherRelatedMemories(options: {
98
98
  query,
99
99
  projectId: options.projectId,
100
100
  sessionId: options.sessionId ?? undefined,
101
- kinds: ['episodic'],
102
101
  limit: MAX_RELATED_SHOWN,
103
102
  expandHops: 0
104
103
  });
@@ -37,7 +37,6 @@
37
37
  import { graphQueries, graphLayoutQueries, type GraphBinGrid } from '$backend/database/queries/graph-queries';
38
38
  import type {
39
39
  GraphNode,
40
- GraphNodeKind,
41
40
  GraphRegion,
42
41
  GraphScope,
43
42
  GraphSource,
@@ -69,7 +68,6 @@ export interface GraphViewFilter {
69
68
  projectId?: string | null;
70
69
  /** The multi-select's answer: absent = every project, empty = global only. */
71
70
  projectIds?: string[];
72
- kinds?: GraphNodeKind[];
73
71
  /** Narrow to particular subkinds — decisions only, failures only, and so on. */
74
72
  subkinds?: string[];
75
73
  scopes?: GraphScope[];
@@ -340,7 +338,6 @@ function toViewNode(
340
338
  ): GraphViewNode {
341
339
  return {
342
340
  id: node.id,
343
- kind: node.kind,
344
341
  subkind: node.subkind,
345
342
  scope: node.scope,
346
343
  label: node.label,
@@ -458,13 +455,19 @@ function truncate(label: string): string {
458
455
  return label.length > BIN_LABEL_MAX ? `${label.slice(0, BIN_LABEL_MAX - 1)}…` : label;
459
456
  }
460
457
 
461
- /** A node plus the nodes it reaches — what the inspector renders. */
458
+ /**
459
+ * A node plus the nodes it reaches — what the inspector renders.
460
+ *
461
+ * The paths are attached HERE and nowhere else on the read path. They are a
462
+ * per-node query, and a listing draws thousands of nodes at a time; the
463
+ * inspector draws one.
464
+ */
462
465
  export function buildNodeDetail(nodeId: string, hops = 1) {
463
466
  const node = graphQueries.getById(nodeId);
464
467
  if (!node) return null;
465
468
 
466
469
  return {
467
- node,
470
+ node: { ...node, relatedPaths: graphQueries.pathsOf(nodeId) },
468
471
  neighbours: graphQueries.neighbours(nodeId, hops).map(n => ({ node: n.node, hops: n.hops }))
469
472
  };
470
473
  }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Tests for the note collection access rule.
3
+ *
4
+ * This one function decides who can read notes and who can read the image bytes
5
+ * behind them. Both answers have to stay in step, and the global case has to
6
+ * stay deliberate: it grants every signed-in account, so a regression that
7
+ * quietly widened the project case into it would be invisible in the UI.
8
+ */
9
+
10
+ import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
11
+ import { randomUUID } from 'node:crypto';
12
+
13
+ import { initializeDatabase, closeDatabase } from '../database';
14
+ import { projectQueries } from '../database/queries/project-queries';
15
+ import { noteCollectionQueries } from '../database/queries/note-queries';
16
+ import { canAccessCollection } from './access';
17
+ import type { NoteCollection } from '$shared/types/database/schema';
18
+
19
+ let memberId: string;
20
+ let outsiderId: string;
21
+ let projectId: string;
22
+
23
+ beforeAll(async () => {
24
+ await initializeDatabase();
25
+ memberId = randomUUID();
26
+ outsiderId = randomUUID();
27
+ projectId = projectQueries.create({
28
+ name: 'notes-access-test',
29
+ // `projects.path` is unique, so a fixed path collides with whatever an
30
+ // earlier run left behind in the test data dir.
31
+ path: `/tmp/notes-access-test-${randomUUID()}`,
32
+ created_at: new Date().toISOString(),
33
+ last_opened_at: new Date().toISOString()
34
+ }).id;
35
+ projectQueries.addUserProject(memberId, projectId);
36
+ });
37
+
38
+ afterAll(() => {
39
+ projectQueries.deleteProject(projectId);
40
+ closeDatabase();
41
+ });
42
+
43
+ describe('canAccessCollection — project scope', () => {
44
+ it('admits a member of the project', () => {
45
+ const collection = noteCollectionQueries.create({ name: 'P', scope: 'project', projectId });
46
+ expect(canAccessCollection(memberId, collection)).toBe(true);
47
+ noteCollectionQueries.delete(collection.id);
48
+ });
49
+
50
+ it('refuses someone who is not a member', () => {
51
+ const collection = noteCollectionQueries.create({ name: 'P', scope: 'project', projectId });
52
+ expect(canAccessCollection(outsiderId, collection)).toBe(false);
53
+ noteCollectionQueries.delete(collection.id);
54
+ });
55
+
56
+ it('refuses a project collection with no project rather than admitting everyone', () => {
57
+ // The table's CHECK makes this unreachable through the queries, but a row
58
+ // in this shape must fail closed rather than fall through to the global
59
+ // branch and become readable by the whole instance.
60
+ const malformed = {
61
+ id: 'x',
62
+ name: 'Malformed',
63
+ scope: 'project',
64
+ project_id: null,
65
+ created_by: null,
66
+ created_at: '',
67
+ updated_at: ''
68
+ } as NoteCollection;
69
+ expect(canAccessCollection(memberId, malformed)).toBe(false);
70
+ });
71
+ });
72
+
73
+ describe('canAccessCollection — global scope', () => {
74
+ it('admits any signed-in user, including one in no project at all', () => {
75
+ // Deliberate: a global collection has no per-note ACL, so everything in it
76
+ // is readable by every account that can sign in.
77
+ const collection = noteCollectionQueries.create({ name: 'G', scope: 'global' });
78
+ expect(canAccessCollection(memberId, collection)).toBe(true);
79
+ expect(canAccessCollection(outsiderId, collection)).toBe(true);
80
+ noteCollectionQueries.delete(collection.id);
81
+ });
82
+ });
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Who may read and write a note collection.
3
+ *
4
+ * The rule lives here rather than in each route because three call sites need
5
+ * to agree on it — the WebSocket handlers, the image upload, and the image
6
+ * download — and a note whose bytes are reachable through a rule its metadata
7
+ * is not would be worse than no rule at all.
8
+ */
9
+
10
+ import type { NoteCollection } from '$shared/types/database/schema';
11
+ import { projectQueries } from '../database/queries/project-queries';
12
+
13
+ /**
14
+ * Whether `userId` may see and edit everything in `collection`.
15
+ *
16
+ * - `project` — members of that project, the same check the rest of the
17
+ * project-scoped API uses.
18
+ * - `global` — every signed-in user on this instance. Global collections are
19
+ * deliberately instance-wide: there is no per-note ACL, so anything put in
20
+ * one is readable by every account that can sign in, including members of
21
+ * unrelated projects.
22
+ */
23
+ export function canAccessCollection(userId: string, collection: NoteCollection): boolean {
24
+ if (collection.scope === 'global') return true;
25
+ if (!collection.project_id) return false;
26
+ return projectQueries.userHasProject(userId, collection.project_id);
27
+ }