@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
@@ -3,7 +3,7 @@
3
3
  * High-level git operations built on top of executor and parser
4
4
  */
5
5
 
6
- import { execGit, isGitRepo, getGitRoot } from './git-executor';
6
+ import { execGit, isGitRepo, getGitRoot, type GitExecResult } from './git-executor';
7
7
  import { resolveBinary } from '../utils/cli';
8
8
  import { getCleanSpawnEnv } from '../utils/env';
9
9
  import {
@@ -69,6 +69,32 @@ export class GitService {
69
69
  }
70
70
  }
71
71
 
72
+ // ============================================
73
+ // Revision probes
74
+ // ============================================
75
+
76
+ /**
77
+ * True when the repo has at least one commit.
78
+ *
79
+ * A freshly `git init`ed repo has an unborn HEAD: every HEAD-relative revision
80
+ * (`HEAD`, `HEAD~1`, `HEAD^`) fails to resolve, and git reports it as a raw
81
+ * `fatal: ambiguous argument` / `bad revision`. Callers probe this so they can
82
+ * answer with an actionable message — or skip the operation entirely — instead
83
+ * of leaking that fatal into a toast.
84
+ */
85
+ private async hasCommits(cwd: string): Promise<boolean> {
86
+ return (await execGit(['rev-parse', '--verify', '--quiet', 'HEAD'], cwd)).exitCode === 0;
87
+ }
88
+
89
+ /**
90
+ * True when `ref` has a parent commit — false for a root (parentless) commit,
91
+ * where `<ref>^` / `<ref>~1` cannot resolve even though `<ref>` itself does.
92
+ */
93
+ private async hasParent(cwd: string, ref = 'HEAD'): Promise<boolean> {
94
+ assertSafeGitRevish(ref, 'parent probe ref');
95
+ return (await execGit(['rev-parse', '--verify', '--quiet', `${ref}^`], cwd)).exitCode === 0;
96
+ }
97
+
72
98
  // ============================================
73
99
  // Status
74
100
  // ============================================
@@ -175,6 +201,11 @@ export class GitService {
175
201
  }
176
202
  const result = await execGit(args, cwd);
177
203
  if (result.exitCode !== 0) {
204
+ // Unborn HEAD — git says "You have nothing to amend", which reads like a
205
+ // failure rather than "commit normally instead".
206
+ if (!(await this.hasCommits(cwd))) {
207
+ throw new Error('There is no commit to amend yet — create the first commit instead.');
208
+ }
178
209
  throw new Error(`git commit --amend failed: ${result.stderr}`);
179
210
  }
180
211
  const hashResult = await execGit(['rev-parse', 'HEAD'], cwd);
