@myrialabs/clopen 0.4.37 → 0.4.38

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 (101) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +14 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/database/crypto/envelope.test.ts +93 -0
  5. package/backend/database/crypto/envelope.ts +127 -0
  6. package/backend/database/crypto/index.ts +22 -0
  7. package/backend/database/crypto/master-key.ts +129 -0
  8. package/backend/database/crypto/secret-columns.ts +147 -0
  9. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  10. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  11. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  12. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  13. package/backend/database/migrations/index.ts +28 -0
  14. package/backend/database/queries/db-client-connection-queries.ts +23 -12
  15. package/backend/database/queries/engine-queries.ts +23 -10
  16. package/backend/database/queries/index.ts +6 -1
  17. package/backend/database/queries/integration-queries.ts +297 -0
  18. package/backend/database/queries/mcp-server-queries.ts +38 -11
  19. package/backend/database/queries/note-queries.test.ts +190 -0
  20. package/backend/database/queries/note-queries.ts +269 -0
  21. package/backend/database/queries/profile-queries.ts +1 -1
  22. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  23. package/backend/database/queries/work-queries.ts +210 -0
  24. package/backend/engine/docs/artifacts.md +22 -9
  25. package/backend/files/os-clipboard.test.ts +209 -0
  26. package/backend/files/os-clipboard.ts +567 -0
  27. package/backend/http/integration-hooks.ts +42 -0
  28. package/backend/http/notes-images.test.ts +228 -0
  29. package/backend/http/notes-images.ts +196 -0
  30. package/backend/index.ts +9 -0
  31. package/backend/integrations/accounts.ts +229 -0
  32. package/backend/integrations/health.ts +146 -0
  33. package/backend/integrations/index.ts +36 -0
  34. package/backend/integrations/projections/index.ts +120 -0
  35. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  36. package/backend/integrations/projections/mcp-projector.ts +159 -0
  37. package/backend/integrations/projections/types.ts +51 -0
  38. package/backend/integrations/registry/define.ts +38 -0
  39. package/backend/integrations/registry/index.ts +56 -0
  40. package/backend/integrations/registry/providers/context7.ts +44 -0
  41. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  42. package/backend/integrations/registry/providers/github.ts +78 -0
  43. package/backend/integrations/registry/types.ts +96 -0
  44. package/backend/integrations/webhooks/gateway.ts +160 -0
  45. package/backend/integrations/webhooks/verify.ts +65 -0
  46. package/backend/mcp/README.md +25 -3
  47. package/backend/mcp/external/config.ts +35 -1
  48. package/backend/mcp/index.ts +1 -1
  49. package/backend/mcp/internal/config.ts +1 -1
  50. package/backend/notes/access.test.ts +82 -0
  51. package/backend/notes/access.ts +27 -0
  52. package/backend/notes/storage.test.ts +77 -0
  53. package/backend/notes/storage.ts +114 -0
  54. package/backend/permissions/service.ts +2 -2
  55. package/backend/profiles/service.ts +1 -1
  56. package/backend/projects/project-cleanup.ts +6 -0
  57. package/backend/work/bindings.ts +124 -0
  58. package/backend/work/index.ts +42 -0
  59. package/backend/work/prompts.ts +150 -0
  60. package/backend/work/providers/github/actions-logs.ts +180 -0
  61. package/backend/work/providers/github/adapter.test.ts +88 -0
  62. package/backend/work/providers/github/adapter.ts +1255 -0
  63. package/backend/work/providers/github/client.ts +280 -0
  64. package/backend/work/providers/github/list-range.test.ts +158 -0
  65. package/backend/work/providers/github/token-kind.test.ts +42 -0
  66. package/backend/work/pull-requests.ts +242 -0
  67. package/backend/work/registry.ts +27 -0
  68. package/backend/work/service.ts +436 -0
  69. package/backend/work/start-work.test.ts +71 -0
  70. package/backend/work/start-work.ts +232 -0
  71. package/backend/work/types.ts +180 -0
  72. package/backend/ws/files/clipboard.ts +78 -0
  73. package/backend/ws/files/index.ts +5 -0
  74. package/backend/ws/git/diff-budget.ts +70 -11
  75. package/backend/ws/index.ts +11 -1
  76. package/backend/ws/integrations/crud.ts +219 -0
  77. package/backend/ws/integrations/index.ts +22 -0
  78. package/backend/ws/mcp/crud.ts +25 -1
  79. package/backend/ws/notes/index.ts +278 -0
  80. package/backend/ws/profiles/crud.ts +1 -1
  81. package/backend/ws/work/actions.ts +206 -0
  82. package/backend/ws/work/context.ts +51 -0
  83. package/backend/ws/work/crud.ts +347 -0
  84. package/backend/ws/work/index.ts +17 -0
  85. package/backend/ws/work/pull-requests.ts +177 -0
  86. package/backend/ws/work/schemas.ts +226 -0
  87. package/dist/assets/{index-sJmS_CCm.js → index-CyH7fSbR.js} +1 -1
  88. package/dist/assets/{index-Bik9TCBi.js → index-DSHIANSy.js} +1 -1
  89. package/dist/assets/main-D2IOjftb.css +1 -0
  90. package/dist/assets/main-DM-tHKbW.js +1152 -0
  91. package/dist/index.html +2 -2
  92. package/package.json +1 -1
  93. package/shared/constants/engine-tools.ts +1 -1
  94. package/shared/constants/tool-icons.ts +33 -0
  95. package/shared/types/database/schema.ts +41 -0
  96. package/shared/types/integrations.ts +140 -0
  97. package/shared/types/stores/settings.ts +8 -0
  98. package/shared/types/work.ts +426 -0
  99. package/shared/utils/logger.ts +3 -0
  100. package/dist/assets/main-DLqolBI2.css +0 -1
  101. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -6,7 +6,7 @@ disk and in their namespace keys:
