@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
@@ -0,0 +1,278 @@
1
+ /**
2
+ * Notes Router
3
+ *
4
+ * Notes live in collections, and a collection carries the scope: `project`
5
+ * (members of that project) or `global` (every signed-in user). Permissions are
6
+ * resolved through the collection on every route — a note id is never treated
7
+ * as a capability on its own.
8
+ *
9
+ * Writes broadcast `notes:changed` to whoever can see the collection, the same
10
+ * way worktrees do: a note another member just created is invisible until the
11
+ * next reload without it. The event carries ids only — a note holds up to
12
+ * 200 KB, so fanning the list out on every autosave would put megabytes on the
13
+ * socket per keystroke of a long note.
14
+ */
15
+
16
+ import { t } from 'elysia';
17
+ import { createRouter } from '$shared/utils/ws-server';
18
+ import type { WSConnection } from '$shared/utils/ws-server';
19
+ import type { NoteCollection } from '$shared/types/database/schema';
20
+ import { ws as wsServer } from '../../utils/ws';
21
+ import { requireProjectAccess } from '../access';
22
+ import {
23
+ noteQueries,
24
+ noteCollectionQueries,
25
+ noteImageQueries
26
+ } from '../../database/queries/note-queries';
27
+ import { canAccessCollection } from '../../notes/access';
28
+ import { removeCollectionFiles, removeNoteFiles, resolveNoteImagePath } from '../../notes/storage';
29
+ import { unlink } from 'node:fs/promises';
30
+
31
+ const scopeSchema = t.Union([t.Literal('project'), t.Literal('global')]);
32
+
33
+ const collectionSchema = t.Object({
34
+ id: t.String(),
35
+ name: t.String(),
36
+ scope: scopeSchema,
37
+ project_id: t.Union([t.String(), t.Null()]),
38
+ created_by: t.Union([t.String(), t.Null()]),
39
+ created_at: t.String(),
40
+ updated_at: t.String()
41
+ });
42
+
43
+ const noteSchema = t.Object({
44
+ id: t.String(),
45
+ collection_id: t.String(),
46
+ title: t.Union([t.String(), t.Null()]),
47
+ content: t.String(),
48
+ created_by: t.Union([t.String(), t.Null()]),
49
+ created_at: t.String(),
50
+ updated_at: t.String(),
51
+ images: t.Array(
52
+ t.Object({
53
+ id: t.String(),
54
+ note_id: t.String(),
55
+ file_name: t.String(),
56
+ mime_type: t.String(),
57
+ size: t.Number(),
58
+ storage_path: t.String(),
59
+ created_at: t.String()
60
+ })
61
+ )
62
+ });
63
+
64
+ /** Resolve a collection and refuse the call unless this connection may see it. */
65
+ function requireCollection(conn: WSConnection, collectionId: string): NoteCollection {
66
+ const collection = noteCollectionQueries.getById(collectionId);
67
+ // Same answer for "does not exist" and "not yours", so the id space cannot be
68
+ // probed for which collections are real.
69
+ if (!collection) throw new Error('Access denied');
70
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
71
+ throw new Error('Access denied');
72
+ }
73
+ return collection;
74
+ }
75
+
76
+ /** Resolve the collection a note belongs to, subject to the same check. */
77
+ function requireNoteCollection(conn: WSConnection, noteId: string): NoteCollection {
78
+ const collection = noteCollectionQueries.getForNote(noteId);
79
+ if (!collection) throw new Error('Access denied');
80
+ if (!canAccessCollection(wsServer.getUserId(conn), collection)) {
81
+ throw new Error('Access denied');
82
+ }
83
+ return collection;
84
+ }
85
+
86
+ /** Check the caller may write into `scope` before anything is created there. */
87
+ function requireScope(conn: WSConnection, scope: 'project' | 'global', projectId: string | null): void {
88
+ if (scope === 'project') {
89
+ if (!projectId) throw new Error('projectId is required for the project scope');
90
+ requireProjectAccess(conn, projectId);
91
+ return;
92
+ }
93
+ // Global is instance-wide; the only requirement is a signed-in connection,
94
+ // which getUserId asserts.
95
+ wsServer.getUserId(conn);
96
+ }
97
+
98
+ /**
99
+ * Tell everyone who can see this collection that its contents moved.
100
+ *
101
+ * A project collection reaches the project room; a global one reaches every
102
+ * connection, because that is exactly the set of people allowed to read it.
103
+ */
104
+ function broadcast(collection: NoteCollection): void {
105
+ const payload = {
106
+ collectionId: collection.id,
107
+ scope: collection.scope,
108
+ projectId: collection.project_id
109
+ };
110
+ if (collection.scope === 'project' && collection.project_id) {
111
+ wsServer.emit.project(collection.project_id, 'notes:changed', payload);
112
+ } else {
113
+ wsServer.emit.global('notes:changed', payload);
114
+ }
115
+ }
116
+
117
+ export const notesRouter = createRouter()
118
+ // ---- Collections ----
119
+
120
+ .http('notes:list', {
121
+ data: t.Object({
122
+ scope: scopeSchema,
123
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
124
+ }),
125
+ response: t.Object({
126
+ collections: t.Array(collectionSchema),
127
+ notes: t.Array(noteSchema)
128
+ })
129
+ }, async ({ data, conn }) => {
130
+ const projectId = data.projectId ?? null;
131
+ requireScope(conn, data.scope, projectId);
132
+ const collections = noteCollectionQueries.listByScope(data.scope, projectId);
133
+ return {
134
+ collections,
135
+ notes: noteQueries.listByCollections(collections.map((c) => c.id))
136
+ };
137
+ })
138
+
139
+ .http('notes:create-collection', {
140
+ data: t.Object({
141
+ name: t.String({ minLength: 1 }),
142
+ scope: scopeSchema,
143
+ projectId: t.Optional(t.Union([t.String(), t.Null()]))
144
+ }),
145
+ response: t.Object({ collection: collectionSchema })
146
+ }, async ({ data, conn }) => {
147
+ const projectId = data.scope === 'project' ? (data.projectId ?? null) : null;
148
+ requireScope(conn, data.scope, projectId);
149
+ const collection = noteCollectionQueries.create({
150
+ name: data.name,
151
+ scope: data.scope,
152
+ projectId,
153
+ createdBy: wsServer.getUserId(conn)
154
+ });
155
+ broadcast(collection);
156
+ return { collection };
157
+ })
158
+
159
+ .http('notes:rename-collection', {
160
+ data: t.Object({ id: t.String({ minLength: 1 }), name: t.String({ minLength: 1 }) }),
161
+ response: t.Object({ collection: t.Union([collectionSchema, t.Null()]) })
162
+ }, async ({ data, conn }) => {
163
+ const collection = requireCollection(conn, data.id);
164
+ const renamed = noteCollectionQueries.rename(collection.id, data.name);
165
+ if (renamed) broadcast(renamed);
166
+ return { collection: renamed };
167
+ })
168
+
169
+ .http('notes:delete-collection', {
170
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
171
+ response: t.Object({ ok: t.Boolean() })
172
+ }, async ({ data, conn }) => {
173
+ const collection = requireCollection(conn, data.id);
174
+ // Notes and image rows cascade with the collection; the files they point
175
+ // at do not, so the whole collection directory goes with them.
176
+ noteCollectionQueries.delete(collection.id);
177
+ await removeCollectionFiles(collection.id);
178
+ broadcast(collection);
179
+ return { ok: true };
180
+ })
181
+
182
+ // ---- Notes ----
183
+
184
+ .http('notes:get', {
185
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
186
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
187
+ }, async ({ data, conn }) => {
188
+ requireNoteCollection(conn, data.id);
189
+ return { note: noteQueries.getById(data.id) };
190
+ })
191
+
192
+ .http('notes:create', {
193
+ data: t.Object({
194
+ // Either an explicit collection, or a scope whose default collection is
195
+ // created on first use.
196
+ collectionId: t.Optional(t.String()),
197
+ scope: t.Optional(scopeSchema),
198
+ projectId: t.Optional(t.Union([t.String(), t.Null()])),
199
+ title: t.Optional(t.Union([t.String(), t.Null()])),
200
+ content: t.Optional(t.String())
201
+ }),
202
+ response: t.Object({ note: noteSchema })
203
+ }, async ({ data, conn }) => {
204
+ const userId = wsServer.getUserId(conn);
205
+ let collection: NoteCollection;
206
+ if (data.collectionId) {
207
+ collection = requireCollection(conn, data.collectionId);
208
+ } else {
209
+ const scope = data.scope ?? 'project';
210
+ const projectId = scope === 'project' ? (data.projectId ?? null) : null;
211
+ requireScope(conn, scope, projectId);
212
+ collection = noteCollectionQueries.ensureDefault(scope, projectId, userId);
213
+ }
214
+ const note = noteQueries.create({
215
+ collectionId: collection.id,
216
+ title: data.title ?? null,
217
+ content: data.content ?? '',
218
+ createdBy: userId
219
+ });
220
+ broadcast(collection);
221
+ return { note: { ...note, images: [] } };
222
+ })
223
+
224
+ .http('notes:update', {
225
+ data: t.Object({
226
+ id: t.String({ minLength: 1 }),
227
+ title: t.Optional(t.Union([t.String(), t.Null()])),
228
+ content: t.Optional(t.String()),
229
+ collectionId: t.Optional(t.String())
230
+ }),
231
+ response: t.Object({ note: t.Union([noteSchema, t.Null()]) })
232
+ }, async ({ data, conn }) => {
233
+ const from = requireNoteCollection(conn, data.id);
234
+ // Moving a note is only allowed between collections the caller can already
235
+ // see, otherwise a move would be a way to read or plant one they cannot.
236
+ const to = data.collectionId ? requireCollection(conn, data.collectionId) : from;
237
+ const updated = noteQueries.update(data.id, {
238
+ title: data.title,
239
+ content: data.content,
240
+ collectionId: data.collectionId
241
+ });
242
+ if (!updated) return { note: null };
243
+ broadcast(from);
244
+ if (to.id !== from.id) broadcast(to);
245
+ return { note: noteQueries.getById(data.id) };
246
+ })
247
+
248
+ .http('notes:delete', {
249
+ data: t.Object({ id: t.String({ minLength: 1 }) }),
250
+ response: t.Object({ ok: t.Boolean() })
251
+ }, async ({ data, conn }) => {
252
+ const collection = requireNoteCollection(conn, data.id);
253
+ noteQueries.delete(data.id);
254
+ await removeNoteFiles(collection.id, data.id);
255
+ broadcast(collection);
256
+ return { ok: true };
257
+ })
258
+
259
+ .http('notes:delete-image', {
260
+ data: t.Object({ imageId: t.String({ minLength: 1 }) }),
261
+ response: t.Object({ ok: t.Boolean() })
262
+ }, async ({ data, conn }) => {
263
+ const img = noteImageQueries.getById(data.imageId);
264
+ if (!img) return { ok: true };
265
+ const collection = requireNoteCollection(conn, img.note_id);
266
+ const absolute = resolveNoteImagePath(img.storage_path);
267
+ if (absolute) await unlink(absolute).catch(() => {});
268
+ noteImageQueries.delete(data.imageId);
269
+ broadcast(collection);
270
+ return { ok: true };
271
+ })
272
+
273
+ // Collaborative broadcast events (Server → Client)
274
+ .emit('notes:changed', t.Object({
275
+ collectionId: t.String(),
276
+ scope: scopeSchema,
277
+ projectId: t.Union([t.String(), t.Null()])
278
+ }));
@@ -7,7 +7,7 @@
7
7
  * - profiles:available / project-default (non-admin)