@@ -212,8 +243,7 @@ export class GitService {
212
243
  // changed". Detect the parentless case and diff against the empty tree via
213
244
  // `diff-tree --root` so the initial commit's files show up as additions.
214
245
  // Commits with a parent (including merges) keep the original behaviour.
215
- const hasParent =
216
- (await execGit(['rev-parse', '--verify', '--quiet', `${commitHash}^`], cwd)).exitCode === 0;
246
+ const hasParent = await this.hasParent(cwd, commitHash);
217
247
  // Fetch the full commit message alongside the diff so the detail view can
218
248
  // render the body. `%s\0%b` splits cleanly on NUL since a subject never
219
249
  // contains one; the body is kept verbatim (it may span many lines).
@@ -460,6 +490,11 @@ export class GitService {
460
490
 
461
491
  const result = await execGit(args, cwd);
462
492
  if (result.exitCode !== 0) {
493
+ // A repo with no commits yet isn't an error — `git log` just has nothing
494
+ // to walk. Report it as an empty history so the UI shows its empty state.
495
+ if (!(await this.hasCommits(cwd))) {
496
+ return { commits: [], total: 0, hasMore: false };
497
+ }
463
498
  throw new Error(`git log failed: ${result.stderr}`);
464
499
  }
465
500
 
@@ -510,6 +545,24 @@ export class GitService {
510
545
  };
511
546
  }
512
547
 
548
+ /**
549
+ * Shape a `git push` outcome. On an unborn HEAD git only reports
550
+ * `src refspec <branch> does not match any`, which reads like a broken remote
551
+ * rather than "there is nothing here to push yet".
552
+ */
553
+ private async describePushResult(
554
+ cwd: string,
555
+ result: GitExecResult
556
+ ): Promise<{ success: boolean; message: string }> {
557
+ if (result.exitCode === 0) {
558
+ return { success: true, message: result.stderr || result.stdout };
559
+ }
560
+ if (!(await this.hasCommits(cwd))) {
561
+ return { success: false, message: 'This branch has no commits yet, so there is nothing to push.' };
562
+ }
563
+ return { success: false, message: result.stderr };
564
+ }
565
+
513
566
  async push(cwd: string, remote = 'origin', branch?: string, force = false): Promise<{ success: boolean; message: string }> {
514
567
  assertSafeGitRemoteName(remote);
515
568
  const args = ['push', remote];
@@ -520,11 +573,7 @@ export class GitService {
520
573
  if (force) args.push('--force-with-lease');
521
574
  // Set upstream if needed
522
575
  args.push('-u');
523
- const result = await execGit(args, cwd, 60000);
524
- return {
525
- success: result.exitCode === 0,
526
- message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
527
- };
576
+ return this.describePushResult(cwd, await execGit(args, cwd, 60000));
528
577
  }
529
578
 
530
579
  /**
@@ -554,11 +603,7 @@ export class GitService {
554
603
  else if (mode === 'force') args.push('--force');
555
604
  args.push('-u');
556
605
  }
557
- const result = await execGit(args, cwd, 60000);
558
- return {
559
- success: result.exitCode === 0,
560
- message: result.exitCode === 0 ? (result.stderr || result.stdout) : result.stderr
561
- };
606
+ return this.describePushResult(cwd, await execGit(args, cwd, 60000));
562
607
  }
563
608
 
564
609
  /** Fetch every configured remote and prune deleted remote-tracking refs. */
@@ -637,6 +682,10 @@ export class GitService {
637
682
  'Stashing staged changes only requires Git 2.35 or newer. Please update Git to use this option.'
638
683
  );
639
684
  }
685
+ // Stashing needs a commit to record the base state against.
686
+ if (!(await this.hasCommits(cwd))) {
687
+ throw new Error('Stashing requires at least one commit — create the first commit first.');
688
+ }
640
689
  throw new Error(`git stash failed: ${result.stderr}`);
641
690
  }
642
691
  }
