@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
@@ -0,0 +1,97 @@
1
+ /**
2
+ * System Settings — single source of truth for the `system:settings` row.
3
+ *
4
+ * Every reader and writer of that blob goes through here. Two rules keep the
5
+ * "wizard came back / settings reset themselves" class of bug from returning:
6
+ *
7
+ * 1. A failed read is never flattened into "the setting is unset".
8
+ * `readSystemSettings()` throws when the database is unavailable or the blob
9
+ * is unparseable, so each caller has to pick its fallback deliberately. The
10
+ * old copy-pasted readers swallowed every error and returned `{}`, which told
11
+ * a perfectly healthy install that it had never been onboarded.
12
+ * 2. Writes always merge into the stored blob, never replace it, so a caller
13
+ * holding a stale copy of the settings cannot drop sibling fields.
14
+ */
15
+
16
+ import { settingsQueries } from '$backend/database/queries';
17
+ import type { AuthMode, SystemSettings } from '$shared/types/stores/settings';
18
+ import { debug } from '$shared/utils/logger';
19
+
20
+ /** The settings-table key the whole system-settings blob lives under. */
21
+ export const SYSTEM_SETTINGS_KEY = 'system:settings';
22
+
23
+ /**
24
+ * Stored shape: the typed fields, plus anything a newer or older build wrote.
25
+ * Unknown keys are preserved by every write so a downgrade never loses data.
26
+ */
27
+ export type StoredSystemSettings = Partial<SystemSettings> & Record<string, unknown>;
28
+
29
+ /**
30
+ * Read and parse the system settings blob.
31
+ *
32
+ * Returns `{}` only when the row genuinely does not exist yet (fresh install).
33
+ * THROWS when the database is unreachable or the stored value is not valid
34
+ * JSON — those are failures, not "no settings", and callers must not treat them
35
+ * the same way.
36
+ */
37
+ export function readSystemSettings(): StoredSystemSettings {
38
+ const row = settingsQueries.get(SYSTEM_SETTINGS_KEY);
39
+ if (!row?.value) return {};
40
+
41
+ const parsed = typeof row.value === 'string' ? JSON.parse(row.value) : row.value;
42
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
43
+ throw new Error(`${SYSTEM_SETTINGS_KEY} holds a non-object value`);
44
+ }
45
+ return parsed as StoredSystemSettings;
46
+ }
47
+
48
+ /**
49
+ * Read a single field with an explicit fallback, tolerating an unreadable blob.
50
+ *
51
+ * Use this for settings where continuing with the default is genuinely correct
52
+ * (a size limit, a public URL). Do NOT use it for state that decides whether the
53
+ * user has already completed something — see `auth-service`'s onboarding state.
54
+ */
55
+ export function readSystemSetting<T>(pick: (settings: StoredSystemSettings) => T | undefined, fallback: T): T {
56
+ try {
57
+ const value = pick(readSystemSettings());
58
+ return value === undefined ? fallback : value;
59
+ } catch (error) {
60
+ debug.warn('settings', 'System settings unreadable, using default for one field:', error);
61
+ return fallback;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Merge a patch into the stored blob — the only writer of this row.
67
+ *
68
+ * Returns the merged result so callers can confirm what was persisted.
69
+ */
70
+ export function writeSystemSettings(patch: StoredSystemSettings): StoredSystemSettings {
71
+ let current: StoredSystemSettings = {};
72
+ try {
73
+ current = readSystemSettings();
74
+ } catch (error) {
75
+ // The blob is unreadable, so rebuilding from the patch is the only way
76
+ // forward — but it is also the moment sibling settings are lost, so it is
77
+ // logged as an error rather than quietly absorbed.
78
+ debug.error('settings', 'System settings unreadable, rebuilding from patch:', error);
79
+ }
80
+
81
+ const merged = { ...current, ...patch };
82
+ settingsQueries.set(SYSTEM_SETTINGS_KEY, JSON.stringify(merged));
83
+ return merged;
84
+ }
85
+
86
+ /**
87
+ * Current auth mode.
88
+ *
89
+ * Fail-secure: an unreadable blob resolves to 'required' (login enforced), and
90
+ * this runs inside the WebSocket auth gate, so it must never throw.
91
+ */
92
+ export function getAuthMode(): AuthMode {
93
+ return readSystemSetting(
94
+ (s) => (s.authMode === 'none' || s.authMode === 'required' ? s.authMode : undefined),
95
+ 'required'
96
+ );
97
+ }
@@ -16,7 +16,7 @@
16
16
 
17
17
  import { tunnelKit, portFromService } from './tunnel-config';
18
18
  import { SERVER_ENV } from '../utils/env';
19
- import { settingsQueries } from '$backend/database/queries';
19
+ import { readSystemSetting } from '$backend/settings/system-settings';
20
20
  import { debug } from '$shared/utils/logger';
21
21
 
22
22
  export type PublicOriginSource = 'configured' | 'domain' | 'tunnel';
@@ -50,18 +50,10 @@ function normalizeOrigin(url: string): string {
50
50
 
51
51
  /** Read the admin-configured public base URL from system settings, if any. */
52
52
  function getConfiguredPublicBaseUrl(): string | null {
53
- try {
54
- const setting = settingsQueries.get('system:settings');
55
- if (!setting?.value) return null;
56
- const parsed = typeof setting.value === 'string' ? JSON.parse(setting.value) : setting.value;
57
- const url = parsed?.publicBaseUrl;
58
- if (typeof url === 'string' && url.trim()) {
59
- return normalizeOrigin(url.trim());
60
- }
61
- } catch {
62
- // Settings may not exist yet.
63
- }
64
- return null;
53
+ return readSystemSetting((settings) => {
54
+ const url = settings.publicBaseUrl;
55
+ return typeof url === 'string' && url.trim() ? normalizeOrigin(url.trim()) : undefined;
56
+ }, null);
65
57
  }
66
58
 
67
59
  /** Find an already-running quick tunnel pointing at the given local port. */
@@ -16,12 +16,41 @@
16
16
 
17
17
  import { readFileSync } from 'fs';
18
18
  import { join } from 'path';
19
+ import { homedir } from 'os';
19
20
 
20
21
  // ── Server configuration (read once at import time) ─────────────────
21
22
  const isDev = process.env.NODE_ENV !== 'production';
22
23
 
24
+ /**
25
+ * Resolve the Clopen data directory — the single decision point for where ALL
26
+ * persisted state lives (app.db, engine homes, stack, snapshots, tunnel…).
27
+ *
28
+ * Resolved once, at import time, for two reasons:
29
+ *
30
+ * 1. `NODE_ENV` is not stable at runtime. Any dependency that assigns to
31
+ * `process.env.NODE_ENV` mid-process would otherwise silently move the data
32
+ * directory out from under a running server.
33
+ * 2. The test runner sets `NODE_ENV=test`, which used to fall through to the
34
+ * production directory — so `bun test` opened the developer's real
35
+ * `~/.clopen/app.db` and rewrote live rows (that is what kept resetting the
36
+ * onboarding flag and system settings). Tests get their own directory here,
37
+ * once, so no individual test has to remember to isolate itself.
38
+ *
39
+ * `CLOPEN_DATA_DIR` overrides everything, for deployments that keep state
40
+ * outside the home directory.
41
+ */
42
+ function resolveDataDir(): string {
43
+ const override = process.env.CLOPEN_DATA_DIR?.trim();
44
+ if (override) return override;
45
+ if (process.env.NODE_ENV === 'test') return join(homedir(), '.clopen-test');
46
+ if (process.env.NODE_ENV === 'development') return join(homedir(), '.clopen-dev');
47
+ return join(homedir(), '.clopen');
48
+ }
49
+
23
50
  export const SERVER_ENV = {
24
51
  NODE_ENV: (process.env.NODE_ENV || 'development') as string,
52
+ /** Absolute path to the Clopen data directory — see `resolveDataDir()`. */
53
+ DATA_DIR: resolveDataDir(),
25
54
  /** Backend port — dev: CLOPEN_PORT_BACKEND (default 9161), prod: CLOPEN_PORT (default 9141) */
26
55
  PORT: isDev
27
56
  ? (process.env.CLOPEN_PORT_BACKEND ? parseInt(process.env.CLOPEN_PORT_BACKEND) : 9161)
@@ -1,13 +1,19 @@
1
1
  import { join, resolve } from 'path';
2
- import { homedir } from 'os';
2
+ import { SERVER_ENV } from './env';
3
3
 
4
4
  /**
5
5
  * Returns the Clopen data directory.
6
6
  * - development: ~/.clopen-dev
7
- * - everything else (production, undefined): ~/.clopen
7
+ * - test: ~/.clopen-test (never the real one — see resolveDataDir)
8
+ * - production: ~/.clopen
9
+ * - `CLOPEN_DATA_DIR` overrides all of the above.
10
+ *
11
+ * The value is resolved once at import time in `SERVER_ENV.DATA_DIR`; this is
12
+ * only a named accessor for it, so every caller sees the same directory for the
13
+ * lifetime of the process.
8
14
  */
9
15
  export function getClopenDir(): string {
10
- return join(homedir(), process.env.NODE_ENV === 'development' ? '.clopen-dev' : '.clopen');
16
+ return SERVER_ENV.DATA_DIR;
11
17
  }
12
18
 
13
19
  /**
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Process warning filter — the single place that decides which
3
+ * `process.emitWarning` output reaches the server log.
4
+ *
5
+ * Registering ANY 'warning' listener silences the runtime's default printer
6
+ * (Bun only prints when the event has no listener at all — verified on Bun
7
+ * 1.3.x, where `process.listenerCount('warning')` is 0 out of the box). So this
8
+ * module owns the printing too: anything it does not explicitly suppress is
9
+ * re-emitted to the log, or we would swallow deprecation notices,
10
+ * MaxListenersExceededWarning, TimeoutOverflowWarning and friends.
11
+ *
12
+ * Suppress by `code`, never by message text — codes are stable, wording is not.
13
+ */
14
+
15
+ import { debug } from '$shared/utils/logger';
16
+
17
+ /**
18
+ * Warning codes we deliberately drop, each with the reason it is noise here.
19
+ *
20
+ * - CLAUDE_SDK_CAN_USE_TOOL_SHADOWED: @anthropic-ai/claude-agent-sdk >= 0.3.229
21
+ * emits this on every query() when `canUseTool` is passed alongside
22
+ * permissionMode 'bypassPermissions' — a static check on the options object,
23
+ * not an observed failure. Clopen keeps the callback for one job the CLI does
24
+ * still route through it (AskUserQuestion, which must wait on a human without
25
+ * a deadline); tool gating moved to the PreToolUse hook the warning itself
26
+ * recommends. See backend/engine/adapters/claude/stream.ts.
27
+ */
28
+ const SUPPRESSED_WARNING_CODES = new Set(['CLAUDE_SDK_CAN_USE_TOOL_SHADOWED']);
29
+
30
+ let installed = false;
31
+
32
+ /** Idempotent — safe to call from more than one entry point. */
33
+ export function installProcessWarningFilter(): void {
34
+ if (installed) return;
35
+ installed = true;
36
+
37
+ process.on('warning', (warning: Error & { code?: string }) => {
38
+ if (warning.code && SUPPRESSED_WARNING_CODES.has(warning.code)) return;
39
+ debug.warn('server', warning.stack || `${warning.name}: ${warning.message}`);
40
+ });
41
+ }
@@ -53,6 +53,8 @@ const mockCreateUserFromInvite = mock((inviteToken: string, name: string) => ({
53
53
 
54
54
  const mockNeedsSetup = mock(() => true);
55
55
  const mockGetAuthMode = mock(() => 'none');
56
+ const mockMarkOnboardingPending = mock(() => {});
57
+ const mockWriteSystemSettings = mock((patch: Record<string, unknown>) => patch);
56
58
 
57
59
  // Mock settings
58
60
  let mockSettings: any = { value: JSON.stringify({ authMode: 'required' }) };
@@ -83,12 +85,17 @@ mock.module('$backend/database/queries', () => ({
83
85
  }
84
86
  }));
85
87
 
88
+ mock.module('$backend/settings/system-settings', () => ({
89
+ getAuthMode: mockGetAuthMode,
90
+ writeSystemSettings: mockWriteSystemSettings
91
+ }));
92
+
86
93
  mock.module('$backend/auth/auth-service', () => ({
87
94
  createAdmin: mockCreateAdmin,
88
95
  createOrGetNoAuthAdmin: mockCreateOrGetNoAuthAdmin,
89
96
  createUserFromInvite: mockCreateUserFromInvite,
90
97
  needsSetup: mockNeedsSetup,
91
- getAuthMode: mockGetAuthMode,
98
+ markOnboardingPending: mockMarkOnboardingPending,
92
99
  loginWithToken: mock(() => ({})),
93
100
  logout: mock(() => {}),
94
101
  logoutAllSessions: mock(() => 0),
@@ -2,7 +2,6 @@ import { t } from 'elysia';
2
2
  import { createRouter } from '$shared/utils/ws-server';
3
3
  import {
4
4
  createAdmin,
5
- getAuthMode,
6
5
  loginWithToken,
7
6
  createUserFromInvite,
8
7
  logout,
@@ -11,9 +10,11 @@ import {
11
10
  regeneratePAT,
12
11
  updateUserName,
13
12
  createOrGetNoAuthAdmin,
14
- needsSetup
13
+ needsSetup,
14
+ markOnboardingPending
15
15
  } from '$backend/auth/auth-service';
16
- import { settingsQueries, auditLogQueries } from '$backend/database/queries';
16
+ import { getAuthMode, writeSystemSettings } from '$backend/settings/system-settings';
17
+ import { auditLogQueries } from '$backend/database/queries';
17
18
  import { getTokenType } from '$backend/auth/tokens';
18
19
  import { authRateLimiter } from '$backend/auth/rate-limiter';
19
20
  import { ws } from '$backend/utils/ws';
@@ -42,15 +43,22 @@ export const loginHandler = createRouter()
42
43
  expiresAt: t.String()
43
44
  })
44
45
  }, async ({ data, conn }) => {
46
+ // Refuse before touching any state. This route is public, so without the
47
+ // guard a stray call against a live instance would flip the onboarding
48
+ // marker below and send every user back through the wizard.
49
+ if (!needsSetup()) {
50
+ throw new Error('Setup already completed. Admin account exists.');
51
+ }
52
+
53
+ // Mark the wizard as in-progress BEFORE the first user exists, so a refresh
54
+ // between here and "Finish" resumes setup instead of looking like a
55
+ // completed install (which is how onboarding state is inferred).
56
+ markOnboardingPending();
57
+
45
58
  const result = createAdmin(data.name, { userAgent: data.userAgent, ipAddress: clientIpFromConnection(conn) });
46
59
 
47
60
  // Save authMode to system settings
48
- const currentSettings = settingsQueries.get('system:settings');
49
- const parsed = currentSettings?.value
50
- ? (typeof currentSettings.value === 'string' ? JSON.parse(currentSettings.value) : currentSettings.value)
51
- : {};
52
- parsed.authMode = 'required';
53
- settingsQueries.set('system:settings', JSON.stringify(parsed));
61
+ writeSystemSettings({ authMode: 'required' });
54
62
 
55
63
  auditLogQueries.logEvent({
56
64
  userId: result.user.id,
@@ -80,13 +88,12 @@ export const loginHandler = createRouter()
80
88
  throw new Error('Setup already completed.');
81
89
  }
82
90
 
91
+ // Same ordering as auth:setup — record the in-progress wizard before the
92
+ // first user exists.
93
+ markOnboardingPending();
94
+
83
95
  // Save authMode to system settings
84
- const currentSettings = settingsQueries.get('system:settings');
85
- const parsed = currentSettings?.value
86
- ? (typeof currentSettings.value === 'string' ? JSON.parse(currentSettings.value) : currentSettings.value)
87
- : {};
88
- parsed.authMode = 'none';
89
- settingsQueries.set('system:settings', JSON.stringify(parsed));
96
+ writeSystemSettings({ authMode: 'none' });
90
97
 
91
98
  // Create or get default admin
92
99
  const result = createOrGetNoAuthAdmin();
@@ -1,6 +1,7 @@
1
1
  import { t } from 'elysia';
2
2
  import { createRouter } from '$shared/utils/ws-server';
3
- import { needsSetup, getUserById, getAuthMode, isOnboardingComplete } from '$backend/auth/auth-service';
3
+ import { needsSetup, getUserById, isOnboardingComplete, markOnboardingComplete } from '$backend/auth/auth-service';
4
+ import { getAuthMode } from '$backend/settings/system-settings';
4
5
  import { ws } from '$backend/utils/ws';
5
6
 
6
7
  export const statusHandler = createRouter()
@@ -22,6 +23,10 @@ export const statusHandler = createRouter()
22
23
  })
23
24
  }, async ({ conn }) => {
24
25
  const setup = needsSetup();
26
+ // Deliberately NOT wrapped in a try/catch: if onboarding state cannot be
27
+ // read, this request must fail so the client keeps its current screen.
28
+ // Reporting "not onboarded" on a read error is what used to drop working
29
+ // installs into the setup wizard.
25
30
  const onboardingDone = isOnboardingComplete();
26
31
  const authMode = getAuthMode();
27
32
  const authenticated = ws.isAuthenticated(conn);
@@ -38,4 +43,22 @@ export const statusHandler = createRouter()
38
43
  }
39
44
 
40
45
  return { needsSetup: setup, onboardingComplete: onboardingDone, authenticated, authMode, user };
46
+ })
47
+
48
+ // Mark the setup wizard as finished.
49
+ //
50
+ // The server owns this marker rather than letting the client write the raw
51
+ // settings key: the wizard may only be dismissed once persistence is
52
+ // confirmed, otherwise a failed write drops the user straight back into it on
53
+ // the next refresh — silently, because the old client-side write was
54
+ // fire-and-forget. The response echoes the stored state so the client can
55
+ // verify instead of assume.
56
+ .http('auth:complete-onboarding', {
57
+ data: t.Object({}),
58
+ response: t.Object({
59
+ onboardingComplete: t.Boolean()
60
+ })
61
+ }, async () => {
62
+ markOnboardingComplete();
63
+ return { onboardingComplete: isOnboardingComplete() };
41
64
  });
@@ -1022,6 +1022,7 @@ export const streamHandler = createRouter()
1022
1022
  t.Literal('seven_day_opus'),
1023
1023
  t.Literal('seven_day_sonnet'),
1024
1024
  t.Literal('overage'),
1025
+ t.Literal('seven_day_overage_included'),
1025
1026
  t.Null()
1026
1027
  ]),
1027
1028
  timestamp: t.String(),
@@ -146,6 +146,15 @@ export const watchHandler = createRouter()
146
146
  timestamp: t.Number()
147
147
  }))
