@myrialabs/clopen 0.4.36 → 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 (115) 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/git/conflict-state.test.ts +396 -0
  28. package/backend/git/git-executor.ts +6 -0
  29. package/backend/git/git-parser.ts +144 -48
  30. package/backend/git/git-service.ts +727 -57
  31. package/backend/git/push-target.test.ts +264 -0
  32. package/backend/http/integration-hooks.ts +42 -0
  33. package/backend/http/notes-images.test.ts +228 -0
  34. package/backend/http/notes-images.ts +196 -0
  35. package/backend/index.ts +9 -0
  36. package/backend/integrations/accounts.ts +229 -0
  37. package/backend/integrations/health.ts +146 -0
  38. package/backend/integrations/index.ts +36 -0
  39. package/backend/integrations/projections/index.ts +120 -0
  40. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  41. package/backend/integrations/projections/mcp-projector.ts +159 -0
  42. package/backend/integrations/projections/types.ts +51 -0
  43. package/backend/integrations/registry/define.ts +38 -0
  44. package/backend/integrations/registry/index.ts +56 -0
  45. package/backend/integrations/registry/providers/context7.ts +44 -0
  46. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  47. package/backend/integrations/registry/providers/github.ts +78 -0
  48. package/backend/integrations/registry/types.ts +96 -0
  49. package/backend/integrations/webhooks/gateway.ts +160 -0
  50. package/backend/integrations/webhooks/verify.ts +65 -0
  51. package/backend/mcp/README.md +25 -3
  52. package/backend/mcp/external/config.ts +35 -1
  53. package/backend/mcp/index.ts +1 -1
  54. package/backend/mcp/internal/config.ts +1 -1
  55. package/backend/notes/access.test.ts +82 -0
  56. package/backend/notes/access.ts +27 -0
  57. package/backend/notes/storage.test.ts +77 -0
  58. package/backend/notes/storage.ts +114 -0
  59. package/backend/permissions/service.ts +2 -2
  60. package/backend/profiles/service.ts +1 -1
  61. package/backend/project/status-manager.ts +20 -0
  62. package/backend/projects/project-cleanup.ts +6 -0
  63. package/backend/work/bindings.ts +124 -0
  64. package/backend/work/index.ts +42 -0
  65. package/backend/work/prompts.ts +150 -0
  66. package/backend/work/providers/github/actions-logs.ts +180 -0
  67. package/backend/work/providers/github/adapter.test.ts +88 -0
  68. package/backend/work/providers/github/adapter.ts +1255 -0
  69. package/backend/work/providers/github/client.ts +280 -0
  70. package/backend/work/providers/github/list-range.test.ts +158 -0
  71. package/backend/work/providers/github/token-kind.test.ts +42 -0
  72. package/backend/work/pull-requests.ts +242 -0
  73. package/backend/work/registry.ts +27 -0
  74. package/backend/work/service.ts +436 -0
  75. package/backend/work/start-work.test.ts +71 -0
  76. package/backend/work/start-work.ts +232 -0
  77. package/backend/work/types.ts +180 -0
  78. package/backend/ws/files/clipboard.ts +78 -0
  79. package/backend/ws/files/index.ts +5 -0
  80. package/backend/ws/git/branch-name.ts +6 -5
  81. package/backend/ws/git/branch.ts +43 -1
  82. package/backend/ws/git/commit-message.ts +13 -10
  83. package/backend/ws/git/conflict.ts +106 -3
  84. package/backend/ws/git/diff-budget.test.ts +125 -0
  85. package/backend/ws/git/diff-budget.ts +279 -0
  86. package/backend/ws/git/log.ts +25 -0
  87. package/backend/ws/git/remote.ts +75 -1
  88. package/backend/ws/index.ts +11 -1
  89. package/backend/ws/integrations/crud.ts +219 -0
  90. package/backend/ws/integrations/index.ts +22 -0
  91. package/backend/ws/mcp/crud.ts +25 -1
  92. package/backend/ws/notes/index.ts +278 -0
  93. package/backend/ws/profiles/crud.ts +1 -1
  94. package/backend/ws/work/actions.ts +206 -0
  95. package/backend/ws/work/context.ts +51 -0
  96. package/backend/ws/work/crud.ts +347 -0
  97. package/backend/ws/work/index.ts +17 -0
  98. package/backend/ws/work/pull-requests.ts +177 -0
  99. package/backend/ws/work/schemas.ts +226 -0
  100. package/dist/assets/{index-Bg-SUCFg.js → index-CyH7fSbR.js} +1 -1
  101. package/dist/assets/{index-Cz4YpHVi.js → index-DSHIANSy.js} +1 -1
  102. package/dist/assets/main-D2IOjftb.css +1 -0
  103. package/dist/assets/main-DM-tHKbW.js +1152 -0
  104. package/dist/index.html +2 -2
  105. package/package.json +1 -1
  106. package/shared/constants/engine-tools.ts +1 -1
  107. package/shared/constants/tool-icons.ts +33 -0
  108. package/shared/types/database/schema.ts +41 -0
  109. package/shared/types/git.ts +123 -0
  110. package/shared/types/integrations.ts +140 -0
  111. package/shared/types/stores/settings.ts +8 -0
  112. package/shared/types/work.ts +426 -0
  113. package/shared/utils/logger.ts +3 -0
  114. package/dist/assets/main-9G7IpQpK.css +0 -1
  115. package/dist/assets/main-BofFsH8E.js +0 -1085
