@myrialabs/clopen 0.4.4 → 0.4.6

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 (53) hide show
  1. package/backend/auth/permissions.ts +15 -1
  2. package/backend/database/migrations/044_create_skills_table.ts +29 -0
  3. package/backend/database/migrations/index.ts +7 -0
  4. package/backend/database/queries/index.ts +3 -1
  5. package/backend/database/queries/skill-queries.ts +105 -0
  6. package/backend/engine/adapters/claude/stream.ts +5 -0
  7. package/backend/engine/adapters/codex/credential.ts +120 -13
  8. package/backend/engine/adapters/codex/stream.ts +34 -8
  9. package/backend/engine/adapters/copilot/stream.ts +4 -0
  10. package/backend/engine/adapters/opencode/stream.ts +4 -0
  11. package/backend/engine/adapters/qwen/stream.ts +3 -0
  12. package/backend/engine/docs/lessons-learned.md +54 -50
  13. package/backend/git/git-service.ts +40 -0
  14. package/backend/index.ts +10 -1
  15. package/backend/mcp/README.md +77 -24
  16. package/backend/mcp/external/config.ts +82 -101
  17. package/backend/mcp/external/parse.test.ts +190 -0
  18. package/backend/mcp/external/parse.ts +293 -0
  19. package/backend/mcp/external/proxy.ts +202 -0
  20. package/backend/mcp/index.ts +6 -3
  21. package/backend/mcp/internal/remote-server.ts +103 -55
  22. package/backend/skills/index.ts +21 -0
  23. package/backend/skills/marketplace.ts +172 -0
  24. package/backend/skills/service.ts +245 -0
  25. package/backend/skills/spec.ts +214 -0
  26. package/backend/skills/store.ts +99 -0
  27. package/backend/skills/sync.ts +187 -0
  28. package/backend/snapshot/gitignore.ts +230 -7
  29. package/backend/snapshot/helpers.ts +34 -10
  30. package/backend/ws/files/read.ts +10 -1
  31. package/backend/ws/git/branch-name.ts +20 -4
  32. package/backend/ws/git/branch.ts +66 -11
  33. package/backend/ws/git/commit-message.ts +18 -3
  34. package/backend/ws/git/commit.ts +50 -16
  35. package/backend/ws/git/conflict.ts +47 -5
  36. package/backend/ws/git/diff.ts +38 -4
  37. package/backend/ws/git/log.ts +22 -2
  38. package/backend/ws/git/remote.ts +82 -33
  39. package/backend/ws/git/staging.ts +39 -9
  40. package/backend/ws/git/status.ts +52 -0
  41. package/backend/ws/index.ts +5 -1
  42. package/backend/ws/mcp/crud.ts +30 -1
  43. package/backend/ws/skills/catalog.ts +79 -0
  44. package/backend/ws/skills/crud.ts +123 -0
  45. package/backend/ws/skills/index.ts +15 -0
  46. package/backend/ws/snapshot/timeline.ts +1 -1
  47. package/dist/assets/main-BkMrek4_.css +1 -0
  48. package/dist/assets/{main-AqTMkV9D.js → main-TYNK6Orl.js} +332 -295
  49. package/dist/index.html +2 -2
  50. package/package.json +1 -1
  51. package/shared/types/git.ts +20 -0
  52. package/shared/utils/logger.ts +1 -0
  53. package/dist/assets/main-DJf71Zum.css +0 -1