6
6
  | | **Internal** (`internal/`) | **External** (`external/`) |
7
7
  |---|---|---|
8
8
  | What | Custom tools defined in code via `defineServer()` | Servers the user installs from the official MCP registry |
9
- | Managed | By developers (this README) | By users in **Settings → MCP** |
9
+ | Managed | By developers (this README) | By users in **Settings → Integrations** |
10
10
  | Stored | In code (`internal/servers/`) | In the DB (`mcp_servers` table) |
11
11
  | Namespace | `clopen-mcp` bridge (non-Claude) / server name (Claude) | one bare `<slug>` per server (no prefix) |
12
12
  | Execution | In-process (no subprocess) | Engine connects to Clopen's `/mcp/ext/<slug>` proxy; Clopen connects to the real upstream (stdio subprocess or remote HTTP) |
@@ -19,6 +19,27 @@ The rest of this document covers the **internal** custom-tool system. External
19
19
  servers need no code — see `external/registry-client.ts`, `external/config.ts`,
20
20
  and `external/proxy.ts` (the per-server `/mcp/ext/<slug>` proxy bridge).
21
21
 
22
+ ### Where `backend/integrations/` fits
23
+
24
+ MCP is a **protocol**; an integration is a **credential with capabilities**.
25
+ They are separate modules on purpose, and `backend/integrations/` is the newer
26
+ of the two:
27
+
28
+ - `backend/mcp/` owns installing, proxying, per-engine tool exposure and
29
+ MCP-level OAuth. It knows nothing about accounts.
30
+ - `backend/integrations/` owns the account and its credential. One of the
31
+ capabilities an account can offer — `agent-tools` — **projects** a row into
32
+ `mcp_servers`, which is the only place the two meet.
33
+
34
+ That direction matters. A projected row is read by `resolveServerRow()` and by
35
+ every per-engine config builder exactly as a hand-installed one is, so nothing
36
+ in this subsystem has to know accounts exist. And most integrations project no
37
+ MCP server at all — a database provider projects a `db_client_connections` row,
38
+ a chat provider registers a notification channel.
39
+
40
+ Both appear under one UI, **Settings → Integrations**, which absorbed the old
41
+ Connectors section.
42
+
22
43
  > **External servers are proxied, not direct.** Engines never connect straight
23
44
  > to a third-party MCP server. Clopen connects to it (as an MCP client) and
24
45
  > re-exposes its **sanitized** tools through a per-server endpoint on the same
