@myrialabs/clopen 0.4.26 → 0.4.27

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 (93) hide show
  1. package/backend/auth/permissions.ts +21 -0
  2. package/backend/bootstrap.ts +18 -1
  3. package/backend/chat/engine-handoff.test.ts +229 -0
  4. package/backend/chat/engine-handoff.ts +439 -0
  5. package/backend/chat/stream-manager.ts +200 -16
  6. package/backend/database/migrations/066_create_memory_graph.ts +369 -0
  7. package/backend/database/migrations/index.ts +7 -0
  8. package/backend/database/queries/audit-log-queries.test.ts +10 -1
  9. package/backend/database/queries/graph-queries.ts +1764 -0
  10. package/backend/database/queries/index.ts +2 -0
  11. package/backend/database/queries/memory-queue-queries.ts +381 -0
  12. package/backend/database/queries/snapshot-queries.ts +20 -0
  13. package/backend/engine/README.md +45 -2
  14. package/backend/engine/adapters/copilot/stream.ts +37 -1
  15. package/backend/engine/adapters/pi/models.ts +19 -7
  16. package/backend/engine/adapters/pi/stream.ts +2 -1
  17. package/backend/engine/docs/adapter-contract.md +25 -8
  18. package/backend/engine/docs/adding-an-engine.md +40 -4
  19. package/backend/engine/docs/frontend-and-chat.md +66 -1
  20. package/backend/engine/docs/lessons-learned.md +165 -6
  21. package/backend/engine/docs/quick-reference.md +10 -0
  22. package/backend/engine/docs/stack.md +10 -0
  23. package/backend/engine/docs/websocket-routes.md +15 -1
  24. package/backend/engine/engine-setup.ts +1 -1
  25. package/backend/engine/index.test.ts +186 -0
  26. package/backend/engine/index.ts +117 -71
  27. package/backend/engine/install-recipes.test.ts +105 -0
  28. package/backend/engine/install-recipes.ts +4 -1
  29. package/backend/index.ts +9 -0
  30. package/backend/mcp/internal/config.ts +6 -0
  31. package/backend/mcp/internal/servers/index.ts +2 -0
  32. package/backend/mcp/internal/servers/memory-graph/description.ts +33 -0
  33. package/backend/mcp/internal/servers/memory-graph/format.ts +45 -0
  34. package/backend/mcp/internal/servers/memory-graph/index.ts +52 -0
  35. package/backend/mcp/internal/servers/memory-graph/runner.ts +342 -0
  36. package/backend/mcp/internal/servers/memory-graph/schema.ts +140 -0
  37. package/backend/memory/README.md +432 -0
  38. package/backend/memory/bootstrap.ts +101 -0
  39. package/backend/memory/compose.test.ts +198 -0
  40. package/backend/memory/compose.ts +343 -0
  41. package/backend/memory/config.ts +100 -0
  42. package/backend/memory/consolidate.ts +280 -0
  43. package/backend/memory/context.test.ts +321 -0
  44. package/backend/memory/context.ts +451 -0
  45. package/backend/memory/embedding/embedder.test.ts +141 -0
  46. package/backend/memory/embedding/embedder.ts +269 -0
  47. package/backend/memory/embedding/index.ts +17 -0
  48. package/backend/memory/embedding/install.ts +254 -0
  49. package/backend/memory/embedding/paths.ts +101 -0
  50. package/backend/memory/embedding/vector-cache.ts +270 -0
  51. package/backend/memory/extract/episodic.ts +725 -0
  52. package/backend/memory/extract/index.ts +133 -0
  53. package/backend/memory/extract/languages.ts +176 -0
  54. package/backend/memory/extract/scheduler.test.ts +352 -0
  55. package/backend/memory/extract/scheduler.ts +406 -0
  56. package/backend/memory/extract/structural.test.ts +215 -0
  57. package/backend/memory/extract/structural.ts +364 -0
  58. package/backend/memory/index.ts +37 -0
  59. package/backend/memory/indexer.ts +150 -0
  60. package/backend/memory/invalidate.ts +134 -0
  61. package/backend/memory/judge.ts +285 -0
  62. package/backend/memory/maintenance.ts +132 -0
  63. package/backend/memory/model.ts +91 -0
  64. package/backend/memory/notify.ts +102 -0
  65. package/backend/memory/readiness.ts +74 -0
  66. package/backend/memory/redact.test.ts +101 -0
  67. package/backend/memory/redact.ts +133 -0
  68. package/backend/memory/retention.ts +139 -0
  69. package/backend/memory/retrieval.eval.test.ts +301 -0
  70. package/backend/memory/retrieval.test.ts +1023 -0
  71. package/backend/memory/retrieval.ts +707 -0
  72. package/backend/memory/revise.test.ts +693 -0
  73. package/backend/memory/revise.ts +400 -0
  74. package/backend/memory/time.ts +31 -0
  75. package/backend/memory/view.ts +164 -0
  76. package/backend/shipped-runtime-imports.test.ts +228 -0
  77. package/backend/ws/index.ts +5 -1
  78. package/backend/ws/memory/crud.ts +631 -0
  79. package/backend/ws/memory/index.ts +41 -0
  80. package/backend/ws/sessions/crud.ts +10 -0
  81. package/backend/ws/snapshot/restore.ts +38 -4
  82. package/dist/assets/graph-layout.worker-CRFqN7ZQ.js +1 -0
  83. package/dist/assets/{index-B6QGUN03.js → index-BCv5HlPk.js} +1 -1
  84. package/dist/assets/{index-DYa-GDsb.js → index-BTGcf_Vy.js} +1 -1
  85. package/dist/assets/main-BrqMMMRX.css +1 -0
  86. package/dist/assets/{main-Dznkfxsd.js → main-CgmAFpU3.js} +835 -426
  87. package/dist/index.html +2 -2
  88. package/package.json +8 -2
  89. package/shared/types/database/connection.ts +9 -0
  90. package/shared/types/memory.ts +519 -0
  91. package/shared/utils/logger.ts +1 -0
  92. package/dist/assets/main-Dh-MTGNR.css +0 -1
  93. package/shared/utils/anonymous-user.ts +0 -168
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Shipped-runtime import integrity
3
+ *
4
+ * Clopen publishes its backend as SOURCE (see package.json "files": bin,
5
+ * backend, shared, scripts/start.ts) and Bun executes it straight off disk on
6
+ * the user's machine. That machine has only what `dependencies` pulls in —
7
+ * `devDependencies` (every engine SDK, plus the build/lint toolchain) are never
8
+ * installed there.
9
+ *
10
+ * So a runtime import of a devDependency resolves fine in this repo and passes
11
+ * check / lint / test / build / dev, yet crashes every end user at boot:
12
+ *
13
+ * error: Cannot find module '@earendil-works/pi-ai' from '…/adapters/pi/stream.ts'
14
+ *
15
+ * The failure has no local signal, which is what makes it recur. This test
16
+ * supplies that signal by walking the module graph exactly as the published
17
+ * package would be resolved, and asserting every runtime specifier is reachable
18
+ * there. It covers three ways the shipped tree can break:
19
+ *
20
+ * 1. importing a devDependency (engine SDKs must go through `loadEngineSdk`,
21
+ * which resolves them from the managed stack dir at runtime),
22
+ * 2. importing a package that is not declared in `dependencies` at all,
23
+ * 3. importing a file that "files" does not ship (e.g. reaching into
24
+ * `frontend/`, or a path that only exists in the repo).
25
+ *
26
+ * Imports are extracted with `Bun.Transpiler.scanImports`, the same transpiler
27
+ * that runs the code — type-only imports (`import type`, inline `type`
28
+ * specifiers, `typeof import(...)`) are erased by both, so the test sees
29
+ * precisely the specifiers the runtime will try to resolve. That also covers
30
+ * `await import(...)`, which the ESLint guard in eslint.config.js cannot see.
31
+ *
32
+ * Scope is deliberately our own shipped source, not the whole dependency tree.
33
+ * Third-party packages legitimately ship unresolvable specifiers behind guards —
34
+ * ssh2 does `try { require('cpu-features') } catch {}`, cosmiconfig lazily
35
+ * requires `typescript` only when a `.ts` config file exists — which the runtime
36
+ * handles and no static walk can distinguish from a real break.
37
+ */
38
+
39
+ import { describe, expect, test } from 'bun:test';
40
+ import { readFileSync, existsSync, statSync, readdirSync } from 'node:fs';
41
+ import { join, dirname, relative, resolve, sep } from 'node:path';
42
+ import { builtinModules } from 'node:module';
43
+
44
+ const REPO_ROOT = resolve(import.meta.dir, '..');
45
+
46
+ const pkg = JSON.parse(readFileSync(join(REPO_ROOT, 'package.json'), 'utf8')) as {
47
+ files: string[];
48
+ dependencies?: Record<string, string>;
49
+ devDependencies?: Record<string, string>;
50
+ };
51
+
52
+ const dependencies = new Set(Object.keys(pkg.dependencies ?? {}));
53
+ const devDependencies = new Set(Object.keys(pkg.devDependencies ?? {}));
54
+ const builtins = new Set(builtinModules);
55
+
56
+ /**
57
+ * "files" entries that are build output or config rather than source we can
58
+ * meaningfully walk. `dist` is the vite bundle — self-contained, and absent
59
+ * until `bun run build`.
60
+ */
61
+ const NOT_SOURCE = new Set(['dist', 'tsconfig.json', 'bunfig.toml', '.env.example']);
62
+
63
+ /** tsconfig path aliases, restricted to the ones shipped code may use. */
64
+ const ALIASES: Record<string, string> = {
65
+ $backend: 'backend',
66
+ $shared: 'shared',
67
+ $frontend: 'frontend',
68
+ };
69
+
70
+ const SOURCE_EXTENSIONS = ['.ts', '.js'];
71
+ const RESOLVE_SUFFIXES = ['', '.ts', '.js', '.json', '/index.ts', '/index.js'];
72
+
73
+ function walk(dir: string, out: string[]): void {
74
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
75
+ const path = join(dir, entry.name);
76
+ if (entry.isDirectory()) walk(path, out);
77
+ else if (entry.isFile()) out.push(path);
78
+ }
79
+ }
80
+
81
+ /** Every file the published tarball contains, as repo-relative paths. */
82
+ function shippedFiles(): Set<string> {
83
+ const files: string[] = [];
84
+ for (const entry of pkg.files) {
85
+ if (NOT_SOURCE.has(entry)) continue;
86
+ const path = join(REPO_ROOT, entry);
87
+ if (!existsSync(path)) continue;
88
+ if (statSync(path).isDirectory()) walk(path, files);
89
+ else files.push(path);
90
+ }
91
+ return new Set(files.map(f => relative(REPO_ROOT, f)));
92
+ }
93
+
94
+ const shipped = shippedFiles();
95
+
96
+ /**
97
+ * Shipped source files that actually execute for a user. Test files are shipped
98
+ * but never run there, and they legitimately reach for devDependencies.
99
+ */
100
+ const filesToCheck = [...shipped]
101
+ .filter(f => SOURCE_EXTENSIONS.some(ext => f.endsWith(ext)))
102
+ .filter(f => !f.endsWith('.test.ts') && !f.endsWith('.test.js'))
103
+ .sort();
104
+
105
+ /** Root package name of a bare specifier ('@scope/pkg/sub' → '@scope/pkg'). */
106
+ function packageRoot(specifier: string): string {
107
+ const parts = specifier.split('/');
108
+ return specifier.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0]!;
109
+ }
110
+
111
+ /** Repo-relative path a local specifier resolves to, or null when unresolvable. */
112
+ function resolveLocal(fromFile: string, target: string): string | null {
113
+ // A ".js" specifier is the bundler-style spelling of a ".ts" sibling — Bun
114
+ // rewrites it, so the same candidate must be tried here.
115
+ const targets = target.endsWith('.js') ? [target, `${target.slice(0, -3)}.ts`] : [target];
116
+
117
+ for (const candidateTarget of targets) {
118
+ for (const suffix of RESOLVE_SUFFIXES) {
119
+ const candidate = resolve(REPO_ROOT, dirname(fromFile), candidateTarget + suffix);
120
+ if (existsSync(candidate) && statSync(candidate).isFile()) {
121
+ return relative(REPO_ROOT, candidate);
122
+ }
123
+ }
124
+ }
125
+ return null;
126
+ }
127
+
128
+ interface Violation {
129
+ file: string;
130
+ specifier: string;
131
+ kind: string;
132
+ problem: string;
133
+ }
134
+
135
+ function inspect(file: string): Violation[] {
136
+ const transpiler = new Bun.Transpiler({ loader: file.endsWith('.js') ? 'js' : 'ts' });
137
+ const violations: Violation[] = [];
138
+
139
+ // The transpiler rejects a shebang line, which the CLI entrypoints carry.
140
+ const source = readFileSync(join(REPO_ROOT, file), 'utf8').replace(/^#!.*/, '');
141
+
142
+ for (const { path: specifier, kind } of transpiler.scanImports(source)) {
143
+ const report = (problem: string) => violations.push({ file, specifier, kind, problem });
144
+
145
+ // Aliased ($backend/…) and relative specifiers must land on a shipped file.
146
+ const aliasRoot = specifier.split('/')[0]!;
147
+ const aliasTarget = ALIASES[aliasRoot];
148
+ const local = aliasTarget !== undefined
149
+ ? resolveLocal('.', `./${[aliasTarget, ...specifier.split('/').slice(1)].join('/')}`)
150
+ : specifier.startsWith('.') ? resolveLocal(file, specifier) : undefined;
151
+
152
+ if (local !== undefined) {
153
+ if (local === null) report('does not resolve to any file in the repo');
154
+ else if (!shipped.has(local)) {
155
+ report(`resolves to "${local}", which package.json "files" does not ship`);
156
+ }
157
+ continue;
158
+ }
159
+
160
+ if (specifier.startsWith('node:') || specifier.startsWith('bun:')) continue;
161
+ if (builtins.has(packageRoot(specifier))) continue;
162
+
163
+ const root = packageRoot(specifier);
164
+ if (dependencies.has(root)) continue;
165
+ if (devDependencies.has(root)) {
166
+ report(
167
+ `"${root}" is a devDependency, so it is absent on an end user's install — ` +
168
+ 'import it with `import type`, or load it at runtime via loadEngineSdk()'
169
+ );
170
+ continue;
171
+ }
172
+ report(`"${root}" is not declared in package.json dependencies`);
173
+ }
174
+
175
+ return violations;
176
+ }
177
+
178
+ describe('shipped runtime', () => {
179
+ test('ships a non-trivial number of source files', () => {
180
+ // Guards the walk itself: a bad "files" read would otherwise make every
181
+ // assertion below pass vacuously.
182
+ expect(filesToCheck.length).toBeGreaterThan(100);
183
+ expect(filesToCheck.some(f => f.startsWith(`backend${sep}`))).toBe(true);
184
+ });
185
+
186
+ test('every runtime import resolves on an end user install', () => {
187
+ const violations = filesToCheck.flatMap(inspect);
188
+ const report = violations
189
+ .map(v => ` ${v.file}\n ${v.kind} "${v.specifier}" — ${v.problem}`)
190
+ .join('\n');
191
+ expect(report).toBe('');
192
+ });
193
+
194
+ test('detects a devDependency import (the guard itself works)', () => {
195
+ // The bug this suite exists to prevent, reproduced in-memory: if this ever
196
+ // stops being reported, the check above has silently gone blind.
197
+ const transpiler = new Bun.Transpiler({ loader: 'ts' });
198
+ const offending = "import { clampThinkingLevel } from '@earendil-works/pi-ai';\n" +
199
+ 'export const level = clampThinkingLevel;\n';
200
+ const scanned = transpiler.scanImports(offending);
201
+
202
+ expect(scanned.map(s => s.path)).toContain('@earendil-works/pi-ai');
203
+ expect(devDependencies.has('@earendil-works/pi-ai')).toBe(true);
204
+ expect(dependencies.has('@earendil-works/pi-ai')).toBe(false);
205
+ });
206
+
207
+ test('type-only imports are erased, so they are never flagged', () => {
208
+ const transpiler = new Bun.Transpiler({ loader: 'ts' });
209
+ const typeOnly = [
210
+ "import type { Model } from '@earendil-works/pi-ai';",
211
+ "import { type Api } from '@earendil-works/pi-ai';",
212
+ "type Sdk = typeof import('@earendil-works/pi-coding-agent');",
213
+ "type Snip = import('svelte').Snippet;",
214
+ 'export type { Model, Api, Sdk, Snip };',
215
+ ].join('\n');
216
+
217
+ expect(transpiler.scanImports(typeOnly)).toEqual([]);
218
+ });
219
+
220
+ test('runtime dynamic imports are seen (ESLint alone cannot see these)', () => {
221
+ const transpiler = new Bun.Transpiler({ loader: 'ts' });
222
+ const dynamic = "export const load = () => import('@github/copilot-sdk');\n";
223
+
224
+ expect(transpiler.scanImports(dynamic)).toEqual([
225
+ { kind: 'dynamic-import', path: '@github/copilot-sdk' },
226
+ ]);
227
+ });
228
+ });
@@ -39,6 +39,7 @@ import { instructionsRouter } from './instructions';
39
39
  import { permissionsRouter } from './permissions';
40
40
  import { profilesRouter } from './profiles';
41
41
  import { artifactsRouter } from './artifacts';
42
+ import { memoryRouter } from './memory';
42
43
 
43
44
  // ============================================
44
45
  // Main App Router - Merge All Module Routers
@@ -97,7 +98,10 @@ export const wsRouter = createRouter()
97
98
 
98
99
  // Profiles (reusable artifact bundles activated per-session)
99
100
  .merge(profilesRouter)
100
- .merge(artifactsRouter);
101
+ .merge(artifactsRouter)
102
+
103
+ // Memory Graph (unified episodic + structural memory, shared by every engine)
104
+ .merge(memoryRouter);
101
105
 
102
106
  // Export API type for frontend type-safe access
103
107
  export type WSAPI = typeof wsRouter['$api'];