@myrialabs/clopen 0.4.28 → 0.4.30

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 (62) hide show
  1. package/backend/auth/auth-service.ts +45 -25
  2. package/backend/auth/onboarding.test.ts +106 -0
  3. package/backend/auth/permissions.ts +1 -1
  4. package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/database/queries/graph-queries.ts +417 -32
  7. package/backend/database/utils/connection.ts +7 -31
  8. package/backend/db-client/drivers/mssql.ts +57 -22
  9. package/backend/db-client/drivers/mysql.ts +69 -48
  10. package/backend/db-client/drivers/postgres.ts +65 -53
  11. package/backend/engine/README.md +8 -3
  12. package/backend/engine/adapters/claude/message-converter.ts +51 -0
  13. package/backend/engine/adapters/claude/stream.ts +81 -15
  14. package/backend/engine/adapters/codex/message-converter.ts +8 -2
  15. package/backend/engine/adapters/codex/models.ts +85 -98
  16. package/backend/engine/adapters/codex/stream.ts +5 -7
  17. package/backend/engine/adapters/codex/usage-rollout.ts +7 -0
  18. package/backend/engine/adapters/copilot/stream.ts +24 -0
  19. package/backend/engine/docs/artifacts.md +1 -1
  20. package/backend/engine/docs/lessons-learned.md +78 -1
  21. package/backend/engine/docs/quick-reference.md +1 -1
  22. package/backend/engine/docs/stack.md +8 -0
  23. package/backend/engine/install-recipes.ts +19 -2
  24. package/backend/files/file-size-limit.ts +5 -14
  25. package/backend/files/file-watcher.test.ts +160 -0
  26. package/backend/files/file-watcher.ts +276 -58
  27. package/backend/git/git-executor.ts +8 -0
  28. package/backend/git/git-service.test.ts +136 -0
  29. package/backend/git/git-service.ts +113 -17
  30. package/backend/index.ts +16 -4
  31. package/backend/mcp/internal/remote-server.test.ts +8 -3
  32. package/backend/mcp/internal/remote-server.ts +1 -1
  33. package/backend/memory/bootstrap.ts +9 -0
  34. package/backend/memory/layout.ts +985 -0
  35. package/backend/memory/notify.ts +33 -7
  36. package/backend/memory/view.ts +375 -69
  37. package/backend/permissions/index.ts +4 -2
  38. package/backend/permissions/resolve.ts +7 -5
  39. package/backend/settings/system-settings.ts +97 -0
  40. package/backend/tunnel/public-origin.ts +5 -13
  41. package/backend/utils/env.ts +29 -0
  42. package/backend/utils/paths.ts +9 -3
  43. package/backend/utils/process-warnings.ts +41 -0
  44. package/backend/ws/auth/login.test.ts +8 -1
  45. package/backend/ws/auth/login.ts +22 -15
  46. package/backend/ws/auth/status.ts +24 -1
  47. package/backend/ws/chat/stream.ts +1 -0
  48. package/backend/ws/files/watch.ts +9 -0
  49. package/backend/ws/memory/crud.ts +50 -2
  50. package/backend/ws/settings/crud.ts +14 -22
  51. package/dist/assets/{index-BujQYGBm.js → index-DUc5T21e.js} +1 -1
  52. package/dist/assets/{index-DRMOgS9y.js → index-DYwQ5bP8.js} +1 -1
  53. package/dist/assets/main-VgdjTBLR.css +1 -0
  54. package/dist/assets/main-r0iv2PDz.js +1044 -0
  55. package/dist/index.html +2 -2
  56. package/package.json +14 -14
  57. package/shared/constants/engines.ts +1 -0
  58. package/shared/types/memory.ts +70 -0
  59. package/shared/types/stores/settings.ts +11 -1
  60. package/shared/types/unified/stream.ts +10 -4
  61. package/dist/assets/main-BrYtWn-4.js +0 -1036
  62. package/dist/assets/main-BrqMMMRX.css +0 -1
@@ -4,7 +4,8 @@
4
4
  * Core authentication logic: user creation, session management, invite handling.
5
5
  */
6
6
 
7
- import { authQueries, projectQueries, settingsQueries } from '$backend/database/queries';
7
+ import { authQueries, projectQueries } from '$backend/database/queries';
8
+ import { readSystemSettings, writeSystemSettings } from '$backend/settings/system-settings';
8
9
  import type { Project } from '$shared/types/database/schema';
9
10
  import { generateSessionToken, generatePAT, generateInviteToken, generateDeviceCode, hashToken, getTokenType } from './tokens';
10
11
  import { generateColorFromString, getInitials } from '$backend/utils/user-helpers';
@@ -85,38 +86,57 @@ export function needsSetup(): boolean {
85
86
  }
86
87
 