148
148
 
149
+ // Emitted when the watcher was rebuilt after a fault and may have missed
150
+ // events. Consumers should re-fetch their own data, but must NOT treat this
151
+ // as "these files changed" — no path is known to have changed, so live views
152
+ // (an open diff, an editor tab) must be reconciled in place, not rebuilt.
153
+ .emit('files:resync', t.Object({
154
+ projectId: t.String(),
155
+ timestamp: t.Number()
156
+ }))
157
+
149
158
  // Emitted on watcher errors
150
159
  .emit('files:watch-error', t.Object({
151
160
  projectId: t.String(),
@@ -24,8 +24,9 @@ import { createRouter, type WSConnection } from '$shared/utils/ws-server';
24
24
  import { ws } from '$backend/utils/ws';
25
25
  import { projectContextService } from '$backend/mcp/internal/project-context';
26
26
  import { debug } from '$shared/utils/logger';
27
- import { graphQueries } from '$backend/database/queries/graph-queries';
27
+ import { graphQueries, graphLayoutQueries } from '$backend/database/queries/graph-queries';
28
28
  import { buildGraphView, buildNodeDetail } from '$backend/memory/view';
29
+ import { resetGraphLayoutState } from '$backend/memory/layout';
29
30
  import { markConsulted, retrieve } from '$backend/memory/retrieval';
30
31
  import { scheduleVectorIndexing } from '$backend/memory/indexer';
31
32
  import { getMemoryConfig, setMemoryConfig } from '$backend/memory/config';
@@ -176,9 +177,20 @@ export const memoryCrudHandler = createRouter()
176
177
  sources: t.Optional(t.Array(SOURCE)),
177
178
  includeArchived: t.Optional(t.Boolean()),
178
179
  includeSuperseded: t.Optional(t.Boolean()),
180
+ // The rectangle of the layout to zoom into, when a mark was opened.
181
+ // Absent asks for the whole graph at whatever resolution fits.
182
+ region: t.Optional(
183
+ t.Object({
184
+ minX: t.Number(),
185
+ maxX: t.Number(),
186
+ minY: t.Number(),
187
+ maxY: t.Number()
188
+ })
189
+ ),
179
190
  limit: t.Optional(t.Number())
180
191
  }),
181
192
  response: t.Object({
193
+ level: t.String(),
182
194
  nodes: t.Array(t.Object({
183
195
  id: t.String(),
184
196
  kind: t.String(),
@@ -190,7 +202,9 @@ export const memoryCrudHandler = createRouter()
190
202
  weight: t.Number(),
191
203
  pinned: t.Boolean(),
192
204
  community: t.Number(),
193
- createdAt: t.String()
205
+ createdAt: t.String(),
206
+ x: t.Optional(t.Number()),
207
+ y: t.Optional(t.Number())
194
208
  })),
195
209
  edges: t.Array(t.Object({
196
210
  id: t.Number(),
@@ -199,6 +213,34 @@ export const memoryCrudHandler = createRouter()
199
213
  rel: t.String(),
200
214
  weight: t.Number()
201
215
  })),
216
+ bins: t.Array(t.Object({
217
+ id: t.String(),
218
+ members: t.Number(),
219
+ label: t.String(),
220
+ community: t.Number(),
221
+ x: t.Number(),
222
+ y: t.Number(),
223
+ region: t.Object({
224
+ minX: t.Number(),
225
+ maxX: t.Number(),
226
+ minY: t.Number(),
227
+ maxY: t.Number()
228
+ })
229
+ })),
230
+ binEdges: t.Array(t.Object({
231
+ source: t.String(),
232
+ target: t.String(),
233
+ weight: t.Number()
234
+ })),
235
+ region: t.Union([
236
+ t.Object({
237
+ minX: t.Number(),
238
+ maxX: t.Number(),
239
+ minY: t.Number(),
240
+ maxY: t.Number()
241
+ }),
242
+ t.Null()
243
+ ]),
202
244
  totalNodes: t.Number(),
203
245
  truncated: t.Boolean()
204
246
  })
@@ -212,6 +254,7 @@ export const memoryCrudHandler = createRouter()
212
254
  sources: data.sources as GraphSource[] | undefined,
213
255
  includeArchived: data.includeArchived,
214
256
  includeSuperseded: data.includeSuperseded,
257
+ region: data.region,
215
258
  limit: data.limit
216
259
  });