@@ -199,7 +220,7 @@ backend/mcp/
199
220
  │ ├── types.ts # CatalogServer / ResolvedExternalServer
200
221
  │ ├── registry-client.ts # Fetch + normalise registry.modelcontextprotocol.io
201
222
  │ ├── proxy.ts # `/mcp/ext/<slug>` proxy: Clopen ↔ upstream, schema sanitiser
202
- │ ├── probe.ts # Connection health probe (Settings → MCP status)
223
+ │ ├── probe.ts # Connection health probe (Settings → Integrations status)
203
224
  │ ├── oauth.ts # Centralized OAuth (discovery + dynamic reg + PKCE)
204
225
  │ └── config.ts # Per-engine builders (bridge URL, bare <slug>) + resolveExternalToolName
205
226
  └── README.md # This file
@@ -1305,7 +1326,8 @@ checklist in `backend/engine/README.md` §10.12. The summary:
1305
1326
 
1306
1327
  Everything above describes **internal** custom tools (the `clopen-mcp`
1307
1328
  bridge). **External** servers are the ones a user installs from the official
1308
- registry (Settings → MCP → Browse), stored in the `mcp_servers` table.
1329
+ registry (Settings → Integrations → Add → Browse the MCP registry), stored in
1330
+ the `mcp_servers` table.
1309
1331
 
1310
1332
  ### Proxied through the bridge (not direct)
1311
1333
 
@@ -110,7 +110,7 @@ export function getEnabledExternalServers(profileFilter?: Set<string>): Resolved
110
110
  //
111
111
  // When a Profile is active it is the source of truth for which connectors run:
112
112
  // a connector it references is emitted even if globally disabled in the
113
- // Connectors settings, and the global enable toggle is ignored. Without a
113
+ // Integrations settings, and the global enable toggle is ignored. Without a
114
114
  // profile filter, only enabled servers apply (unchanged).
115
115
  const rows = profileFilter ? mcpServerQueries.getAll() : mcpServerQueries.getEnabled();
116
116
  return rows
@@ -268,3 +268,37 @@ function logBuilt(engine: string, out: Record<string, unknown>): void {
268
268
  const count = Object.keys(out).length;
269
269
  if (count > 0) debug.log('mcp', `🧩 ${engine} external MCP: ${count} server(s)`);
270
270
  }
271
+
272
+ /**
273
+ * The config each engine is handed for ONE external server, keyed by engine.
274
+ *
275
+ * Surfaced in the Integrations detail view. It exists because "what does the
276
+ * engine actually receive" is otherwise unanswerable from the UI: every server,
277
+ * whatever its real transport, is emitted as a Streamable-HTTP remote pointing
278
+ * at the `/mcp/ext/<slug>` proxy, so the row a user configured and the config an
279
+ * engine sees do not look alike. Showing the row and calling it the engine's
280
+ * config would be a lie of omission.
281
+ *
282
+ * Returns `{}` for a server that is disabled or unknown — the honest answer,
283
+ * since a disabled server is handed to nobody.
284
+ */
285
+ export function getEngineConfigsForServer(slug: string): Record<string, unknown> {
286
+ const namespace = externalNamespace(slug);
287
+ const pick = (config: Record<string, unknown>): unknown => config[namespace];
288
+
289
+ const out: Record<string, unknown> = {};
290
+ const builders: Record<string, () => Record<string, unknown>> = {
291
+ 'claude-code': () => getClaudeExternalMcpConfig() as Record<string, unknown>,
292
+ opencode: () => getOpenCodeExternalMcpConfig() as Record<string, unknown>,
293
+ codex: () => getCodexExternalMcpConfig() as Record<string, unknown>,
294
+ copilot: () => getCopilotExternalMcpConfig() as Record<string, unknown>,
295
+ cursor: () => getCursorExternalMcpConfig() as Record<string, unknown>,
296
+ qwen: () => getQwenExternalMcpConfig() as Record<string, unknown>
297
+ };
298
+
299
+ for (const [engine, build] of Object.entries(builders)) {
300
+ const config = pick(build());
301
+ if (config !== undefined) out[engine] = config;
302
+ }
303
+ return out;
304
+ }
@@ -75,7 +75,7 @@ export {
75
75
 
76
76
  // External catalog + types (used by the WS layer and Settings → MCP)
77
77
  export { listRegistryServers, mapRegistryServer } from './external/registry-client';
78
- export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth } from './external/config';
78
+ export { getEnabledExternalServers, resolveServerRow, remoteNeedsOAuth, getEngineConfigsForServer } from './external/config';
79
79
  export { listExternalServerTools, callExternalServerTool } from './external/proxy';