@@ -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
  *
@@ -5,6 +5,7 @@
5
5
 
6
6
  import { streamManager, type StreamState } from '../chat/stream-manager.js';
7
7
  import { ws } from '../utils/ws.js';
8
+ import { sessionQueries } from '../database/queries/session-queries.js';
8
9
  import type { UnifiedMessage } from '$shared/types/unified';
9
10
  import { isWaitingForInteractiveInput } from '$shared/utils/interactive-input';
10
11
 
@@ -25,6 +26,21 @@ function detectStreamWaitingInput(stream: StreamState): boolean {
25
26
  return isWaitingForInteractiveInput(messages);
26
27
  }
27
28
 
29
+ /**
30
+ * Which tree a stream runs in (null = the main project tree).
31
+ * Resolved from the session rather than the stream, because a stream never
32
+ * carries the worktree it was started in — and the callers need it to tell
33
+ * apart "this project is busy" from "this worktree is busy".
34
+ */
35
+ function resolveStreamWorktreeId(chatSessionId: string, memo: Map<string, string | null>): string | null {
36
+ const cached = memo.get(chatSessionId);
37
+ if (cached !== undefined) return cached;
38
+
39
+ const worktreeId = sessionQueries.getById(chatSessionId)?.worktree_id ?? null;
40
+ memo.set(chatSessionId, worktreeId);
41
+ return worktreeId;
42
+ }
43
+
28
44
  // Store active users per project (shared with main endpoint)
29
45
  const projectUsers = new Map<string, Set<{ userId: string; userName: string; lastSeen: number }>>();
30
46
 