8
8
  *
9
9
  * A Profile bundles references to existing artifacts (Skills, Commands,
10
- * Subagents, MCP Connectors) by slug plus an optional per-engine allow/deny
10
+ * Subagents, Integrations) by slug plus an optional per-engine allow/deny
11
11
  * overlay. Nothing is duplicated — see `backend/profiles`. Admin gating lives in
12
12
  * `backend/auth/permissions.ts`; the picker/default-read routes stay non-admin
13
13
  * (choosing a profile for a session is a run choice like the model).
@@ -0,0 +1,206 @@
1
+ /**
2
+ * The two actions that turn a work item into work.
3
+ *
4
+ * work:start-work item → worktree + branch + session + first prompt
5
+ * work:checks CI runs for a branch
6
+ * work:check-logs a failing run's logs, composed into a chat prompt
7
+ *
8
+ * Both return TEXT for the client to send rather than sending it themselves.
9
+ * The chat pipeline is driven from the browser — it owns which session is
10
+ * active, the streaming state and the optimistic message — and a second, silent
11
+ * path that injects messages from the backend would race with all three.
12
+ */
13
+
14
+ import { t } from 'elysia';
15
+ import { createRouter } from '$shared/utils/ws-server';
16
+ import { gitService } from '$backend/git/git-service';
17
+ import { buildCheckLogPrompt, workService, startWork } from '$backend/work';
18
+ import { serializeWorktree } from '../worktrees/crud';
19
+ import { worktreeQueries } from '$backend/database/queries';
20
+ import { ws } from '$backend/utils/ws';
21
+ import type { EngineType } from '$shared/types/unified';
22
+ import { resolveWorkProject } from './context';
23
+ import { announceWorkChanged } from './crud';
24
+ import {
25
+ CHECK_RUN_SCHEMA,
26
+ COMMIT_DETAIL_SCHEMA,
27
+ COMMIT_SCHEMA,
28
+ FILE_CHANGE_SCHEMA,
29
+ KIND_SCHEMA
30
+ } from './schemas';
31
+ import { debug } from '$shared/utils/logger';
32
+
33
+ const ENGINE_SCHEMA = t.Union([
34
+ t.Literal('claude-code'),
35
+ t.Literal('opencode'),
36
+ t.Literal('copilot'),
37
+ t.Literal('codex'),
38
+ t.Literal('qwen'),
39
+ t.Literal('pi'),
40
+ t.Literal('cline'),
41
+ t.Literal('cursor')
42
+ ]);
43
+
44
+ /** The branch the caller is looking at, when it did not name one. */
45
+ async function currentBranchOf(root: string): Promise<string> {
46
+ const branches = await gitService.getBranches(root);
47
+ if (!branches.current || branches.detached) {
48
+ throw new Error('This workspace is not on a branch');
49
+ }
50
+ return branches.current;
51
+ }
52
+
53
+ export const workActionsHandler = createRouter()
54
+ .http('work:start-work', {
55
+ data: t.Object({
56
+ projectId: t.Optional(t.String()),
57
+ accountId: t.String({ minLength: 1 }),
58
+ kind: KIND_SCHEMA,
59
+ id: t.String({ minLength: 1 }),
60
+ engine: ENGINE_SCHEMA
61
+ }),
62
+ response: t.Object({
63
+ worktreeId: t.String(),
64
+ worktreeName: t.String(),
65
+ sessionId: t.String(),
66
+ branch: t.String(),
67
+ prompt: t.String(),
68
+ transitionedTo: t.Union([t.String(), t.Null()]),
69
+ transitionError: t.Union([t.String(), t.Null()]),
70
+ needsSetup: t.Boolean()
71
+ })
72
+ }, async ({ data, conn }) => {
73
+ const { projectId } = resolveWorkProject(conn, data.projectId);
74
+ const userId = ws.getUserId(conn);
75
+
76
+ const result = await startWork({
77
+ projectId,
78
+ accountId: data.accountId,
79
+ kind: data.kind,
80
+ itemId: data.id,
81
+ engine: data.engine as EngineType,
82
+ userId
83
+ });
84
+
85
+ // The worktree list and the session list both just changed for everyone in
86
+ // the project, and the person who clicked is about to switch into both.
87
+ ws.emit.project(projectId, 'worktrees:changed', {
88
+ projectId,
89
+ worktrees: worktreeQueries.getByProjectId(projectId).map(serializeWorktree)
90
+ });
91
+ announceWorkChanged(projectId);
92
+
93
+ debug.log('work', `Started work on ${data.kind} ${data.id} in worktree ${result.worktreeId}`);
94
+ return result;
95
+ })
96
+
97
+ .http('work:checks', {
98
+ data: t.Object({
99
+ projectId: t.Optional(t.String()),
100
+ accountId: t.String({ minLength: 1 }),
101
+ branch: t.Optional(t.String())
102
+ }),
103
+ response: t.Object({
104
+ branch: t.String(),
105
+ runs: t.Array(CHECK_RUN_SCHEMA)
106
+ })
107
+ }, async ({ data, conn }) => {
108
+ const { projectId, root } = resolveWorkProject(conn, data.projectId);
109
+
110
+ const branch = data.branch?.trim() || (await currentBranchOf(root));
111
+ return { branch, runs: await workService.listChecks(projectId, data.accountId, branch) };
112
+ })
113
+
114
+ .http('work:check-logs', {
115
+ data: t.Object({
116
+ projectId: t.Optional(t.String()),
117
+ accountId: t.String({ minLength: 1 }),
118
+ runId: t.String({ minLength: 1 }),
119
+ branch: t.String({ minLength: 1 }),
120
+ runUrl: t.String()
121
+ }),
122
+ response: t.Object({
123
+ runName: t.String(),
124
+ /** The logs themselves, so they can be READ here rather than only sent. */
125
+ text: t.String(),
126
+ prompt: t.String(),
127
+ truncated: t.Boolean()
128
+ })
129
+ }, async ({ data, conn }) => {
130
+ const { projectId } = resolveWorkProject(conn, data.projectId);
131
+ const bundle = await workService.fetchCheckLogs(projectId, data.accountId, data.runId);
132
+
133
+ return {
134
+ runName: bundle.runName,
135
+ text: bundle.text,
136
+ prompt: buildCheckLogPrompt(bundle, {
137
+ locator: workService.describeBinding(projectId, data.accountId) ?? 'this repository',
138
+ branch: data.branch,
139
+ runUrl: data.runUrl
140
+ }),
141
+ truncated: bundle.truncated
142
+ };
143
+ })
144
+
145
+ .http('work:pr-commits', {
146
+ data: t.Object({
147
+ projectId: t.Optional(t.String()),
148
+ accountId: t.String({ minLength: 1 }),
149
+ id: t.String({ minLength: 1 })
150
+ }),
151
+ response: t.Array(COMMIT_SCHEMA)
152
+ }, async ({ data, conn }) => {
153
+ const { projectId } = resolveWorkProject(conn, data.projectId);
154
+ return workService.listCommits(projectId, data.accountId, data.id);
155
+ })
156
+
157
+ /**
158
+ * One commit, opened.
159
+ *
160
+ * Separate from `pr-commits` because it costs a request per commit and the
161
+ * list is read far more often than any single commit is opened.
162
+ */
163
+ .http('work:commit-detail', {
164
+ data: t.Object({
165
+ projectId: t.Optional(t.String()),
166
+ accountId: t.String({ minLength: 1 }),
167
+ sha: t.String({ minLength: 1, maxLength: 100 })
168
+ }),
169
+ response: COMMIT_DETAIL_SCHEMA
170
+ }, async ({ data, conn }) => {
171
+ const { projectId } = resolveWorkProject(conn, data.projectId);
172
+ return workService.commitDetail(projectId, data.accountId, data.sha);
173
+ })
174
+
175
+ .http('work:file-content', {
176
+ data: t.Object({
177
+ projectId: t.Optional(t.String()),
178
+ accountId: t.String({ minLength: 1 }),
179
+ path: t.String({ minLength: 1, maxLength: 1000 }),
180
+ ref: t.String({ minLength: 1, maxLength: 250 }),
181
+ /** Preferred address: it survives forks, deletions and gone branches. */
182
+ blobSha: t.Optional(t.String({ maxLength: 100 }))
183
+ }),
184
+ response: t.Object({ content: t.String(), truncated: t.Boolean() })
185
+ }, async ({ data, conn }) => {
186
+ const { projectId } = resolveWorkProject(conn, data.projectId);
187
+ return workService.fetchFileContent(
188
+ projectId,
189
+ data.accountId,
190
+ data.path,
191
+ data.ref,
192
+ data.blobSha
193
+ );
194
+ })
195
+
196
+ .http('work:pr-files', {
197
+ data: t.Object({
198
+ projectId: t.Optional(t.String()),
199
+ accountId: t.String({ minLength: 1 }),
200
+ id: t.String({ minLength: 1 })
201
+ }),
202
+ response: t.Array(FILE_CHANGE_SCHEMA)
203
+ }, async ({ data, conn }) => {
204
+ const { projectId } = resolveWorkProject(conn, data.projectId);
205
+ return workService.listFiles(projectId, data.accountId, data.id);
206
+ });
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Which project an issues route acts on.
3
+ *
4
+ * The surface lives in More Tools, and More Tools is global — a user looking at
5
+ * project A should be able to read project B's issues without leaving their
6
+ * session. So every route takes an OPTIONAL `projectId` and falls back to the
7
+ * connection's current one, rather than reading the connection and nothing else.
8
+ *
9
+ * Access is still checked per call. `projectId` arriving from the client is a
10
+ * request, not a permission: `requireProjectAccess` is what decides.
11
+ */
12
+
13
+ import type { WSConnection } from '$shared/utils/ws-server';
14
+ import type { Project } from '$shared/types/database/schema';
15
+ import { ws } from '$backend/utils/ws';
16
+ import { resolveWorktreeRoot } from '$backend/worktrees';
17
+ import { requireProjectAccess } from '../access';
18
+
19
+ export interface IssueProjectContext {
20
+ projectId: string;
21
+ project: Project;
22
+ /**
23
+ * The tree git commands run against.
24
+ *
25
+ * Worktree-aware ONLY for the project the connection is actually viewing: a
26
+ * worktree belongs to a session, and resolving another project's root
27
+ * through this connection's worktree id would run git in the wrong tree —
28
+ * or in one that does not exist.
29
+ */
30
+ root: string;
31
+ /** True when this is the project the user is currently working in. */
32
+ isCurrent: boolean;
33
+ }
34
+
35
+ export function resolveWorkProject(conn: WSConnection, projectId?: string): IssueProjectContext {
36
+ const current = ws.getProjectId(conn);
37
+ const target = (projectId ?? '').trim() || current;
38
+ const project = requireProjectAccess(conn, target);
39
+
40
+ if (target !== current) {
41
+ return { projectId: target, project, root: project.path, isCurrent: false };
42
+ }
43
+
44
+ const resolved = resolveWorktreeRoot(target, ws.getWorktreeId(conn));
45
+ return {
46
+ projectId: target,
47
+ project,
48
+ root: resolved.path || project.path,
49
+ isCurrent: true
50
+ };
51
+ }