80
80
  export { parseToolOverrides, resolveToolExposure, pruneToolOverrides, MCP_ENGINES } from './external/tools';
81
81
  export type { ToolExposure } from './external/tools';
@@ -289,7 +289,7 @@ export function getEnabledServerNames(): string[] {
289
289
  * Internal server names ACTIVE for a stream. When a Profile is active, its
290
290
  * referenced connector set is the source of truth — a referenced internal server
291
291
  * counts even if globally disabled, and one NOT referenced is excluded (built-in
292
- * connectors appear in the profile's Connectors picker, so this is an explicit
292
+ * connectors appear in the profile's Integrations picker, so this is an explicit
293
293
  * choice). Without a profile, every globally-enabled server is active (unchanged).
294
294
  */
295
295
  export function activeInternalServerNames(profileFilter?: Set<string>): string[] {
@@ -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
+ }
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Tests for the note attachment path contract.
3
+ *
4
+ * The reason these exist: `note_images.storage_path` used to be an absolute
5
+ * path, which pinned every attachment to the machine and OS that uploaded it.
6
+ * The rules below are what make a `~/.clopen` portable between a `CLOPEN_DATA_DIR`
7
+ * move and between platforms, so they are pinned rather than left to review.
8
+ */
9
+
10
+ import { describe, it, expect } from 'bun:test';
11
+ import { join, isAbsolute } from 'node:path';
12
+
13
+ import {
14
+ getNotesRootDir,
15
+ noteImageRelPath,
16
+ resolveNoteImagePath,
17
+ sanitizeImageFileName
18
+ } from './storage';
19
+
20
+ describe('noteImageRelPath', () => {
21
+ it('is relative and POSIX-separated so the row survives a move between platforms', () => {
22
+ const rel = noteImageRelPath('coll-1', 'note-1', 'abc-photo.png');
23
+ expect(rel).toBe('notes/coll-1/note-1/abc-photo.png');
24
+ expect(isAbsolute(rel)).toBe(false);
25
+ expect(rel).not.toContain('\\');
26
+ });
27
+ });
28
+
29
+ describe('resolveNoteImagePath', () => {
30
+ it('resolves a stored relative path under the current data dir', () => {
31
+ const rel = noteImageRelPath('coll-1', 'note-1', 'abc-photo.png');
32
+ expect(resolveNoteImagePath(rel)).toBe(join(getNotesRootDir(), 'coll-1', 'note-1', 'abc-photo.png'));
33
+ });
34
+
35
+ it('still resolves an absolute path written before the relative format', () => {
36
+ const absolute = join(getNotesRootDir(), 'coll-1', 'note-1', 'legacy.png');
37
+ expect(resolveNoteImagePath(absolute)).toBe(absolute);
38
+ });
39
+
40
+ it('refuses a path that escapes the notes root', () => {
41
+ expect(resolveNoteImagePath('notes/../../.ssh/id_rsa')).toBeNull();
42
+ expect(resolveNoteImagePath('../../../etc/passwd')).toBeNull();
43
+ expect(resolveNoteImagePath('/etc/passwd')).toBeNull();
44
+ });
45
+
46
+ it('refuses an empty path rather than resolving to the data dir', () => {
47
+ expect(resolveNoteImagePath('')).toBeNull();
48
+ });
49
+ });
50
+
51
+ describe('sanitizeImageFileName', () => {
52
+ it('keeps only characters that are legal on every platform', () => {
53
+ expect(sanitizeImageFileName('my photo (1).png')).toBe('my_photo__1_.png');
54
+ expect(sanitizeImageFileName('re:port|v2*.jpg')).toBe('re_port_v2_.jpg');
55
+ });
56
+
57
+ it('strips any directory component from both separator styles', () => {
58
+ expect(sanitizeImageFileName('../../etc/passwd')).toBe('passwd');
59
+ expect(sanitizeImageFileName('C:\\Users\\me\\shot.png')).toBe('shot.png');
60
+ });
61
+
62
+ it('drops trailing dots and spaces, which Windows removes behind our back', () => {
63
+ // A stored `shot.png.` would leave the row pointing at a name the OS
64
+ // never actually wrote.
65
+ expect(sanitizeImageFileName('shot.png.')).toBe('shot.png');
66
+ expect(sanitizeImageFileName('shot.png ')).toBe('shot.png');
67
+ });
68
+
69
+ it('caps the length so the full path stays under the Windows 260-char limit', () => {
70
+ expect(sanitizeImageFileName(`${'a'.repeat(400)}.png`).length).toBeLessThanOrEqual(64);
71
+ });
72
+
73
+ it('never returns an empty name', () => {
74
+ expect(sanitizeImageFileName('')).toBe('image');
75
+ expect(sanitizeImageFileName('...')).toBe('image');
76
+ });
77
+ });
@@ -0,0 +1,114 @@
1
+ /**
2
+ * On-disk storage for note image attachments.
3
+ *
4
+ * Files live at `<DATA_DIR>/notes/<collectionId>/<noteId>/<uuid>-<name>`, but
5
+ * `note_images.storage_path` holds that location *relative* to the data dir,
6
+ * with forward slashes. An absolute path would pin every attachment to the
7
+ * machine that uploaded it: `CLOPEN_DATA_DIR` is a supported override, and a
8
+ * `~/.clopen` copied from macOS to Windows would carry `/Users/...` paths that
9
+ * resolve nowhere on the target. Relative + POSIX separators survives both.
10
+ */
11
+
12
+ import { join, resolve } from 'node:path';
13
+ import { rm } from 'node:fs/promises';
14
+
15
+ import { getClopenDir } from '../utils/paths';
16
+ import { noteCollectionQueries } from '../database/queries/note-queries';
17
+ // One exported implementation already lives with the worktree paths; notes
18
+ // resolve the same class of "is this inside the directory I own" question.
19
+ import { isPathInside } from '../worktrees/paths';
20
+
21
+ /**
22
+ * Longest attachment file name kept after sanitizing.
23
+ *
24
+ * Windows still caps a full path at 260 characters by default. The rest of an
25
+ * attachment path costs roughly 150 (data dir + `notes` + two UUID directories
26
+ * + the UUID prefix), so anything past 64 risks an upload that succeeds on
27
+ * macOS and Linux and fails on Windows with ENAMETOOLONG.
28
+ */
29
+ const MAX_FILE_NAME_LENGTH = 64;
30
+
31
+ /** Root that holds every note attachment of every project. */
32
+ export function getNotesRootDir(): string {
33
+ return join(getClopenDir(), 'notes');
34
+ }
35
+
36
+ /** Directory that holds one collection's note attachments. */
37
+ export function getCollectionNotesDir(collectionId: string): string {
38
+ return join(getNotesRootDir(), collectionId);
39
+ }
40
+
41
+ /** Directory that holds one note's attachments. */
42
+ export function getNoteDir(collectionId: string, noteId: string): string {
43
+ return join(getCollectionNotesDir(collectionId), noteId);
44
+ }
45
+
46
+ /**
47
+ * Reduce a client-supplied name to something safe on every filesystem.
48
+ *
49
+ * Windows rejects `<>:"/\|?*` and silently drops trailing dots and spaces — a
50
+ * dropped trailing dot would leave the database pointing at a file name the OS
51
+ * never wrote. Reserved device names (CON, NUL, …) can't occur because the
52
+ * stored name is always prefixed with the image UUID.
53
+ */
54
+ export function sanitizeImageFileName(name: string): string {
55
+ const flattened = name.split(/[\\/]/).pop() ?? '';
56
+ // Trailing dots and spaces go before the character replacement, not after:
57
+ // afterwards a trailing space is already an underscore and would survive.
58
+ const trimmed = flattened.replace(/[.\s]+$/, '').trim();
59
+ const cleaned = trimmed
60
+ .replace(/[^a-zA-Z0-9._-]/g, '_')
61
+ .slice(0, MAX_FILE_NAME_LENGTH)
62
+ // The length cap can land on a dot, which puts one back at the end.
63
+ .replace(/\.+$/, '');
64
+ return cleaned || 'image';
65
+ }
66
+
67
+ /** The value to persist in `note_images.storage_path`. */
68
+ export function noteImageRelPath(collectionId: string, noteId: string, fileName: string): string {
69
+ return `notes/${collectionId}/${noteId}/${fileName}`;
70
+ }
71
+
72
+ /**
73
+ * Turn a stored path back into an absolute one under the current data dir.
74
+ *
75
+ * Returns null when the value escapes the notes root — a stored path is always
76
+ * server-generated, so an escape means the row was tampered with and the read
77
+ * must not fall through to an arbitrary file.
78
+ */
79
+ export function resolveNoteImagePath(storagePath: string): string | null {
80
+ if (!storagePath) return null;
81
+ const absolute = storagePath.startsWith('/') || /^[A-Za-z]:[\\/]/.test(storagePath)
82
+ ? resolve(storagePath)
83
+ : resolve(join(getClopenDir(), ...storagePath.split('/')));
84
+ return isPathInside(getNotesRootDir(), absolute) ? absolute : null;
85
+ }
86
+
87
+ /** Remove one note's attachment directory. Best-effort: never throws. */
88
+ export async function removeNoteFiles(collectionId: string, noteId: string): Promise<void> {
89
+ await rm(getNoteDir(collectionId, noteId), { recursive: true, force: true }).catch(() => {});
90
+ }
91
+
92
+ /** Remove one collection's attachment directory. Best-effort: never throws. */
93
+ export async function removeCollectionFiles(collectionId: string): Promise<void> {
94
+ const root = getNotesRootDir();
95
+ const dir = getCollectionNotesDir(collectionId);
96
+ // The directory is derived from the id, so an empty or traversing id would
97
+ // aim this recursive delete at the notes root itself.
98
+ if (dir === root || !isPathInside(root, dir)) return;
99
+ await rm(dir, { recursive: true, force: true }).catch(() => {});
100
+ }
101
+
102
+ /**
103
+ * Remove every attachment belonging to a project's note collections.
104
+ *
105
+ * Deleting the project cascades the collections, notes and image rows away, so
106
+ * without this the files would have no row left to point at them and would sit
107
+ * in the data dir until the user found them by hand. Runs before the project
108
+ * row is deleted, while the collection ids can still be resolved.
109
+ */
110
+ export async function removeProjectNotes(projectId: string): Promise<void> {
111
+ for (const collectionId of noteCollectionQueries.idsByProject(projectId)) {
112
+ await removeCollectionFiles(collectionId);
113
+ }
114
+ }
@@ -5,7 +5,7 @@
5
5
  *
6
6
  * The inventory (what the UI offers as allow/deny targets) is the union of:
7
7
  * - built-in engine tools ({@link ENGINE_BUILTIN_TOOLS}),
8
- * - live MCP tools from enabled Connectors (best-effort; a server that fails to
8
+ * - live MCP tools from enabled connectors (best-effort; a server that fails to
9
9
  * connect is simply skipped),
10
10
  * - tool names named by subagent allowlists.
11
11
  */
@@ -142,7 +142,7 @@ export const permissionService = {
142
142
  const tools = await listExternalServerTools(server.slug);
143
143
  // Claude-style namespaced name (`mcp__<namespace>__<tool>`) — the form
144
144
  // the authoritative Claude hook sees. MCP exposure is primarily
145
- // governed by Connectors (Prompt 2); these are a belt-and-suspenders
145
+ // governed by Integrations (Prompt 2); these are a belt-and-suspenders
146
146
  // deny target.
147
147
  for (const tool of tools) mcpSet.add(`mcp__${server.namespace}__${tool.name}`);
148
148
  } catch (error) {
@@ -3,7 +3,7 @@
3
3
  * resolution consumed by the artifact/MCP sync path.
4
4
  *
5
5
  * A Profile is a reusable, named set of references to existing artifacts
6
- * (Skills, Commands, Subagents, MCP Connectors). It NARROWS which of the
6
+ * (Skills, Commands, Subagents, Integrations). It NARROWS which of the
7
7
  * instance-global artifacts are active for a session, without duplicating any
8
8
  * artifact data — `profile_items` only stores slugs.
9
9
  *
@@ -7,6 +7,7 @@ import { fileWatcher } from '../files/file-watcher';
7
7
  import { clearProjectPresence } from '../project/status-manager';
8
8
  import { registerProjectCleanup } from './project-cleanup-registry';
9
9
  import { removeProjectWorktrees } from '../worktrees';
10
+ import { removeProjectNotes } from '../notes/storage';
10
11
 
11
12
  registerProjectCleanup({
12
13
  name: 'engine',
@@ -36,3 +37,8 @@ registerProjectCleanup({
36
37
  name: 'worktrees',
37
38
  run: (projectId) => removeProjectWorktrees(projectId)
38
39
  });
40
+
41
+ registerProjectCleanup({
42
+ name: 'notes',
43
+ run: (projectId) => removeProjectNotes(projectId)
44
+ });
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Which remote project a Clopen project is looking at.
3
+ *
4
+ * The binding is discovered rather than asked for. A project that pushes to
5
+ * `git@github.com:acme/web.git` and has a GitHub account connected already
6
+ * answered the question, and making the user pick from a list of their 200
7
+ * repositories to say what `git remote -v` says is exactly the kind of setup
8
+ * step that makes an integration feel like homework.
9
+ *
10
+ * Detection is recorded as detection (`detected: true`) so the UI can say where
11
+ * the answer came from, and it is always overridable — a monorepo whose issues
12
+ * live in a different repository is a real, ordinary case.
13
+ */
14
+
15
+ import { gitService } from '$backend/git/git-service';
16
+ import {
17
+ integrationAccountQueries,
18
+ workBindingQueries,
19
+ parseBindingConfig,
20
+ type IntegrationAccountRow
21
+ } from '$backend/database/queries';
22
+ import type { IssueBinding } from '$shared/types/work';
23
+ import { DEFAULT_BINDING_CONFIG } from '$shared/types/work';
24
+ import type { WorkProviderAdapter, ResolvedBinding } from './types';
25
+ import { debug } from '$shared/utils/logger';
26
+
27
+ /**
28
+ * Locators this adapter recognises among the project's git remotes.
29
+ *
30
+ * Ordered by how likely each remote is to be the one that matters: `origin`
31
+ * first, then `upstream` (a fork's parent, where the issues usually live), then
32
+ * whatever else is configured.
33
+ */
34
+ export async function suggestLocators(
35
+ adapter: WorkProviderAdapter,
36
+ credentials: Record<string, string>,
37
+ projectRoot: string
38
+ ): Promise<string[]> {
39
+ let remotes: { name: string; fetchUrl: string; pushUrl: string }[] = [];
40
+ try {
41
+ remotes = await gitService.getRemotes(projectRoot);
42
+ } catch (error) {
43
+ // A project that is not a repository has no remotes, which is a normal
44
+ // state and not worth surfacing — the user simply picks a locator.
45
+ debug.log('work', `No git remotes for ${projectRoot}: ${error instanceof Error ? error.message : error}`);
46
+ return [];
47
+ }
48
+
49
+ const rank = (name: string): number => (name === 'origin' ? 0 : name === 'upstream' ? 1 : 2);
50
+ const ordered = [...remotes].sort((a, b) => rank(a.name) - rank(b.name));
51
+
52
+ const seen = new Set<string>();
53
+ const locators: string[] = [];
54
+ for (const remote of ordered) {
55
+ for (const url of [remote.fetchUrl, remote.pushUrl]) {
56
+ const locator = url ? adapter.locatorFromRemote(url, credentials) : null;
57
+ if (locator && !seen.has(locator)) {
58
+ seen.add(locator);
59
+ locators.push(locator);
60
+ }
61
+ }
62
+ }
63
+ return locators;
64
+ }
65
+
66
+ /** The stored binding for one account on one project, or null. */
67
+ export function readBinding(projectId: string, accountId: string): ResolvedBinding | null {
68
+ const row = workBindingQueries.get(projectId, accountId);
69
+ if (!row) return null;
70
+ return {
71
+ locator: row.locator,
72
+ detected: row.detected === 1,
73
+ defaultBranch: row.default_branch,
74
+ config: parseBindingConfig(row.config_json)
75
+ };
76
+ }
77
+
78
+ /**
79
+ * The binding, detecting and persisting one when there is none.
80
+ *
81
+ * Persisting the detected value rather than re-deriving it on every call is
82
+ * deliberate: it means the binding a user later edits has a row to edit, and it
83
+ * means changing a git remote does not silently repoint a project whose issues
84
+ * someone has already started working.
85
+ */
86
+ export async function resolveBinding(
87
+ adapter: WorkProviderAdapter,
88
+ account: IntegrationAccountRow,
89
+ projectId: string,
90
+ projectRoot: string
91
+ ): Promise<ResolvedBinding | null> {
92
+ const existing = readBinding(projectId, account.id);
93
+ if (existing) return existing;
94
+
95
+ const credentials = integrationAccountQueries.credentialsOf(account);
96
+ const [detected] = await suggestLocators(adapter, credentials, projectRoot);
97
+ if (!detected) return null;
98
+
99
+ workBindingQueries.upsert({
100
+ projectId,
101
+ accountId: account.id,
102
+ locator: detected,
103
+ detected: true,
104
+ config: { ...DEFAULT_BINDING_CONFIG }
105
+ });
106
+ debug.log('work', `Bound project ${projectId} to ${account.provider}:${detected} from a git remote`);
107
+
108
+ return readBinding(projectId, account.id);
109
+ }
110
+
111
+ /** Shape a binding for the client, or null when the project has none. */
112
+ export function toBindingInfo(
113
+ adapter: WorkProviderAdapter,
114
+ binding: ResolvedBinding | null
115
+ ): IssueBinding | null {
116
+ if (!binding) return null;
117
+ return {
118
+ locator: binding.locator,
119
+ displayName: adapter.describeLocator(binding.locator),
120
+ detected: binding.detected,
121
+ defaultBranch: binding.defaultBranch,
122
+ config: binding.config
123
+ };
124
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The Issues & PRs surface.
3
+ *
4
+ * Work items — issues, pull requests and the CI attached to them — for the
5
+ * current project, behind one provider-agnostic interface. GitHub is the first
6
+ * provider; GitLab, Gitea, Forgejo, Linear, Jira and PostHog are meant to be a
7
+ * file in `providers/` and a line below.
8
+ *
9
+ * types.ts the adapter contract
10
+ * registry.ts provider id → adapter
11
+ * bindings.ts which remote project this project is looking at
12
+ * service.ts the operations every route goes through
13
+ * start-work.ts work item → worktree + branch + session + first prompt
14
+ * pull-requests.ts branch → pull request, with an AI-drafted description
15
+ * prompts.ts the text this surface sends into a chat session
16
+ *
17
+ * Importing this module is what wires a provider up, so it must be imported for
18
+ * its side effects before any route runs — `backend/ws/issues/` does that.
19
+ */
20
+
21
+ import { registerAccountProbe } from '$backend/integrations';
22
+ import { registerWorkProvider } from './registry';
23
+ import { githubWorkAdapter } from './providers/github/adapter';
24
+ import { workService } from './service';
25
+
26
+ registerWorkProvider(githubWorkAdapter);
27
+
28
+ // Health for accounts whose capability projects no MCP row. Without this the
29
+ // hub would report "Nothing to probe yet" for a GitHub account forever.
30
+ registerAccountProbe('github', (accountId, projectId) => workService.probe(accountId, projectId));
31
+
32
+ export { workService } from './service';
33
+ export { getWorkAdapter, listWorkAdapters, registerWorkProvider } from './registry';
34
+ export { readBinding, resolveBinding, suggestLocators, toBindingInfo } from './bindings';
35
+ export { startWork, renderBranchName, applyConfiguredTransition } from './start-work';
36
+ export {
37
+ buildPullRequestContext,
38
+ draftPullRequestDescription,
39
+ pushPullRequestHead
40
+ } from './pull-requests';
41
+ export { buildCheckLogPrompt, buildStartWorkPrompt } from './prompts';
42
+ export type { WorkContext, WorkProviderAdapter, ResolvedBinding, UnboundContext } from './types';