217
260
  })
@@ -597,6 +640,11 @@ export const memoryCrudHandler = createRouter()
597
640
  // may now be looking at an empty graph.
598
641
  vectorCache.reset();
599
642
  resetGraphEmptiness();
643
+ // The arrangement describes nodes that are gone. Dropping the orphans now
644
+ // rather than waiting for the next pass is what stops the overview counting
645
+ // lobes whose members no longer exist.
646
+ graphLayoutQueries.pruneOrphans();
647
+ resetGraphLayoutState();
600
648
  notifyGraphChanged('purged', data.projectIds?.[0] ?? null);
601
649
  debug.log('memory', `Purged ${result.nodes} node(s) and ${result.edges} edge(s)`);
602
650
  return result;
@@ -10,6 +10,7 @@
10
10
  import { t } from 'elysia';
11
11
  import { createRouter } from '$shared/utils/ws-server';
12
12
  import { settingsQueries, engineQueries } from '../../database/queries';
13
+ import { SYSTEM_SETTINGS_KEY, writeSystemSettings } from '../../settings/system-settings';
13
14
  import { initializeEngine } from '../../engine';
14
15
  import { checkEngineSetup } from '../../engine/engine-setup';
15
16
  import { registerModels } from '$shared/constants/engines';
@@ -49,6 +50,13 @@ export const crudHandler = createRouter()
49
50
  throw new Error('Key and value are required');
