@myrialabs/clopen 0.4.37 → 0.4.39

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 (193) hide show
  1. package/README.md +2 -2
  2. package/backend/auth/permissions.ts +39 -0
  3. package/backend/bootstrap.ts +16 -0
  4. package/backend/chat/stream-manager.ts +1 -1
  5. package/backend/database/crypto/envelope.test.ts +93 -0
  6. package/backend/database/crypto/envelope.ts +127 -0
  7. package/backend/database/crypto/index.ts +22 -0
  8. package/backend/database/crypto/master-key.ts +129 -0
  9. package/backend/database/crypto/secret-columns.ts +151 -0
  10. package/backend/database/migrations/071_create_notes_tables.ts +90 -0
  11. package/backend/database/migrations/072_encrypt_stored_secrets.ts +107 -0
  12. package/backend/database/migrations/073_create_integration_tables.ts +119 -0
  13. package/backend/database/migrations/074_create_work_tables.ts +94 -0
  14. package/backend/database/migrations/075_create_deploy_bindings.ts +54 -0
  15. package/backend/database/migrations/076_remove_memory_code_graph.ts +229 -0
  16. package/backend/database/migrations/077_create_integration_db_links.ts +150 -0
  17. package/backend/database/migrations/index.ts +49 -0
  18. package/backend/database/queries/db-client-connection-queries.ts +42 -12
  19. package/backend/database/queries/deploy-queries.ts +124 -0
  20. package/backend/database/queries/engine-queries.ts +23 -10
  21. package/backend/database/queries/graph-queries.ts +291 -247
  22. package/backend/database/queries/index.ts +10 -1
  23. package/backend/database/queries/integration-db-link-queries.ts +168 -0
  24. package/backend/database/queries/integration-queries.ts +325 -0
  25. package/backend/database/queries/mcp-server-queries.ts +38 -11
  26. package/backend/database/queries/note-queries.test.ts +190 -0
  27. package/backend/database/queries/note-queries.ts +269 -0
  28. package/backend/database/queries/profile-queries.ts +1 -1
  29. package/backend/database/queries/ssh-connection-queries.ts +19 -8
  30. package/backend/database/queries/work-queries.ts +210 -0
  31. package/backend/db-client/integrations/index.ts +37 -0
  32. package/backend/db-client/integrations/links.ts +533 -0
  33. package/backend/db-client/integrations/projector.test.ts +280 -0
  34. package/backend/db-client/integrations/projector.ts +256 -0
  35. package/backend/db-client/integrations/supabase-service.ts +266 -0
  36. package/backend/db-client/providers/registry.ts +27 -0
  37. package/backend/db-client/providers/supabase/adapter.ts +500 -0
  38. package/backend/db-client/providers/supabase/api-types.ts +92 -0
  39. package/backend/db-client/providers/supabase/apply-migration.ts +104 -0
  40. package/backend/db-client/providers/supabase/client.ts +259 -0
  41. package/backend/db-client/providers/supabase/features.ts +502 -0
  42. package/backend/db-client/providers/supabase/local.test.ts +78 -0
  43. package/backend/db-client/providers/supabase/local.ts +137 -0
  44. package/backend/db-client/providers/types.ts +137 -0
  45. package/backend/deployments/bindings.test.ts +43 -0
  46. package/backend/deployments/bindings.ts +216 -0
  47. package/backend/deployments/index.ts +53 -0
  48. package/backend/deployments/log-streams.ts +214 -0
  49. package/backend/deployments/prompts.ts +70 -0
  50. package/backend/deployments/providers/vercel/adapter.ts +757 -0
  51. package/backend/deployments/providers/vercel/build-logs.test.ts +80 -0
  52. package/backend/deployments/providers/vercel/build-logs.ts +211 -0
  53. package/backend/deployments/providers/vercel/client.ts +203 -0
  54. package/backend/deployments/providers/vercel/list.test.ts +624 -0
  55. package/backend/deployments/providers/vercel/normalise.test.ts +115 -0
  56. package/backend/deployments/providers/vercel/normalise.ts +113 -0
  57. package/backend/deployments/providers/vercel/types.ts +104 -0
  58. package/backend/deployments/registry.ts +27 -0
  59. package/backend/deployments/service.ts +458 -0
  60. package/backend/deployments/types.ts +278 -0
  61. package/backend/engine/docs/artifacts.md +22 -9
  62. package/backend/files/os-clipboard.test.ts +209 -0
  63. package/backend/files/os-clipboard.ts +567 -0
  64. package/backend/http/integration-hooks.ts +42 -0
  65. package/backend/http/notes-images.test.ts +228 -0
  66. package/backend/http/notes-images.ts +196 -0
  67. package/backend/index.ts +13 -0
  68. package/backend/integrations/accounts.ts +229 -0
  69. package/backend/integrations/health.ts +146 -0
  70. package/backend/integrations/index.ts +36 -0
  71. package/backend/integrations/projections/index.ts +0 -0
  72. package/backend/integrations/projections/mcp-projector.test.ts +204 -0
  73. package/backend/integrations/projections/mcp-projector.ts +163 -0
  74. package/backend/integrations/projections/types.ts +63 -0
  75. package/backend/integrations/registry/define.ts +38 -0
  76. package/backend/integrations/registry/index.ts +60 -0
  77. package/backend/integrations/registry/providers/context7.ts +44 -0
  78. package/backend/integrations/registry/providers/firecrawl.ts +41 -0
  79. package/backend/integrations/registry/providers/github.ts +78 -0
  80. package/backend/integrations/registry/providers/supabase.ts +61 -0
  81. package/backend/integrations/registry/providers/vercel.ts +46 -0
  82. package/backend/integrations/registry/types.ts +96 -0
  83. package/backend/integrations/webhooks/gateway.ts +160 -0
  84. package/backend/integrations/webhooks/verify.ts +65 -0
  85. package/backend/mcp/README.md +25 -3
  86. package/backend/mcp/external/config.ts +35 -1
  87. package/backend/mcp/index.ts +1 -1
  88. package/backend/mcp/internal/config.ts +1 -1
  89. package/backend/mcp/internal/servers/memory-graph/description.ts +3 -3
  90. package/backend/mcp/internal/servers/memory-graph/runner.ts +4 -9
  91. package/backend/mcp/internal/servers/memory-graph/schema.ts +0 -4
  92. package/backend/memory/README.md +57 -34
  93. package/backend/memory/compose.test.ts +3 -3
  94. package/backend/memory/compose.ts +6 -9
  95. package/backend/memory/config.ts +0 -5
  96. package/backend/memory/consolidate.ts +1 -2
  97. package/backend/memory/context.test.ts +8 -54
  98. package/backend/memory/context.ts +19 -25
  99. package/backend/memory/extract/episodic.ts +10 -12
  100. package/backend/memory/extract/index.ts +23 -52
  101. package/backend/memory/extract/scheduler.ts +3 -6
  102. package/backend/memory/index.ts +6 -5
  103. package/backend/memory/invalidate.ts +36 -48
  104. package/backend/memory/layout.ts +319 -130
  105. package/backend/memory/retention.ts +12 -42
  106. package/backend/memory/retrieval.eval.test.ts +2 -2
  107. package/backend/memory/retrieval.test.ts +228 -183
  108. package/backend/memory/retrieval.ts +22 -21
  109. package/backend/memory/revise.test.ts +62 -116
  110. package/backend/memory/revise.ts +0 -1
  111. package/backend/memory/view.ts +8 -5
  112. package/backend/notes/access.test.ts +82 -0
  113. package/backend/notes/access.ts +27 -0
  114. package/backend/notes/storage.test.ts +77 -0
  115. package/backend/notes/storage.ts +114 -0
  116. package/backend/permissions/service.ts +2 -2
  117. package/backend/profiles/service.ts +1 -1
  118. package/backend/projects/project-cleanup.ts +6 -0
  119. package/backend/snapshot/helpers.ts +35 -41
  120. package/backend/snapshot/snapshot-service.ts +90 -0
  121. package/backend/snapshot/turn-changes.test.ts +163 -0
  122. package/backend/snapshot/turn-changes.ts +131 -0
  123. package/backend/work/bindings.ts +124 -0
  124. package/backend/work/index.ts +42 -0
  125. package/backend/work/prompts.ts +150 -0
  126. package/backend/work/providers/github/actions-logs.ts +180 -0
  127. package/backend/work/providers/github/adapter.test.ts +88 -0
  128. package/backend/work/providers/github/adapter.ts +1255 -0
  129. package/backend/work/providers/github/client.ts +280 -0
  130. package/backend/work/providers/github/list-range.test.ts +158 -0
  131. package/backend/work/providers/github/token-kind.test.ts +42 -0
  132. package/backend/work/pull-requests.ts +242 -0
  133. package/backend/work/registry.ts +27 -0
  134. package/backend/work/service.ts +436 -0
  135. package/backend/work/start-work.test.ts +71 -0
  136. package/backend/work/start-work.ts +232 -0
  137. package/backend/work/types.ts +180 -0
  138. package/backend/ws/db-client/accounts.ts +225 -0
  139. package/backend/ws/db-client/connections.ts +34 -3
  140. package/backend/ws/db-client/context.ts +37 -0
  141. package/backend/ws/db-client/index.ts +20 -1
  142. package/backend/ws/db-client/supabase.ts +188 -0
  143. package/backend/ws/deployments/actions.ts +360 -0
  144. package/backend/ws/deployments/context.ts +43 -0
  145. package/backend/ws/deployments/crud.ts +152 -0
  146. package/backend/ws/deployments/index.ts +15 -0
  147. package/backend/ws/deployments/schemas.ts +183 -0
  148. package/backend/ws/files/clipboard.ts +78 -0
  149. package/backend/ws/files/index.ts +5 -0
  150. package/backend/ws/git/diff-budget.ts +70 -11
  151. package/backend/ws/index.ts +16 -2
  152. package/backend/ws/integrations/crud.ts +219 -0
  153. package/backend/ws/integrations/index.ts +22 -0
  154. package/backend/ws/mcp/crud.ts +25 -1
  155. package/backend/ws/memory/crud.ts +4 -16
  156. package/backend/ws/notes/index.ts +278 -0
  157. package/backend/ws/profiles/crud.ts +1 -1
  158. package/backend/ws/snapshot/changes.ts +279 -0
  159. package/backend/ws/snapshot/index.ts +4 -3
  160. package/backend/ws/work/actions.ts +206 -0
  161. package/backend/ws/work/context.ts +51 -0
  162. package/backend/ws/work/crud.ts +347 -0
  163. package/backend/ws/work/index.ts +17 -0
  164. package/backend/ws/work/pull-requests.ts +177 -0
  165. package/backend/ws/work/schemas.ts +226 -0
  166. package/dist/assets/{index-sJmS_CCm.js → index-BrF6nqld.js} +1 -1
  167. package/dist/assets/{index-Bik9TCBi.js → index-C8Gi-b6U.js} +1 -1
  168. package/dist/assets/main-Bd3gb79F.css +1 -0
  169. package/dist/assets/main-Bo1hD7mt.js +1191 -0
  170. package/dist/index.html +2 -2
  171. package/package.json +1 -1
  172. package/shared/constants/engine-tools.ts +1 -1
  173. package/shared/constants/tool-icons.ts +42 -0
  174. package/shared/types/database/schema.ts +41 -0
  175. package/shared/types/db-client/connection.ts +6 -0
  176. package/shared/types/db-client/index.ts +2 -0
  177. package/shared/types/db-client/integrations.ts +174 -0
  178. package/shared/types/db-client/supabase.ts +131 -0
  179. package/shared/types/deployments.ts +382 -0
  180. package/shared/types/integrations.ts +140 -0
  181. package/shared/types/memory.ts +34 -51
  182. package/shared/types/stores/settings.ts +8 -0
  183. package/shared/types/ui/components.ts +1 -1
  184. package/shared/types/work.ts +426 -0
  185. package/shared/utils/diff-calculator.test.ts +89 -0
  186. package/shared/utils/diff-calculator.ts +30 -65
  187. package/shared/utils/logger.ts +4 -0
  188. package/backend/memory/extract/languages.ts +0 -176
  189. package/backend/memory/extract/structural.test.ts +0 -215
  190. package/backend/memory/extract/structural.ts +0 -364
  191. package/backend/ws/snapshot/content.ts +0 -85
  192. package/dist/assets/main-DLqolBI2.css +0 -1
  193. package/dist/assets/main-Df1I3hnw.js +0 -1096
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Per-turn file changes, read from checkpoint snapshots.
3
+ *
4
+ * This is the source of truth for "what did this turn change", and it is
5
+ * deliberately NOT derived from tool calls. A snapshot is a gitignore-aware
6
+ * disk diff, so it sees a file rewritten by `sed`, a formatter, a codemod, an
7
+ * `apply_patch`, a notebook edit or a sub-agent — none of which necessarily
8
+ * surface as an Edit/Write tool_use, and several of which reach the frontend
9
+ * with their inputs stripped (see subagent-wire-trim.ts). Reading the disk
10
+ * instead of the transcript means a tool that does not exist yet is already
11
+ * handled.
12
+ *
13
+ * The trade-off is honest and must stay visible in the UI: a turn's delta is
14
+ * everything that changed on disk while the turn ran, which can include the
15
+ * user's own save or a build artifact that no .gitignore covers. It is "changed
16
+ * during this turn", not "provably written by the model".
17
+ */
18
+
19
+ import type { SessionScopedChanges } from '$shared/types/database/schema';
20
+ import { countLineChanges, isBinaryBuffer } from '$shared/utils/diff-calculator';
21
+
22
+ export { isBinaryBuffer };
23
+
24
+ export type TurnFileStatus = 'added' | 'modified' | 'deleted';
25
+
26
+ export interface TurnFileChange {
27
+ /** Project-relative path with forward slashes, as stored in the snapshot. */
28
+ path: string;
29
+ status: TurnFileStatus;
30
+ insertions: number;
31
+ deletions: number;
32
+ isBinary: boolean;
33
+ /**
34
+ * False when a blob this file needs is no longer readable. The change still
35
+ * happened — only its content is gone — so the row is kept and the UI says
36
+ * so, rather than rendering a diff of nothing.
37
+ */
38
+ contentAvailable: boolean;
39
+ }
40
+
41
+ /** Which way a file moved, decided by which side of the change has content. */
42
+ export function statusOf(oldHash: string, newHash: string): TurnFileStatus {
43
+ if (!oldHash) return 'added';
44
+ if (!newHash) return 'deleted';
45
+ return 'modified';
46
+ }
47
+
48
+ /**
49
+ * Turn one checkpoint's `session_changes` into a displayable file list.
50
+ *
51
+ * `readBlob` is injected so this stays a pure function over its inputs — the
52
+ * only I/O is the reader the caller hands in.
53
+ */
54
+ export async function buildTurnFiles(
55
+ changes: SessionScopedChanges,
56
+ readBlob: (hash: string) => Promise<Buffer>
57
+ ): Promise<TurnFileChange[]> {
58
+ const files: TurnFileChange[] = [];
59
+
60
+ for (const [path, change] of Object.entries(changes)) {
61
+ const status = statusOf(change.oldHash, change.newHash);
62
+
63
+ let oldBuf: Buffer | null = null;
64
+ let newBuf: Buffer | null = null;
65
+ let contentAvailable = true;
66
+
67
+ if (change.oldHash) {
68
+ try {
69
+ oldBuf = await readBlob(change.oldHash);
70
+ } catch {
71
+ contentAvailable = false;
72
+ }
73
+ }
74
+ if (change.newHash) {
75
+ try {
76
+ newBuf = await readBlob(change.newHash);
77
+ } catch {
78
+ contentAvailable = false;
79
+ }
80
+ }
81
+
82
+ const isBinary =
83
+ (oldBuf !== null && isBinaryBuffer(oldBuf)) || (newBuf !== null && isBinaryBuffer(newBuf));
84
+
85
+ let insertions = 0;
86
+ let deletions = 0;
87
+ if (contentAvailable && !isBinary) {
88
+ const counts = countLineChanges(
89
+ oldBuf ? oldBuf.toString('utf8') : '',
90
+ newBuf ? newBuf.toString('utf8') : ''
91
+ );
92
+ insertions = counts.additions;
93
+ deletions = counts.deletions;
94
+ }
95
+
96
+ files.push({ path, status, insertions, deletions, isBinary, contentAvailable });
97
+ }
98
+
99
+ // Alphabetical: a turn's file list is read as a checklist, and a stable order
100
+ // is what lets the eye return to the same row after a refetch.
101
+ files.sort((a, b) => a.path.localeCompare(b.path));
102
+ return files;
103
+ }
104
+
105
+ /**
106
+ * The prompt excerpt a turn row shows.
107
+ *
108
+ * Bounded because a single instruction can run to thousands of characters and
109
+ * every turn of the chat is sent at once, but cut marks itself with an ellipsis:
110
+ * a row that silently ends mid-sentence reads as the whole question.
111
+ */
112
+ export function excerptPrompt(text: string, limit: number): string {
113
+ const trimmed = text.trim();
114
+ if (trimmed.length <= limit) return trimmed;
115
+ return `${trimmed.slice(0, limit).trimEnd()}…`;
116
+ }
117
+
118
+ /** Roll a turn's file list up into the numbers a turn header shows. */
119
+ export function summariseTurnFiles(files: TurnFileChange[]): {
120
+ filesChanged: number;
121
+ insertions: number;
122
+ deletions: number;
123
+ } {
124
+ let insertions = 0;
125
+ let deletions = 0;
126
+ for (const file of files) {
127
+ insertions += file.insertions;
128
+ deletions += file.deletions;
129
+ }
130
+ return { filesChanged: files.length, insertions, deletions };
131
+ }
@@ -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
+ }
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Pulling a failing Actions run's logs into something a prompt can carry.
3
+ *
4
+ * Two decisions worth stating.
5
+ *
6
+ * FAILED JOBS ONLY, VIA THE PER-JOB ENDPOINT. The run-level endpoint hands back
7
+ * a zip of every job's log, including the twelve that passed. Listing the jobs
8
+ * and fetching only the failed ones is one extra request and avoids unzipping
9
+ * megabytes to throw almost all of it away.
10
+ *
11
+ * THE TAIL, NOT THE HEAD. A CI log's first 500 lines are dependency
12
+ * installation; the failure is at the end. Truncating from the front is the one
13
+ * way to produce a log excerpt that contains no information about the failure,
14
+ * so this keeps the tail and says how much it dropped.
15
+ */
16
+
17
+ import type { CheckLogBundle } from '$shared/types/work';
18
+ import { apiBaseOf, githubRequest, GitHubError, type GitHubCredentials } from './client';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ /** Total log text handed to the model, across every failed job in the run. */
22
+ const TOTAL_LOG_BUDGET = 24 * 1024;
23
+ /** Per job, so one catastrophic job cannot crowd out the other three. */
24
+ const PER_JOB_BUDGET = 12 * 1024;
25
+ const LOG_TIMEOUT_MS = 30_000;
26
+
27
+ interface GitHubJob {
28
+ id: number;
29
+ name: string;
30
+ conclusion: string | null;
31
+ status: string;
32
+ html_url: string | null;
33
+ steps?: { name: string; conclusion: string | null; number: number }[];
34
+ }
35
+
36
+ /**
37
+ * Fetch one job's log as text.
38
+ *
39
+ * `redirect: 'manual'` is not a detail. GitHub answers with a 302 to a signed
40
+ * storage URL, and that URL carries its own credentials in the query string.
41
+ * Following automatically would replay our `Authorization: Bearer` header at a
42
+ * third-party host — leaking the token to a service that has no business seeing
43
+ * it, and which will reject the request for having two credentials anyway.
44
+ */
45
+ async function fetchJobLog(credentials: GitHubCredentials, jobId: number): Promise<string> {
46
+ const url = `${apiBaseOf(credentials)}/actions/jobs/${jobId}/logs`;
47
+
48
+ const response = await fetch(url, {
49
+ headers: {
50
+ Accept: 'application/vnd.github+json',
51
+ Authorization: `Bearer ${credentials.token}`,
52
+ 'X-GitHub-Api-Version': '2022-11-28',
53
+ 'User-Agent': 'clopen'
54
+ },
55
+ redirect: 'manual',
56
+ signal: AbortSignal.timeout(LOG_TIMEOUT_MS)
57
+ });
58
+
59
+ if (response.status >= 300 && response.status < 400) {
60
+ const location = response.headers.get('location');
61
+ if (!location) throw new GitHubError('GitHub returned a redirect with no location', response.status, 'error');
62
+ const followed = await fetch(location, { signal: AbortSignal.timeout(LOG_TIMEOUT_MS) });
63
+ if (!followed.ok) {
64
+ throw new GitHubError(`Could not download the job log (HTTP ${followed.status})`, followed.status, 'error');
65
+ }
66
+ return followed.text();
67
+ }
68
+
69
+ if (!response.ok) {
70
+ // Logs expire, and a repo can disable log retention entirely. Both are
71
+ // normal states, not failures of this feature.
72
+ throw new GitHubError(
73
+ response.status === 410
74
+ ? 'These logs have expired and are no longer stored by GitHub'
75
+ : `Could not read the job log (HTTP ${response.status})`,
76
+ response.status,
77
+ response.status === 401 ? 'auth' : 'error'
78
+ );
79
+ }
80
+
81
+ return response.text();
82
+ }
83
+
84
+ /** Keep the last `limit` bytes, cut on a line boundary, and say what was dropped. */
85
+ function keepTail(text: string, limit: number): { text: string; truncated: boolean } {
86
+ if (text.length <= limit) return { text, truncated: false };
87
+ const tail = text.slice(text.length - limit);
88
+ const firstNewline = tail.indexOf('\n');
89
+ const body = firstNewline >= 0 ? tail.slice(firstNewline + 1) : tail;
90
+ const droppedLines = text.slice(0, text.length - body.length).split('\n').length;
91
+ return {
92
+ text: `… ${droppedLines} earlier line${droppedLines === 1 ? '' : 's'} omitted …\n${body}`,
93
+ truncated: true
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Actions prefixes every line with an ISO timestamp and wraps output in
99
+ * `##[group]` markers. Both are pure noise in a prompt and together they are
100
+ * roughly a quarter of the bytes, which is a quarter of the budget spent on
101
+ * nothing.
102
+ */
103
+ function stripActionsNoise(text: string): string {
104
+ return text
105
+ .split('\n')
106
+ .map((line) => line.replace(/^\d{4}-\d{2}-\d{2}T[\d:.]+Z\s?/, ''))
107
+ .filter((line) => !/^##\[(group|endgroup)\]/.test(line))
108
+ .join('\n')
109
+ .trimEnd();
110
+ }
111
+
112
+ /**
113
+ * Logs for the failed jobs of one run, budgeted and annotated.
114
+ *
115
+ * Returns a bundle even when every job's log has expired: the run name and the
116
+ * list of failed steps still tell the agent what broke, and an empty answer
117
+ * would look like the feature not working.
118
+ */
119
+ export async function buildRunLogBundle(
120
+ credentials: GitHubCredentials,
121
+ locator: string,
122
+ runId: string,
123
+ runName: string
124
+ ): Promise<CheckLogBundle> {
125
+ const jobs = await githubRequest<{ jobs: GitHubJob[] }>(
126
+ credentials,
127
+ `/repos/${locator}/actions/runs/${runId}/jobs?per_page=100`,
128
+ { noCache: true }
129
+ );
130
+
131
+ const failed = (jobs.data?.jobs ?? []).filter(
132
+ (job) => job.conclusion === 'failure' || job.conclusion === 'timed_out'
133
+ );
134
+
135
+ if (failed.length === 0) {
136
+ return {
137
+ runId,
138
+ runName,
139
+ text: 'The run reported a failure but no individual job failed — this is usually a cancelled or infrastructure-level failure.',
140
+ truncated: false
141
+ };
142
+ }
143
+
144
+ const sections: string[] = [];
145
+ let used = 0;
146
+ let truncated = false;
147
+
148
+ for (const job of failed) {
149
+ const failedSteps = (job.steps ?? [])
150
+ .filter((step) => step.conclusion === 'failure')
151
+ .map((step) => step.name);
152
+
153
+ const header = failedSteps.length > 0
154
+ ? `### Job "${job.name}" — failed at: ${failedSteps.join(', ')}`
155
+ : `### Job "${job.name}" — failed`;
156
+
157
+ if (used >= TOTAL_LOG_BUDGET) {
158
+ sections.push(`${header}\n(log omitted — the earlier jobs used the available context)`);
159
+ truncated = true;
160
+ continue;
161
+ }
162
+
163
+ let body: string;
164
+ try {
165
+ const raw = stripActionsNoise(await fetchJobLog(credentials, job.id));
166
+ const limit = Math.min(PER_JOB_BUDGET, TOTAL_LOG_BUDGET - used);
167
+ const clipped = keepTail(raw, limit);
168
+ if (clipped.truncated) truncated = true;
169
+ body = clipped.text;
170
+ used += clipped.text.length;
171
+ } catch (error) {
172
+ debug.warn('work', `Could not read log for job ${job.id}:`, error);
173
+ body = `(log unavailable: ${error instanceof Error ? error.message : String(error)})`;
174
+ }
175
+
176
+ sections.push(`${header}\n\n\`\`\`\n${body}\n\`\`\``);
177
+ }
178
+
179
+ return { runId, runName, text: sections.join('\n\n'), truncated };
180
+ }