@@ -868,12 +917,55 @@ export class GitService {
868
917
  * - `soft` keeps the changes staged
869
918
  * - `mixed` keeps the changes in the working tree (unstaged)
870
919
  * - `hard` discards the changes entirely (destructive)
920
+ *
921
+ * The root commit has no `HEAD~1` to reset onto, so undoing it means deleting
922
+ * the branch ref itself: `update-ref -d HEAD` returns the repo to the unborn
923
+ * state while leaving the index intact — which is exactly `--soft`. `--mixed`
924
+ * and `--hard` then unwind the index (and working tree) from there.
871
925
  */
872
926
  async undoLastCommit(cwd: string, mode: 'soft' | 'mixed' | 'hard'): Promise<void> {
873
- const flag = mode === 'soft' ? '--soft' : mode === 'hard' ? '--hard' : '--mixed';
874
- const result = await execGit(['reset', flag, 'HEAD~1'], cwd);
875
- if (result.exitCode !== 0) {
876
- throw new Error(`git reset ${flag} failed: ${result.stderr}`);
927
+ if (!(await this.hasCommits(cwd))) {
928
+ throw new Error('This repository has no commits yet, so there is nothing to undo.');
929
+ }
930
+
931
+ if (await this.hasParent(cwd)) {
932
+ const flag = mode === 'soft' ? '--soft' : mode === 'hard' ? '--hard' : '--mixed';
933
+ const result = await execGit(['reset', flag, 'HEAD~1'], cwd);
934
+ if (result.exitCode !== 0) {
935
+ throw new Error(`git reset ${flag} failed: ${result.stderr}`);
936
+ }
937
+ return;
938
+ }
939
+
940
+ // Root commit. `--hard` must discard the working tree while HEAD still
941
+ // resolves — once the ref is gone there is no commit left to reset onto.
942
+ if (mode === 'hard') {
943
+ const discard = await execGit(['reset', '--hard', 'HEAD'], cwd);
944
+ if (discard.exitCode !== 0) {
945
+ throw new Error(`git reset --hard failed: ${discard.stderr}`);
946
+ }
947
+ }
948
+
949
+ const removeRef = await execGit(['update-ref', '-d', 'HEAD'], cwd);
950
+ if (removeRef.exitCode !== 0) {
951
+ throw new Error(`git update-ref -d HEAD failed: ${removeRef.stderr}`);
952
+ }
953
+
954
+ if (mode === 'mixed') {
955
+ // Drop the index so the commit's files come back as untracked changes.
956
+ const unstage = await execGit(['reset'], cwd);
957
+ if (unstage.exitCode !== 0) {
958
+ throw new Error(`git reset failed: ${unstage.stderr}`);
959
+ }
960
+ } else if (mode === 'hard') {
961
+ // Delete exactly what the commit tracked — unrelated untracked files
962
+ // survive, matching `reset --hard HEAD~1` on a non-root commit. The
963
+ // `:/` pathspec covers the whole work tree even when cwd is a subdir,
964
+ // and `--ignore-unmatch` keeps an empty root commit from erroring.
965
+ const clearIndex = await execGit(['rm', '-rf', '--quiet', '--ignore-unmatch', '--', ':/'], cwd);
966
+ if (clearIndex.exitCode !== 0) {
967
+ throw new Error(`git rm failed: ${clearIndex.stderr}`);
968
+ }
877
969
  }
878
970
  }
879
971
 
@@ -881,6 +973,10 @@ export class GitService {
881
973
  async revertCommit(cwd: string, ref = 'HEAD'): Promise<{ success: boolean; message: string }> {
882
974
  assertSafeGitRevish(ref, 'revert ref');
883
975
  const result = await execGit(['revert', '--no-edit', ref], cwd);
976
+ if (result.exitCode !== 0 && !(await this.hasCommits(cwd))) {
977
+ // Unborn HEAD — git only reports `bad revision 'HEAD'`.
978
+ return { success: false, message: 'This repository has no commits yet, so there is nothing to revert.' };
979
+ }
884
980
  return {
885
981
  success: result.exitCode === 0,
886
982
  message: result.exitCode === 0 ? (result.stdout || result.stderr) : result.stderr
package/backend/index.ts CHANGED
@@ -27,6 +27,7 @@ import { bootstrapAfterDbInit } from './bootstrap';
27
27
  import { disposeAllEngines } from './engine';
28
28
  import { connectionManager } from './db-client/connection-manager';
29
29
  import { refreshProcessPath } from './utils/path-enrich';
30
+ import { installProcessWarningFilter } from './utils/process-warnings';
30
31
  import { debug } from '$shared/utils/logger';
31
32
  import { networkInterfaces } from 'os';
32
33
  import { resolve } from 'node:path';
@@ -50,7 +51,7 @@ import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAut
50
51
 
51
52
  // Auth middleware
52
53
  import { checkRouteAccess, PUBLIC_ROUTES } from './auth/permissions';
53
- import { getAuthMode } from './auth/auth-service';
54
+ import { getAuthMode } from './settings/system-settings';
54
55
  import { authQueries } from './database/queries';
55
56
  import { authRateLimiter } from './auth';
56
57
  import { sessionCleanupScheduler } from './auth/session-cleanup';
@@ -232,10 +233,15 @@ async function startServer() {
232
233
  debug.warn('path', '⚠️ Initial PATH enrichment failed:', error);
233
234
  }
234
235
 
235
- // Initialize database first before accepting connections
236
+ // Initialize database first before accepting connections.
237
+ //
238
+ // A failure here is fatal on purpose. Serving requests without a database
239
+ // means every settings read fails, and callers that fall back to defaults
240
+ // report a configured instance as unconfigured — an empty project list, an
241
+ // unfinished setup wizard. Refusing to start is both louder and safer.
236
242
  try {
237
243
  await initializeDatabase();
238
- debug.log('database', '✅ Database initialized successfully');
244
+ debug.log('database', `✅ Database initialized successfully (data dir: ${SERVER_ENV.DATA_DIR})`);
239
245
  // Re-establish code-defined built-ins that live outside migrations/seeders
240
246
  // (internal MCP servers like Browser Automation + the default engine).
241
247
  // Shared with the clear-data handler so a DB wipe on the live process
@@ -245,7 +251,9 @@ async function startServer() {
245
251
  sessionCleanupScheduler.start();
246
252
  uploadTempCleanup.start();
247
253
  } catch (error) {
248
- debug.warn('database', '⚠️ Database initialization failed:', error);
254
+ console.error('❌ Database initialization failed — refusing to start:', error);
255
+ console.error(` Data directory: ${SERVER_ENV.DATA_DIR}`);
256
+ process.exit(1);
249
257
  }
250
258
 
251
259
  // Start listening after database is ready
@@ -374,6 +382,10 @@ globalThis.addEventListener('unhandledrejection', (event: PromiseRejectionEvent)
374
382
  reportUnhandledRejection(event.reason);
375
383
  });
376
384
 
385
+ // Owns every `process.emitWarning` line in the server log (see the module for
386
+ // why registering a listener means we must re-print what we keep).
387
+ installProcessWarningFilter();
388
+
377
389
  process.on('uncaughtException', (error) => {
378
390
  try {
379
391
  debug.error('server', 'Uncaught exception (server still running):', error);
@@ -13,7 +13,8 @@ import { randomUUID } from 'node:crypto';
13
13
 
14
14
  import { handleMcpRequest } from './remote-server';
15
15
  import { getMcpServiceToken } from './service-token';
16
- import { authQueries, settingsQueries } from '../../database/queries';
16
+ import { authQueries } from '../../database/queries';
17
+ import { writeSystemSettings } from '../../settings/system-settings';
17
18
  import { generatePAT, generateSessionToken, hashToken } from '../../auth/tokens';
18
19
  import { initializeDatabase, closeDatabase, getDatabase } from '../../database';
19
20
 
@@ -22,7 +23,11 @@ let sessionToken: string;
22
23
  let patToken: string;
23
24
 
24
25
  function setAuthMode(mode: 'none' | 'required'): void {
25
- settingsQueries.set('system:settings', JSON.stringify({ authMode: mode }));
26
+ // Merge rather than replace: the system settings blob holds unrelated state
27
+ // (the onboarding marker, admin limits) and a test must never be able to drop
28
+ // it — the data directory is isolated under NODE_ENV=test, but the habit is
29
+ // what keeps it isolated if that ever changes.
30
+ writeSystemSettings({ authMode: mode });
26
31
  }
27
32
 
28
33
  function sessionCount(userId: string): number {
@@ -80,7 +85,7 @@ beforeAll(async () => {
80
85
  afterAll(() => {
81
86
  authQueries.deleteSessionsByUserId(testUserId);
82
87
  authQueries.deleteUser(testUserId);
83
- settingsQueries.set('system:settings', JSON.stringify({ authMode: 'required' }));
88
+ setAuthMode('required');
84
89
  closeDatabase();
85
90
  });
86
91
 
@@ -23,7 +23,7 @@ import { createExternalProxyServer } from '../external/proxy';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { authQueries } from '$backend/database/queries';
25
25
  import { hashToken } from '$backend/auth/tokens';
26
- import { getAuthMode } from '$backend/auth/auth-service';
26
+ import { getAuthMode } from '$backend/settings/system-settings';
27
27
  import { isMcpServiceToken } from './service-token';
28
28
  import type { EngineType } from '$shared/types/unified';
29
29
 
@@ -20,6 +20,7 @@ import { notifyMemoryReadiness } from './notify';
20
20
  import { resetGraphEmptiness } from './context';
21
21
  import { reconcileVectorIndex } from './indexer';
22
22
  import { startMemoryMaintenance } from './maintenance';
23
+ import { resetGraphLayoutState, scheduleGraphLayout } from './layout';
23
24
  import { ensureMemoryModel } from './model';
24
25
  import { startExtractionRunner } from './extract';
25
26
 
@@ -42,6 +43,14 @@ export function bootstrapMemoryGraph(): void {
42
43
  vectorCache.reset();
43
44
  resetGraphEmptiness();
44
45
 
46
+ // Same reason as the caches above: "Clear All Data" wipes the database under a
47
+ // live process, so what the last pass laid out describes rows that no longer
48
+ // exist. Scheduling one here is also what places an EXISTING graph the first
49
+ // time the upgrade runs — until it lands the view falls back to the flat
50
+ // listing it always used, so nothing is missing meanwhile.
51
+ resetGraphLayoutState();
52
+ scheduleGraphLayout();
53
+
45
54
  // Duplicate collapse and retention are pure SQL and are worth running whether
46
55
  // or not the artifact ever lands, so maintenance starts independently of the
47
56
  // download. Its own first tick is minutes away, well clear of startup.