87
88
  /**
88
- * Get parsed system settings from DB (cached per call).
89
+ * Onboarding (setup wizard) state.
90
+ *
91
+ * `pending` is only ever reported when we positively know the wizard is
92
+ * unfinished — a fresh install, or a run that recorded the marker and has not
93
+ * completed yet. Everything else resolves to `complete`, because sending a
94
+ * working instance back through the wizard is destructive: it re-asks for the
95
+ * auth mode and lets the user overwrite live settings.
96
+ *
97
+ * `getOnboardingState()` deliberately does NOT catch read failures. A database
98
+ * error must surface to the caller instead of being reported as "never
99
+ * onboarded" — that silent downgrade is what used to drop users into the wizard
100
+ * at random.
89
101
  */
90
- function getSystemSettingsParsed(): Record<string, unknown> {
91
- try {
92
- const setting = settingsQueries.get('system:settings');
93
- if (setting?.value) {
94
- return typeof setting.value === 'string' ? JSON.parse(setting.value) : setting.value;
95
- }
96
- } catch {
97
- // Settings may not exist yet
102
+ export type OnboardingState = 'pending' | 'complete';
103
+
104
+ export function getOnboardingState(): OnboardingState {
105
+ const stored = readSystemSettings();
106
+
107
+ // `onboarding` is the current marker; `onboardingComplete` is the legacy
108
+ // boolean, still read (and written) so a downgrade keeps working.
109
+ if (stored.onboarding === 'complete' || stored.onboardingComplete === true) return 'complete';
110
+ if (stored.onboarding === 'pending') return 'pending';
111
+
112
+ // No marker at all. An install that already has users has, by definition,
113
+ // been through setup — the wizard is what created them. Record that so a
114
+ // single missing key can never flap the whole instance back to setup.
115
+ if (!needsSetup()) {
116
+ markOnboardingComplete();
117
+ debug.log('auth', 'Onboarding marker missing but users exist — recorded as complete');
118
+ return 'complete';
98
119
  }
99
- return {};
120
+
121
+ return 'pending';
100
122
  }
101
123
 
102
- /**
103
- * Get the current auth mode from system settings.
104
- * Returns 'required' by default (before setup is complete).
105
- */
106
- export function getAuthMode(): 'none' | 'required' {
107
- const parsed = getSystemSettingsParsed();
108
- if (parsed.authMode === 'none' || parsed.authMode === 'required') {
109
- return parsed.authMode as 'none' | 'required';
110
- }
111
- return 'required';
124
+ /** True when the setup wizard has been completed. */
125
+ export function isOnboardingComplete(): boolean {
126
+ return getOnboardingState() === 'complete';
112
127
  }
113
128
 
114
129
  /**
115
- * Check if the initial onboarding wizard has been completed.
130
+ * Record that a fresh install has entered the wizard, so a refresh mid-setup
131
+ * resumes it instead of being mistaken for a completed install.
116
132
  */
117
- export function isOnboardingComplete(): boolean {
118
- const parsed = getSystemSettingsParsed();
119
- return parsed.onboardingComplete === true;
133
+ export function markOnboardingPending(): void {
134
+ writeSystemSettings({ onboarding: 'pending', onboardingComplete: false });
135
+ }
136
+
137
+ /** Record that the wizard finished. Writes both the current and legacy markers. */
138
+ export function markOnboardingComplete(): void {
139
+ writeSystemSettings({ onboarding: 'complete', onboardingComplete: true });
120
140
  }
121
141
 
122
142
  /**
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Regression tests for the setup-wizard gate.
3
+ *
4
+ * These lock in the two properties that stopped a working install from being
5
+ * sent back through onboarding (and having its settings reset by the wizard):
6
+ * the data directory is isolated while testing, and a missing onboarding marker
7
+ * on an install that already has users resolves to "complete" instead of
8
+ * "never onboarded".
9
+ */
10
+
11
+ import { describe, expect, test, beforeAll, afterAll } from 'bun:test';
12
+ import { randomUUID } from 'node:crypto';
13
+
14
+ import { getOnboardingState, markOnboardingComplete } from './auth-service';
15
+ import { readSystemSettings, writeSystemSettings, SYSTEM_SETTINGS_KEY } from '../settings/system-settings';
16
+ import { getClopenDir } from '../utils/paths';
17
+ import { authQueries, settingsQueries } from '../database/queries';
18
+ import { initializeDatabase, closeDatabase } from '../database';
19
+
20
+ let testUserId: string;
21
+ let originalSettings: string | null = null;
22
+
23
+ beforeAll(async () => {
24
+ await initializeDatabase();
25
+ originalSettings = settingsQueries.get(SYSTEM_SETTINGS_KEY)?.value ?? null;
26
+
27
+ // The self-heal path is only correct for an install that has users, so make
28
+ // sure one exists regardless of what else ran before this file.
29
+ testUserId = `user-${randomUUID()}`;
30
+ authQueries.createUser({
31
+ id: testUserId,
32
+ name: 'Onboarding Test User',
33
+ color: '#000000',
34
+ avatar: 'OT',
35
+ role: 'admin',
36
+ personal_access_token_hash: `hash-${randomUUID()}`,
37
+ created_at: new Date().toISOString()
38
+ });
39
+ });
40
+
41
+ afterAll(() => {
42
+ authQueries.deleteUser(testUserId);
43
+ if (originalSettings === null) {
44
+ settingsQueries.delete(SYSTEM_SETTINGS_KEY);
45
+ } else {
46
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, originalSettings);
47
+ }
48
+ closeDatabase();
49
+ });
50
+
51
+ describe('data directory isolation', () => {
52
+ test('tests never resolve to the production data directory', () => {
53
+ // The whole class of bug this file guards against started here: the test
54
+ // runner sets NODE_ENV=test, which used to fall through to ~/.clopen and
55
+ // let the suite rewrite live rows in the developer's own install.
56
+ const dir = getClopenDir();
57
+ expect(dir).toContain('.clopen-test');
58
+ expect(dir.endsWith('/.clopen')).toBe(false);
59
+ });
60
+ });
61
+
62
+ describe('system settings writes', () => {
63
+ test('merge into the stored blob instead of replacing it', () => {
64
+ writeSystemSettings({ onboarding: 'complete', maxFileSizeMB: 123 });
65
+ writeSystemSettings({ authMode: 'required' });
66
+
67
+ const stored = readSystemSettings();
68
+ expect(stored.authMode).toBe('required');
69
+ expect(stored.maxFileSizeMB).toBe(123);
70
+ // The sibling that used to disappear.
71
+ expect(stored.onboarding).toBe('complete');
72
+ });
73
+ });
74
+
75
+ describe('onboarding state', () => {
76
+ test('is complete once the marker is recorded', () => {
77
+ markOnboardingComplete();
78
+ expect(getOnboardingState()).toBe('complete');
79
+ });
80
+
81
+ test('respects an explicitly pending wizard so a refresh resumes setup', () => {
82
+ writeSystemSettings({ onboarding: 'pending', onboardingComplete: false });
83
+ expect(getOnboardingState()).toBe('pending');
84
+ });
85
+
86
+ test('still honours the legacy onboardingComplete boolean', () => {
87
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify({ onboardingComplete: true }));
88
+ expect(getOnboardingState()).toBe('complete');
89
+ });
90
+
91
+ test('self-heals when the marker is missing but users exist', () => {
92
+ // Exactly the state a stray full-blob write leaves behind.
93
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify({ authMode: 'required' }));
94
+
95
+ expect(getOnboardingState()).toBe('complete');
96
+ // And it is persisted, so the next read cannot flap back to the wizard.
97
+ expect(readSystemSettings().onboarding).toBe('complete');
98
+ });
99
+
100
+ test('self-heals when the whole settings row is gone', () => {
101
+ settingsQueries.delete(SYSTEM_SETTINGS_KEY);
102
+
103
+ expect(getOnboardingState()).toBe('complete');
104
+ expect(readSystemSettings().onboarding).toBe('complete');
105
+ });
106
+ });
@@ -5,7 +5,7 @@
5
5
  * Used by the auth gate in WSRouter.handleMessage().
6
6
  */
7
7
 
8
- import { getAuthMode } from './auth-service';
8
+ import { getAuthMode } from '$backend/settings/system-settings';
9
9
 
10
10
  /** Routes that can be accessed WITHOUT authentication */
11
11
  export const PUBLIC_ROUTES = new Set([
@@ -0,0 +1,91 @@
1
+ import type { DatabaseConnection } from '$shared/types/database/connection';
2
+ import { debug } from '$shared/utils/logger';
3
+
4
+ export const description =
5
+ 'Persist memory-graph communities and layout positions, and index the graph view ordering';
6
+
7
+ /**
8
+ * Make the Memory view stop paying for the whole graph on every look.
9
+ *
10
+ * Two things used to be recomputed from scratch on every single fetch, and both
11
+ * of them grow with the store rather than with what is being displayed:
12
+ *
13
+ * - COMMUNITY DETECTION. Louvain ran inside `buildGraphView`, so opening the
14
+ * modal, changing a filter, or any conversation writing a memory made every
15
+ * connected client re-cluster the graph server-side. The result is stable
16
+ * per dataset, so it belonged in a table all along.
17
+ *
18
+ * - LAYOUT. ForceAtlas2 ran in the browser on every open, from a deterministic
19
+ * seed — several hundred iterations to arrive at the same arrangement it
20
+ * arrived at last time, discarded the moment the modal closed. That is what
21
+ * made opening the modal janky once the graph got big: the animation and a
22
+ * few hundred milliseconds of layout were competing for one thread.
23
+ *
24
+ * `graph_layout` holds both, keyed by node. It is deliberately a SEPARATE table
25
+ * rather than columns on `graph_nodes`: a position is a property of an
26
+ * arrangement, not of a memory, so a re-layout must never look like an edit to
27
+ * the memory itself — `updated_at` on `graph_nodes` drives recall ranking, and
28
+ * bumping it every time a node drifted two pixels would have quietly reordered
29
+ * what agents get told.
30
+ *
31
+ * The row is derived data. Losing it costs a background pass, never a memory,
32
+ * which is why it cascades away with its node and is safe to delete wholesale.
33
+ */
34
+ export const up = (db: DatabaseConnection): void => {
35
+ debug.log('migration', 'Creating the memory graph layout table...');
36
+
37
+ // `placed` separates the two halves of what a pass produces, and they do NOT
38
+ // have the same reach. Community detection runs over every live node — it is
39
+ // linear in the edges and it is what the overview groups by, so leaving nodes
40
+ // out of it would leave them out of the picture entirely. The force simulation
41
+ // is superlinear and therefore capped, so the lowest-ranked nodes get their
42
+ // community's neighbourhood as a position rather than a computed one.
43
+ //
44
+ // Without the flag those two are indistinguishable, and a guessed position
45
+ // would be handed to the client as though it were a real one — every member of
46
+ // a large lobe stacked on a single point, with nothing to say they should be
47
+ // spread out.
48
+ db.exec(`
49
+ CREATE TABLE IF NOT EXISTS graph_layout (
50
+ node_id TEXT PRIMARY KEY REFERENCES graph_nodes(id) ON DELETE CASCADE,
51
+ community INTEGER NOT NULL DEFAULT 0,
52
+ x REAL NOT NULL DEFAULT 0,
53
+ y REAL NOT NULL DEFAULT 0,
54
+ placed INTEGER NOT NULL DEFAULT 1,
55
+ updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP
56
+ )
57
+ `);
58
+
59
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_layout_community ON graph_layout (community)`);
60
+
61
+ // Zooming into part of the map asks for the nodes inside a rectangle, which
62
+ // without this is a scan of the whole arrangement for a handful of rows.
63
+ db.exec(`CREATE INDEX IF NOT EXISTS idx_graph_layout_position ON graph_layout (x, y)`);
64
+
65
+ /**
66
+ * The graph view's own ordering, which had no index at all.
67
+ *
68
+ * `graphQueries.list` selects `ORDER BY pinned DESC, weight DESC, updated_at
69
+ * DESC LIMIT n`, and with nothing to read that order from SQLite had to scan
70
+ * every live row and sort ALL of them before taking the first few thousand.
71
+ * That is the one part of a fetch that grew without bound: the cap limited
72
+ * what was returned, never what was examined.
73
+ *
74
+ * Partial on the same predicate the view always applies, so it stays the size
75
+ * of the live graph however much history accumulates behind it.
76
+ */
77
+ db.exec(`
78
+ CREATE INDEX IF NOT EXISTS idx_graph_nodes_view
79
+ ON graph_nodes (pinned DESC, weight DESC, updated_at DESC)
80
+ WHERE archived_at IS NULL AND superseded_by IS NULL
81
+ `);
82
+
83
+ debug.log('migration', 'Memory graph layout table ready');
84
+ };
85
+
86
+ export const down = (db: DatabaseConnection): void => {
87
+ db.exec(`DROP INDEX IF EXISTS idx_graph_nodes_view`);
88
+ db.exec(`DROP INDEX IF EXISTS idx_graph_layout_position`);
89
+ db.exec(`DROP INDEX IF EXISTS idx_graph_layout_community`);
90
+ db.exec(`DROP TABLE IF EXISTS graph_layout`);
91
+ };
@@ -65,6 +65,7 @@ import * as migration063 from './063_add_invite_project_ids';
65
65
  import * as migration064 from './064_create_messages_fts';
66
66
  import * as migration065 from './065_add_session_reasoning_effort';
67
67
  import * as migration066 from './066_create_memory_graph';
68
+ import * as migration067 from './067_add_memory_graph_layout';
68
69
 
69
70
  // Export all migrations in order
70
71
  export const migrations = [
@@ -463,6 +464,12 @@ export const migrations = [
463
464
  description: migration066.description,
464
465
  up: migration066.up,
465
466
  down: migration066.down
467
+ },
468
+ {
469
+ id: '067',
470
+ description: migration067.description,
471
+ up: migration067.up,
472
+ down: migration067.down
466
473
  }
467
474
  ];
468
475