@@ -0,0 +1,187 @@
1
+ /**
2
+ * Engine sync — materialize enabled skills into the shape each engine consumes.
3
+ *
4
+ * Skills are an open standard, but engines surface them differently:
5
+ * - NATIVE (Claude, Qwen, Copilot): read a real skills directory and do their
6
+ * own progressive disclosure. We mirror each enabled skill folder there.
7
+ * Claude's dir is inside its isolated CLAUDE_CONFIG_DIR; Qwen and Copilot
8
+ * resolve theirs from $HOME (`~/.qwen/skills`, `~/.copilot/skills`) with no
9
+ * relocation env, so for those we manage the user's real global skills dir —
10
+ * touching only the slugs we own, never the user's own skills.
11
+ * - SYNTHETIC (Codex, OpenCode): no native skills concept, so we emit a
12
+ * "skills preamble" — name + description + the absolute path to each skill's
13
+ * SKILL.md — into a managed, marker-delimited block of the engine's global
14
+ * instructions file (inside its isolated home). The engine reads the body on
15
+ * demand with its own file tool, emulating progressive disclosure.
16
+ *
17
+ * Sync is wrapped so a failure degrades gracefully — a stream never breaks
18
+ * because skills couldn't sync.
19
+ *
20
+ * NOTE: the synthetic target paths (Codex/OpenCode) follow each engine's
21
+ * documented global-memory convention but are best-effort; if an engine ignores
22
+ * the path, its skills simply don't surface (no error, no data loss) until the
23
+ * mapping is verified against that engine.
24
+ */
25
+
26
+ import { join } from 'path';
27
+ import { homedir } from 'os';
28
+ import { mkdir, readFile, writeFile, readdir, rm, stat } from 'node:fs/promises';
29
+ import { getEngineUserConfigDir } from '$backend/utils/paths';
30
+ import { skillQueries } from '$backend/database/queries';
31
+ import { debug } from '$shared/utils/logger';
32
+ import { getSkillMdPath, copySkillInto } from './store';
33
+
34
+ export type SkillEngine = 'claude' | 'codex' | 'copilot' | 'qwen' | 'opencode';
35
+
36
+ const MARKER_START = '<!-- CLOPEN:SKILLS:START — managed block, do not edit -->';
37
+ const MARKER_END = '<!-- CLOPEN:SKILLS:END -->';
38
+
39
+ interface EnabledSkill {
40
+ slug: string;
41
+ name: string;
42
+ description: string;
43
+ }
44
+
45
+ function getEnabledSkills(): EnabledSkill[] {
46
+ return skillQueries.getEnabled().map(r => ({ slug: r.slug, name: r.name, description: r.description }));
47
+ }
48
+
49
+ /**
50
+ * Native engines read a real skills directory; this is where we mirror to.
51
+ *
52
+ * Claude's skills dir lives under its isolated `CLAUDE_CONFIG_DIR`, so it stays
53
+ * fully inside Clopen's sandbox. Qwen and Copilot DO support skills natively but
54
+ * resolve the user-level dir from `$HOME` (`~/.qwen/skills`, `~/.copilot/skills`)
55
+ * — neither `QWEN_RUNTIME_DIR` nor `COPILOT_HOME` relocates it, and there is no
56
+ * config-dir override. So for those two we manage the user's real global skills
57
+ * dir, touching ONLY the slugs we own (see syncNative's prune guard) and never
58
+ * the user's own skills.
59
+ */
60
+ function nativeSkillsDir(engine: SkillEngine): string | null {
61
+ switch (engine) {
62
+ case 'claude': return join(getEngineUserConfigDir('claude'), 'skills');
63
+ case 'qwen': return join(homedir(), '.qwen', 'skills');
64
+ case 'copilot': return join(homedir(), '.copilot', 'skills');
65
+ default: return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Synthetic engines have no native skills concept — we inject the preamble into
71
+ * the global instructions file each one auto-loads from its (isolated) home.
72
+ */
73
+ function syntheticMemoryFile(engine: SkillEngine): string | null {
74
+ switch (engine) {
75
+ // Codex loads global guidance from `$CODEX_HOME/AGENTS.md`.
76
+ case 'codex': return join(getEngineUserConfigDir('codex'), 'AGENTS.md');
77
+ // OpenCode reads `AGENTS.md` from its XDG config dir (`$XDG_CONFIG_HOME/opencode`).
78
+ case 'opencode': return join(getEngineUserConfigDir('opencode'), 'opencode', 'AGENTS.md');
79
+ default: return null;
80
+ }
81
+ }
82
+
83
+ async function pathExists(path: string): Promise<boolean> {
84
+ try { await stat(path); return true; } catch { return false; }
85
+ }
86
+
87
+ /** Mirror enabled skill folders into a native engine's skills dir; prune the rest. */
88
+ async function syncNative(destDir: string, enabled: EnabledSkill[]): Promise<void> {
89
+ await mkdir(destDir, { recursive: true });
90
+ const enabledSlugs = new Set(enabled.map(s => s.slug));
91
+ const managedSlugs = new Set(skillQueries.getAll().map(s => s.slug));
92
+
93
+ // Remove copies of managed skills that are no longer enabled. Folders we
94
+ // don't manage (e.g. user-placed skills) are left untouched.
95
+ for (const entry of await readdir(destDir, { withFileTypes: true })) {
96
+ if (!entry.isDirectory()) continue;
97
+ if (managedSlugs.has(entry.name) && !enabledSlugs.has(entry.name)) {
98
+ await rm(join(destDir, entry.name), { recursive: true, force: true });
99
+ }
100
+ }
101
+
102
+ for (const skill of enabled) {
103
+ await copySkillInto(skill.slug, destDir);
104
+ }
105
+ }
106
+
107
+ /** Build the synthetic preamble block listing each enabled skill. */
108
+ function buildPreamble(enabled: EnabledSkill[]): string {
109
+ if (enabled.length === 0) return '';
110
+ const lines: string[] = [
111
+ MARKER_START,
112
+ '# Available Skills',
113
+ '',
114
+ 'You have access to the following skills. Each is a set of instructions for a',
115
+ 'specific kind of task. When the user\'s request matches a skill\'s purpose, READ',
116
+ 'its SKILL.md file with your file-reading tool to load the full instructions',
117
+ 'before proceeding. Only load a skill when it is relevant.',
118
+ ''
119
+ ];
120
+ for (const skill of enabled) {
121
+ lines.push(`- **${skill.name}** — ${skill.description}`);
122
+ lines.push(` Instructions: ${getSkillMdPath(skill.slug)}`);
123
+ }
124
+ lines.push(MARKER_END);
125
+ return lines.join('\n');
126
+ }
127
+
128
+ /** Replace (or remove) the managed skills block inside an engine memory file. */
129
+ async function syncSynthetic(filePath: string, enabled: EnabledSkill[]): Promise<void> {
130
+ let existing = '';
131
+ if (await pathExists(filePath)) existing = await readFile(filePath, 'utf8');
132
+
133
+ // Strip any prior managed block so updates are idempotent and never duplicate.
134
+ const blockRe = new RegExp(`\\n*${escapeRe(MARKER_START)}[\\s\\S]*?${escapeRe(MARKER_END)}\\n*`, 'g');
135
+ const base = existing.replace(blockRe, '\n').replace(/\n{3,}/g, '\n\n').trim();
136
+
137
+ const block = buildPreamble(enabled);
138
+ const next = block ? (base ? `${base}\n\n${block}\n` : `${block}\n`) : (base ? `${base}\n` : '');
139
+
140
+ if (next === existing) return;
141
+ if (next === '') {
142
+ // Nothing managed and nothing else in the file — leave any empty file as-is.
143
+ await writeFile(filePath, '', 'utf8');
144
+ return;
145
+ }
146
+ await mkdir(join(filePath, '..'), { recursive: true });
147
+ await writeFile(filePath, next, 'utf8');
148
+ }
149
+
150
+ function escapeRe(s: string): string {
151
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
152
+ }
153
+
154
+ /**
155
+ * Sync enabled skills for one engine. Safe to call at every stream start —
156
+ * native dirs are reconciled and the synthetic block is rewritten in place.
157
+ * Never throws: failures are logged and swallowed so streaming is unaffected.
158
+ */
159
+ export async function syncSkills(engine: SkillEngine): Promise<void> {
160
+ try {
161
+ const enabled = getEnabledSkills();
162
+ const native = nativeSkillsDir(engine);
163
+ if (native) {
164
+ await syncNative(native, enabled);
165
+ debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (native)`);
166
+ return;
167
+ }
168
+ const memoryFile = syntheticMemoryFile(engine);
169
+ if (memoryFile) {
170
+ await syncSynthetic(memoryFile, enabled);
171
+ debug.log('skills', `🧩 Synced ${enabled.length} skill(s) → ${engine} (synthetic)`);
172
+ }
173
+ } catch (error) {
174
+ debug.warn('skills', `⚠️ Skill sync for ${engine} failed (continuing without):`, error);
175
+ }
176
+ }
177
+
178
+ /** Re-sync every engine — used after a mutation so changes propagate eagerly. */
179
+ export async function syncSkillsAllEngines(): Promise<void> {
180
+ const engines: SkillEngine[] = ['claude', 'codex', 'copilot', 'qwen', 'opencode'];
181
+ await Promise.all(engines.map(syncSkills));
182
+ }
183
+
184
+ /** Validate that a skill's SKILL.md exists on disk (used by the WS status surface). */
185
+ export async function skillFileReady(slug: string): Promise<boolean> {
186
+ return pathExists(getSkillMdPath(slug));
187
+ }
@@ -22,6 +22,138 @@ const ALWAYS_EXCLUDE_DIRS = new Set([
22
22
  'node_modules',
23
23
  ]);
24
24
 
25
+ /**
26
+ * Find paths of all nested git repos (directories with their own `.git`) at any
27
+ * depth under `rootPath`. Walks into nested repos to find deeply nested ones.
28
+ * Does NOT scan the repos — just returns their absolute paths.
29
+ *
30
+ * Used by callers that need to run git commands inside each nested repo
31
+ * (e.g. `git:status` aggregating changes from nested repos into the Changes
32
+ * tab of the Git panel).
33
+ */
34
+ export async function findNestedRepoPaths(rootPath: string): Promise<string[]> {
35
+ const paths: string[] = [];
36
+
37
+ const walk = async (currentPath: string): Promise<void> => {
38
+ let entries;
39
+ try {
40
+ entries = await fs.readdir(currentPath, { withFileTypes: true });
41
+ } catch {
42
+ return;
43
+ }
44
+
45
+ for (const entry of entries) {
46
+ if (!entry.isDirectory()) continue;
47
+ if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
48
+
49
+ const fullPath = path.join(currentPath, entry.name);
50
+
51
+ // Check if this directory is itself a git repo
52
+ try {
53
+ await fs.access(path.join(fullPath, '.git'));
54
+ paths.push(fullPath);
55
+ // Fall through to also walk into it for deeper nested repos
56
+ } catch {
57
+ // Not a git repo
58
+ }
59
+
60
+ await walk(fullPath);
61
+ }
62
+ };
63
+
64
+ await walk(rootPath);
65
+ return paths;
66
+ }
67
+
68
+ /**
69
+ * Read the outer repo's `.gitmodules` file and return the set of relative
70
+ * submodule paths. Returns an empty set when the file is missing or unreadable
71
+ * (e.g. the project isn't a git repo at all, or has no submodules).
72
+ *
73
+ * The format is INI-like:
74
+ * [submodule "vendor/foo"]
75
+ * path = vendor/foo
76
+ * url = git@example.com:vendor/foo.git
77
+ *
78
+ * The `path =` value is what we return — the directory inside the project root
79
+ * where the submodule is checked out. If a section omits `path =`, git falls
80
+ * back to the section name; we mirror that.
81
+ */
82
+ export async function findSubmodulePaths(rootPath: string): Promise<Set<string>> {
83
+ const out = new Set<string>();
84
+ let raw: string;
85
+ try {
86
+ raw = await fs.readFile(path.join(rootPath, '.gitmodules'), 'utf8');
87
+ } catch {
88
+ return out; // file missing → no submodules
89
+ }
90
+
91
+ // Two-pass parse: collect per-section { name, path? } then resolve.
92
+ // Single-pass is simpler but needs careful handling of the implicit
93
+ // section-name fallback; the two-pass version reads more clearly.
94
+ const sections: Array<{ name: string; path?: string }> = [];
95
+ let current: { name: string; path?: string } | null = null;
96
+ for (const line of raw.split(/\r?\n/)) {
97
+ const trimmed = line.trim();
98
+ if (!trimmed || trimmed.startsWith('#')) continue;
99
+
100
+ const sectionMatch = trimmed.match(/^\[submodule\s+"([^"]+)"\]\s*$/);
101
+ if (sectionMatch) {
102
+ if (current) sections.push(current);
103
+ current = { name: sectionMatch[1] };
104
+ continue;
105
+ }
106
+ if (!current) continue;
107
+
108
+ const pathMatch = trimmed.match(/^path\s*=\s*(.+?)\s*$/);
109
+ if (pathMatch) current.path = pathMatch[1].replace(/\\/g, '/');
110
+ }
111
+ if (current) sections.push(current);
112
+
113
+ for (const s of sections) {
114
+ out.add(s.path ?? s.name);
115
+ }
116
+ return out;
117
+ }
118
+
119
+ /**
120
+ * Given a file path relative to the project root, find the deepest nested
121
+ * git repo that contains it. Returns the repo's absolute path and the file
122
+ * path relative to that repo, or `null` if the file lives in the outer repo.
123
+ *
124
+ * Used by git staging/discard handlers so that `git add` / `git restore` /
125
+ * `git rm` run inside the correct repo (the outer repo's `git` would skip
126
+ * or fail on files that are tracked by a nested repo).
127
+ */
128
+ export async function findRepoForFile(
129
+ projectPath: string,
130
+ filePath: string
131
+ ): Promise<{ repoPath: string; relativeFilePath: string } | null> {
132
+ const normalizedFilePath = filePath.replace(/\\/g, '/');
133
+ const nestedRepoPaths = await findNestedRepoPaths(projectPath);
134
+
135
+ let bestMatch: { repoPath: string; relativeFilePath: string } | null = null;
136
+ let bestRepoRelLen = -1;
137
+
138
+ for (const repoPath of nestedRepoPaths) {
139
+ const repoRel = path.relative(projectPath, repoPath).replace(/\\/g, '/');
140
+ // File is inside this repo if its path starts with `repoRel/`
141
+ if (normalizedFilePath === repoRel || normalizedFilePath.startsWith(repoRel + '/')) {
142
+ if (repoRel.length > bestRepoRelLen) {
143
+ bestMatch = {
144
+ repoPath,
145
+ relativeFilePath: normalizedFilePath === repoRel
146
+ ? ''
147
+ : normalizedFilePath.substring(repoRel.length + 1)
148
+ };
149
+ bestRepoRelLen = repoRel.length;
150
+ }
151
+ }
152
+ }
153
+
154
+ return bestMatch;
155
+ }
156
+
25
157
  /**
26
158
  * Get list of snapshot-eligible files using git (preferred) or manual scan.
27
159
  * Returns full absolute paths.
@@ -49,13 +181,39 @@ async function scanWithGit(dirPath: string): Promise<string[] | null> {
49
181
  return null;
50
182
  }
51
183
 
184
+ try {
185
+ // Scan the outer repo
186
+ const files = await scanSingleGitRepo(dirPath);
187
+
188
+ // Find and scan nested git repos — separate repositories living inside
189
+ // the project (e.g. a theme extracted into its own repo). The parent
190
+ // repo's `git ls-files --exclude-standard` skips these because git treats
191
+ // a nested repo as a single gitlink entry (or excludes it entirely when
192
+ // it's listed in the parent's .gitignore). Without this step, files
193
+ // inside nested repos are invisible to the snapshot system, so AI
194
+ // changes to them never appear in the checkpoint banner.
195
+ const nestedFiles = await findAndScanNestedRepos(dirPath);
196
+
197
+ const allFiles = [...files, ...nestedFiles];
198
+ debug.log('snapshot', `Git scan found ${allFiles.length} files (${files.length} outer, ${nestedFiles.length} nested)`);
199
+ return allFiles;
200
+ } catch (err) {
201
+ debug.warn('snapshot', 'git ls-files failed, falling back to manual scan:', err);
202
+ return null;
203
+ }
204
+ }
205
+
206
+ /**
207
+ * Run `git ls-files -co --exclude-standard` in a single git repo and return
208
+ * absolute paths. Used for both the outer repo and nested repos.
209
+ */
210
+ async function scanSingleGitRepo(dirPath: string): Promise<string[]> {
52
211
  try {
53
212
  const result = await execGit(['ls-files', '-co', '--exclude-standard'], dirPath, 60_000);
54
- if (result.exitCode !== 0) return null;
55
- const output = result.stdout;
213
+ if (result.exitCode !== 0) return [];
56
214
 
57
215
  const files: string[] = [];
58
- for (const line of output.split('\n')) {
216
+ for (const line of result.stdout.split('\n')) {
59
217
  const relativePath = line.trim();
60
218
  if (!relativePath) continue;
61
219
 
@@ -63,17 +221,70 @@ async function scanWithGit(dirPath: string): Promise<string[] | null> {
63
221
  const firstSegment = relativePath.split('/')[0];
64
222
  if (ALWAYS_EXCLUDE_DIRS.has(firstSegment)) continue;
65
223
 
224
+ // Skip directory entries — git emits nested repos as a single
225
+ // entry with a trailing slash (e.g. `theme/`). These are handled
226
+ // by findAndScanNestedRepos, not here.
227
+ if (relativePath.endsWith('/')) continue;
228
+
66
229
  files.push(path.join(dirPath, relativePath));
67
230
  }
68
-
69
- debug.log('snapshot', `Git scan found ${files.length} files`);
70
231
  return files;
71
232
  } catch (err) {
72
- debug.warn('snapshot', 'git ls-files failed, falling back to manual scan:', err);
73
- return null;
233
+ debug.warn('snapshot', `git ls-files failed for ${dirPath}:`, err);
234
+ return [];
74
235
  }
75
236
  }
76
237
 
238
+ /**
239
+ * Walk the project tree to find nested git repos (directories with their own
240
+ * `.git`) and scan each one independently. This catches nested repos that are
241
+ * gitignored by the parent — they'd otherwise be invisible to the outer repo's
242
+ * `git ls-files --exclude-standard`.
243
+ *
244
+ * The walk respects ALWAYS_EXCLUDE_DIRS (skips `.git`, `node_modules`) but does
245
+ * NOT respect .gitignore, because the nested repo we're looking for may itself
246
+ * be gitignored by the parent. Once a nested repo is found, its own
247
+ * `git ls-files --exclude-standard` handles its .gitignore rules.
248
+ */
249
+ async function findAndScanNestedRepos(rootPath: string): Promise<string[]> {
250
+ const files: string[] = [];
251
+
252
+ const walk = async (currentPath: string): Promise<void> => {
253
+ let entries;
254
+ try {
255
+ entries = await fs.readdir(currentPath, { withFileTypes: true });
256
+ } catch {
257
+ return;
258
+ }
259
+
260
+ for (const entry of entries) {
261
+ if (!entry.isDirectory()) continue;
262
+ if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
263
+
264
+ const fullPath = path.join(currentPath, entry.name);
265
+
266
+ // Check if this directory is itself a git repo (`.git` can be a
267
+ // directory or a file — the latter for worktrees/submodules).
268
+ try {
269
+ await fs.access(path.join(fullPath, '.git'));
270
+ // Nested repo found — scan it independently, then continue
271
+ // walking into it to find even deeper nested repos.
272
+ const nestedFiles = await scanSingleGitRepo(fullPath);
273
+ files.push(...nestedFiles);
274
+ await walk(fullPath);
275
+ continue;
276
+ } catch {
277
+ // Not a git repo — recurse to find deeper nested repos
278
+ }
279
+
280
+ await walk(fullPath);
281
+ }
282
+ };
283
+
284
+ await walk(rootPath);
285
+ return files;
286
+ }
287
+
77
288
  // ============================================================================
78
289
  // Strategy 2: Manual scan with .gitignore parsing
79
290
  // ============================================================================
@@ -282,6 +493,18 @@ async function scanWithGitignoreParsing(projectPath: string): Promise<string[]>
282
493
  if (ALWAYS_EXCLUDE_DIRS.has(entry.name)) continue;
283
494
 
284
495
  if (entry.isDirectory()) {
496
+ // Check if this is a nested git repo — scan it independently
497
+ // and bypass the .gitignore filter so files inside a
498
+ // gitignored nested repo are still tracked.
499
+ try {
500
+ await fs.access(path.join(fullPath, '.git'));
501
+ const nestedFiles = await scanSingleGitRepo(fullPath);
502
+ files.push(...nestedFiles);
503
+ continue;
504
+ } catch {
505
+ // Not a git repo — apply gitignore filter and recurse
506
+ }
507
+
285
508
  if (!filter.isIgnored(relativePath, true)) {
286
509
  await scan(fullPath);
287
510
  }
@@ -1,6 +1,8 @@
1
1
  import { snapshotQueries, messageQueries, checkpointQueries } from '../database/queries';
2
+ import { blobStore } from './blob-store';
2
3
  import { debug } from '$shared/utils/logger';
3
4
  import { loadMessage } from '$shared/utils/message-formatter';
5
+ import { calculateFileChangeStats } from '$shared/utils/diff-calculator';
4
6
  import type { DatabaseMessage } from '$shared/types/database/schema';
5
7
  import type { UnifiedMessage, UserMessage } from '$shared/types/unified';
6
8
 
@@ -320,27 +322,49 @@ export function isDescendant(
320
322
  * The snapshot associated with the checkpoint message itself contains the stats
321
323
  * (file changes the assistant made in response to this user message).
322
324
  */
323
- export function getCheckpointFileStats(
325
+ export async function getCheckpointFileStats(
324
326
  checkpointMsg: DatabaseMessage
325
- ): { filesChanged: number; insertions: number; deletions: number } {
327
+ ): Promise<{ filesChanged: number; insertions: number; deletions: number }> {
326
328
  const snapshot = snapshotQueries.getByMessageId(checkpointMsg.id);
327
329
  if (!snapshot) {
328
330
  return { filesChanged: 0, insertions: 0, deletions: 0 };
329
331
  }
330
332
 
331
333
  let filesChanged = snapshot.files_changed || 0;
332
- const insertions = snapshot.insertions || 0;
333
- const deletions = snapshot.deletions || 0;
334
-
335
- // Try to get a more accurate file count from session_changes
336
- if (snapshot.session_changes) {
334
+ let insertions = snapshot.insertions || 0;
335
+ let deletions = snapshot.deletions || 0;
336
+
337
+ // Fallback for snapshots captured before nested-repo files were tracked:
338
+ // `session_changes` may be non-empty (with nested-repo entries) but
339
+ // `files_changed`/`insertions`/`deletions` are 0 because the capture
340
+ // loop never saw those files. Recompute from the blob store so the
341
+ // Restore Checkpoint UI shows the real numbers retroactively.
342
+ if (snapshot.session_changes && (insertions === 0 || deletions === 0)) {
337
343
  try {
338
- const changes = JSON.parse(snapshot.session_changes as string);
344
+ const changes = JSON.parse(snapshot.session_changes as string) as Record<string, { oldHash: string; newHash: string }>;
339
345
  const changeCount = Object.keys(changes).length;
340
346
  if (changeCount > 0) {
341
- filesChanged = changeCount;
347
+ const previousSnapshot: Record<string, Buffer> = {};
348
+ const currentSnapshot: Record<string, Buffer> = {};
349
+ let allBlobsOk = true;
350
+ for (const [filepath, entry] of Object.entries(changes)) {
351
+ if (entry.oldHash) {
352
+ try { previousSnapshot[filepath] = await blobStore.readBlob(entry.oldHash); }
353
+ catch { allBlobsOk = false; break; }
354
+ }
355
+ if (entry.newHash) {
356
+ try { currentSnapshot[filepath] = await blobStore.readBlob(entry.newHash); }
357
+ catch { allBlobsOk = false; break; }
358
+ }
359
+ }
360
+ if (allBlobsOk) {
361
+ const recomputed = calculateFileChangeStats(previousSnapshot, currentSnapshot);
362
+ filesChanged = recomputed.filesChanged;
363
+ insertions = recomputed.insertions;
364
+ deletions = recomputed.deletions;
365
+ }
342
366
  }
343
- } catch { /* use files_changed from DB */ }
367
+ } catch { /* use stored values */ }
344
368
  }
345
369
 
346
370
  return { filesChanged, insertions, deletions };
@@ -19,6 +19,7 @@ import {
19
19
  } from '../../files/file-reading';
20
20
  import { handlePathBrowsing } from '../../files/path-browsing';
21
21
  import { gitService } from '../../git/git-service';
22
+ import { findRepoForFile } from '../../snapshot/gitignore';
22
23
  import { projectQueries } from '../../database/queries/project-queries';
23
24
  import { isAbsolute, relative } from 'node:path';
24
25
  import { requireProjectAccess } from '../access';
@@ -207,7 +208,15 @@ export const readHandler = createRouter()
207
208
  // Normalize path separators for git
208
209
  relativePath = relativePath.replace(/\\/g, '/');
209
210
 
210
- const content = await gitService.getFileAtRef(project.path, ref, relativePath);
211
+ // Route to the nested repo that owns the file (if any) — the outer
212
+ // repo's `git show HEAD:file` returns nothing for files tracked
213
+ // inside a nested repo and gitignored by the parent, so the editor
214
+ // gutter diff would silently go empty for subrepo files without this.
215
+ const repo = await findRepoForFile(project.path, relativePath);
216
+ const cwd = repo?.repoPath ?? project.path;
217
+ const gitFilePath = repo?.relativeFilePath ?? relativePath;
218
+
219
+ const content = await gitService.getFileAtRef(cwd, ref, gitFilePath);
211
220
  return { content, ref };
212
221
  })
213
222
 
@@ -112,6 +112,20 @@ Rules:
112
112
  - Do not include ticket IDs unless they appear in the diff`;
113
113
  }
114
114
 
115
+ import path from 'node:path';
116
+
117
+ function resolveRepoCwd(projectPath: string, repoPath: string | undefined): string {
118
+ if (!repoPath) return projectPath;
119
+ const resolved = path.resolve(repoPath);
120
+ const projectRoot = path.resolve(projectPath);
121
+ const sep = path.sep;
122
+ if (resolved !== projectRoot && !resolved.startsWith(projectRoot + sep)) {
123
+ debug.warn('git', `Rejected nested repoPath outside project: ${resolved}`);
124
+ return projectPath;
125
+ }
126
+ return resolved;
127
+ }
128
+
115
129
  export const branchNameHandler = createRouter()
116
130
  .http('git:generate-branch-name', {
117
131
  data: t.Object({
@@ -121,15 +135,17 @@ export const branchNameHandler = createRouter()
121
135
  modelId: t.String(),
122
136
  branchSeparator: t.Optional(t.String()),
123
137
  maxWords: t.Optional(t.Number()),
124
- customPrompt: t.Optional(t.String())
138
+ customPrompt: t.Optional(t.String()),
139
+ repoPath: t.Optional(t.String())
125
140
  }),
126
141
  response: t.Object({
127
142
  branchName: t.String()
128
143
  })
129
144
  }, async ({ data, conn }) => {
130
145
  const project = requireProjectAccess(conn, data.projectId);
146
+ const cwd = resolveRepoCwd(project.path, data.repoPath);
131
147
 
132
- const diffResult = await execGit(['diff', '--cached'], project.path);
148
+ const diffResult = await execGit(['diff', '--cached'], cwd);
133
149
  const rawDiff = diffResult.stdout;
134
150
 
135
151
  if (!rawDiff.trim()) {
@@ -143,7 +159,7 @@ export const branchNameHandler = createRouter()
143
159
  throw new Error(`Engine "${engineType}" does not support structured generation`);
144
160
  }
145
161
 
146
- const branchResult = await execGit(['branch', '--show-current'], project.path);
162
+ const branchResult = await execGit(['branch', '--show-current'], cwd);
147
163
  const currentBranch = branchResult.stdout.trim();
148
164
  const prefix = getBranchPrefix(currentBranch);
149
165
  const separator = normalizeBranchSeparator(data.branchSeparator);
@@ -158,7 +174,7 @@ export const branchNameHandler = createRouter()
158
174
  providerSlug: data.providerSlug,
159
175
  modelId: data.modelId,
160
176
  schema: BRANCH_NAME_SCHEMA,
161
- projectPath: project.path
177
+ projectPath: cwd
162
178
  });
163
179
 
164
180
  const description = sanitizeBranchDescription(result.description, data.maxWords ?? MAX_BRANCH_DESCRIPTION_WORDS);