@@ -57,6 +73,7 @@ export async function getProjectStatusData(projectId?: string) {
57
73
 
58
74
  // Get per-chat-session user presence from WS rooms
59
75
  const chatSessionUsers = ws.getProjectChatSessions(projectId);
76
+ const worktreeMemo = new Map<string, string | null>();
60
77
 
61
78
  return {
62
79
  projectId,
@@ -69,6 +86,7 @@ export async function getProjectStatusData(projectId?: string) {
69
86
  streams: allProjectStreams.map(s => ({
70
87
  streamId: s.streamId,
71
88
  chatSessionId: s.chatSessionId,
89
+ worktreeId: resolveStreamWorktreeId(s.chatSessionId, worktreeMemo),
72
90
  status: s.status,
73
91
  startedAt: s.startedAt,
74
92
  messagesCount: s.messages.length,
@@ -91,6 +109,7 @@ export async function getProjectStatusData(projectId?: string) {
91
109
 
92
110
  // Get all active streams grouped by project
93
111
  const allStreams = streamManager.getAllStreams();
112
+ const worktreeMemo = new Map<string, string | null>();
94
113
  allStreams.forEach(stream => {
95
114
  if (stream.projectId) {
96
115
  if (!allProjects.has(stream.projectId)) {
@@ -111,6 +130,7 @@ export async function getProjectStatusData(projectId?: string) {
111
130
  projectData.streams.push({
112
131
  streamId: stream.streamId,
113
132
  chatSessionId: stream.chatSessionId,
133
+ worktreeId: resolveStreamWorktreeId(stream.chatSessionId, worktreeMemo),
114
134
  status: stream.status,
115
135
  startedAt: stream.startedAt,
116
136
  messagesCount: stream.messages.length,
@@ -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';
@@ -0,0 +1,150 @@
1
+ /**
2
+ * The prompts this surface sends into a chat session.
3
+ *
4
+ * They live on the SERVER, next to the data that fills them, for the same
5
+ * reason the git panel's conflict prompt does not: this text is assembled from
6
+ * a provider response the client never receives in full, and duplicating the
7
+ * assembly on both sides would mean two versions of the instructions to keep in
8
+ * step.
9
+ *
10
+ * A budget applies to everything variable. An issue with 200 comments is not
11
+ * rare, and pasting all of them turns "start work" into a request that costs
12
+ * more than the work.
13
+ */
14
+
15
+ import type { CheckLogBundle, WorkItemDetail } from '$shared/types/work';
16
+
17
+ /** Body text kept from the item itself. Enough for a detailed bug report. */
18
+ const MAX_BODY_CHARS = 8_000;
19
+ /** Comments are where a thread goes off-topic, so they get a tighter budget. */
20
+ const MAX_COMMENTS = 12;
21
+ const MAX_COMMENT_CHARS = 1_200;
22
+
23
+ function clip(text: string, limit: number): string {
24
+ const trimmed = (text ?? '').trim();
25
+ if (trimmed.length <= limit) return trimmed;
26
+ return `${trimmed.slice(0, limit)}\n… truncated, ${trimmed.length - limit} more characters — read the item online for the rest`;
27
+ }
28
+
29
+ /**
30
+ * Comments, newest last, oldest dropped first.
31
+ *
32
+ * Dropping from the FRONT is the right direction here and the wrong one for CI
33
+ * logs: a long issue thread converges on the current understanding, so the last
34
+ * comments are the ones that matter.
35
+ */
36
+ function renderComments(item: WorkItemDetail): string {
37
+ if (item.comments.length === 0) return '';
38
+
39
+ const kept = item.comments.slice(-MAX_COMMENTS);
40
+ const dropped = item.comments.length - kept.length;
41
+ const rendered = kept
42
+ .map((comment) => `**${comment.author}** (${comment.createdAt}):\n${clip(comment.body, MAX_COMMENT_CHARS)}`)
43
+ .join('\n\n---\n\n');
44
+
45
+ const header = dropped > 0
46
+ ? `Comments (${kept.length} most recent of ${item.comments.length}):`
47
+ : `Comments (${item.comments.length}):`;
48
+
49
+ return `${header}\n\n${rendered}`;
50
+ }
51
+
52
+ /** The first message of a session started from a work item. */
53
+ export function buildStartWorkPrompt(
54
+ item: WorkItemDetail,
55
+ context: { branch: string; branchMode: 'create' | 'checkout'; locator: string }
56
+ ): string {
57
+ const sections: string[] = [
58
+ `Work on ${item.kind === 'pull-request' ? 'pull request' : 'issue'} #${item.identifier} from ${context.locator}.`,
59
+ `**${item.title}**\n${item.url}`
60
+ ];
61
+
62
+ const facts: string[] = [`State: ${item.state}`];
63
+ if (item.labels.length > 0) facts.push(`Labels: ${item.labels.join(', ')}`);
64
+ if (item.assignees.length > 0) facts.push(`Assigned to: ${item.assignees.join(', ')}`);
65
+ if (item.author) facts.push(`Opened by: ${item.author}`);
66
+ sections.push(facts.join(' · '));
67
+
68
+ sections.push(item.body.trim()
69
+ ? `Description:\n\n${clip(item.body, MAX_BODY_CHARS)}`
70
+ : 'The item has no description.');
71
+
72
+ const comments = renderComments(item);
73
+ if (comments) sections.push(comments);
74
+
75
+ // The environment matters, and it differs by kind: an agent told it is on a
76
+ // new branch will not go looking for existing work, and an agent NOT told it
77
+ // is on a review branch will offer to create one.
78
+ sections.push(
79
+ context.branchMode === 'create'
80
+ ? [
81
+ 'You are in a fresh worktree of this project, already on a new branch:',
82
+ `\`${context.branch}\``,
83
+ '',
84
+ 'Start by reading the relevant code to confirm the description matches what is actually there, then say what you plan to change before changing it. Do not commit or push anything unless asked.'
85
+ ].join('\n')
86
+ : [
87
+ 'You are in a fresh worktree of this project, with the pull request branch checked out:',
88
+ `\`${context.branch}\``,
89
+ '',
90
+ 'The change is already here — read it before anything else. Summarise what it does, then say what you think is wrong with it or what it is missing. Do not commit or push anything unless asked.'
91
+ ].join('\n')
92
+ );
93
+
94
+ return sections.join('\n\n');
95
+ }
96
+
97
+ /** The message sent when a failing CI run is pushed into the chat. */
98
+ export function buildCheckLogPrompt(
99
+ bundle: CheckLogBundle,
100
+ context: { locator: string; branch: string; runUrl: string }
101
+ ): string {
102
+ return [
103
+ `A CI run failed on \`${context.branch}\` in ${context.locator}.`,
104
+ `**${bundle.runName}**\n${context.runUrl}`,
105
+ bundle.truncated
106
+ ? 'Logs from the failed jobs (tails only — earlier output was dropped to fit):'
107
+ : 'Logs from the failed jobs:',
108
+ bundle.text,
109
+ 'Work out what failed and why from these logs, check the claim against the code in this worktree, and propose the smallest fix that addresses the cause. If the logs are not enough to tell, say what else you need rather than guessing.'
110
+ ].join('\n\n');
111
+ }
112
+
113
+ /** The instruction that drafts a pull-request description. */
114
+ export function buildPrDescriptionPrompt(input: {
115
+ branch: string;
116
+ base: string;
117
+ commits: { hash: string; subject: string }[];
118
+ linkedItem: { identifier: string; title: string | null } | null;
119
+ diff: string;
120
+ diffTruncated: boolean;
121
+ }): string {
122
+ const sections: string[] = [
123
+ `Write a pull request description for merging \`${input.branch}\` into \`${input.base}\`.`
124
+ ];
125
+
126
+ if (input.linkedItem) {
127
+ sections.push(
128
+ `This branch was started from issue #${input.linkedItem.identifier}${input.linkedItem.title ? ` ("${input.linkedItem.title}")` : ''}. Reference it in the description.`
129
+ );
130
+ }
131
+
132
+ if (input.commits.length > 0) {
133
+ sections.push(`Commits on this branch:\n${input.commits.map((c) => `- ${c.subject}`).join('\n')}`);
134
+ }
135
+
136
+ sections.push(
137
+ [
138
+ 'Rules:',
139
+ '- title: one line, imperative, no trailing period. If the commits follow a convention, follow it.',
140
+ '- body: markdown. Lead with what changed and why, in prose. Add a short bullet list only when the change touches several unrelated areas.',
141
+ '- Describe only what is in the diff. Do not invent testing that was not done, and do not promise follow-up work.',
142
+ input.diffTruncated
143
+ ? '- The diff below is a sample. Describe the change as a whole using the file list, not only the visible hunks.'
144
+ : ''
145
+ ].filter(Boolean).join('\n')
146
+ );
147
+
148
+ sections.push(input.diff);
149
+ return sections.join('\n\n');
150
+ }