50
51
  }
51
52
 
53
+ if (key === SYSTEM_SETTINGS_KEY) {
54
+ // The system blob is never replaced wholesale — a caller sending a
55
+ // partial copy would silently drop every field it does not know about
56
+ // (that is how the onboarding marker used to disappear). Merge instead.
57
+ throw new Error(`Use settings:update-system to change ${SYSTEM_SETTINGS_KEY}`);
58
+ }
59
+
52
60
  settingsQueries.set(key, value);
53
61
  const setting = settingsQueries.get(key);
54
62
 
@@ -56,34 +64,18 @@ export const crudHandler = createRouter()
56
64
  })
57
65
 
58
66
  // Merge-update system settings (admin only).
59
- // Reads the current `system:settings` blob, merges the provided patch, and
60
- // writes it back atomically. Sending only the changed keys prevents a partial
61
- // update from clobbering sibling fields (e.g. onboardingComplete) when a
62
- // client's in-memory copy of the settings is stale.
67
+ // Sending only the changed keys prevents a partial update from clobbering
68
+ // sibling fields (e.g. the onboarding marker) when a client's in-memory copy
69
+ // of the settings is stale. The merge itself lives in the system-settings
70
+ // module, which is the only writer of that row.
63
71
  .http('settings:update-system', {
64
72
  data: t.Object({
65
73
  patch: t.Record(t.String(), t.Any())
66
74
  }),
67
75
  response: t.Any()
68
76
  }, async ({ data }) => {
69
- const KEY = 'system:settings';
70
- const existing = settingsQueries.get(KEY);
71
-
72
- let current: Record<string, unknown> = {};
73
- if (existing?.value) {
74
- try {
75
- current = typeof existing.value === 'string'
76
- ? JSON.parse(existing.value)
77
- : (existing.value as Record<string, unknown>);
78
- } catch {
79
- current = {};
80
- }
81
- }
82
-
83
- const merged = { ...current, ...data.patch };
84
- settingsQueries.set(KEY, JSON.stringify(merged));
85
-
86
- return settingsQueries.get(KEY);
77
+ writeSystemSettings(data.patch);
78
+ return settingsQueries.get(SYSTEM_SETTINGS_KEY);
87
79
  })
88
80
 
89
81
  // Batch update multiple settings