@innovatorved/code-lab 0.5.0 → 0.6.0

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 (67) hide show
  1. package/ARCHITECTURE.md +3 -3
  2. package/CHANGELOG.md +15 -0
  3. package/README.md +3 -3
  4. package/dist/code-lab-sql.esm.js +1 -1
  5. package/dist/code-lab-sql.umd.js +2 -2
  6. package/dist/code-lab.css +32 -7273
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +4669 -74678
  9. package/dist/code-lab.js +4655 -74665
  10. package/dist/code-lab.umd.js +4655 -74665
  11. package/dist/extensions/cpp.d.ts +2 -2
  12. package/dist/extensions/cpp.esm.js +1788 -14707
  13. package/dist/extensions/cpp.js +1788 -14707
  14. package/dist/extensions/guided-lab.esm.js +2938 -16127
  15. package/dist/extensions/guided-lab.js +2938 -16127
  16. package/dist/extensions/python.d.ts +2 -2
  17. package/dist/extensions/python.esm.js +1769 -14701
  18. package/dist/extensions/python.js +1769 -14701
  19. package/dist/index.d.ts +1 -1
  20. package/dist/preview-sw.js +4 -188
  21. package/dist/runtime.esm.js +109 -10284
  22. package/dist/runtime.js +107 -10284
  23. package/dist/schemas.d.ts +2 -2
  24. package/dist/schemas.esm.js +2938 -16127
  25. package/dist/schemas.js +2941 -16130
  26. package/dist/scm.d.ts +221 -20
  27. package/dist/shell.esm.js +811 -10002
  28. package/dist/shell.js +811 -10002
  29. package/dist/storage.d.ts +9 -0
  30. package/dist/terminal.esm.js +20 -1347
  31. package/dist/terminal.js +20 -1347
  32. package/dist/workbench/command-palette.d.ts +16 -1
  33. package/dist/workbench/diff-editor.d.ts +27 -1
  34. package/dist/workbench/icons.d.ts +6 -2
  35. package/dist/workbench/index.d.ts +32 -0
  36. package/dist/workbench/intellisense.d.ts +194 -0
  37. package/dist/workbench/xterm-adapter.d.ts +122 -0
  38. package/package.json +7 -1
  39. package/packages/commands/package.json +1 -1
  40. package/packages/core/package.json +1 -1
  41. package/packages/editor/package.json +1 -1
  42. package/packages/fs/package.json +1 -1
  43. package/packages/preview/package.json +1 -1
  44. package/packages/runtime/package.json +1 -1
  45. package/packages/settings/package.json +1 -1
  46. package/packages/sql/package.json +1 -1
  47. package/packages/terminal/package.json +1 -1
  48. package/packages/ui/package.json +1 -1
  49. package/packages/ui/src/settings-dialog.ts +36 -24
  50. package/packages/ui/src/themes.ts +89 -23
  51. package/src/code-lab.css +1345 -481
  52. package/src/extensions/cpp.ts +304 -38
  53. package/src/extensions/python.ts +342 -43
  54. package/src/index.ts +1 -1
  55. package/src/runtime.ts +272 -43
  56. package/src/schemas.ts +2 -2
  57. package/src/scm.ts +1467 -92
  58. package/src/shell.ts +1075 -93
  59. package/src/storage.ts +66 -3
  60. package/src/terminal.ts +148 -12
  61. package/src/workbench/command-palette.ts +289 -48
  62. package/src/workbench/diff-editor.ts +240 -78
  63. package/src/workbench/icons.ts +250 -53
  64. package/src/workbench/index.ts +7 -1
  65. package/src/workbench/intellisense.ts +1859 -0
  66. package/src/workbench/xterm-adapter.ts +1566 -0
  67. package/src/workbench.ts +1605 -236
package/src/scm.ts CHANGED
@@ -1,13 +1,31 @@
1
1
  /**
2
2
  * @innovatorved/code-lab — Interactive Git Source Control (SCM) Engine
3
3
  * ============================================================================
4
- * Pure TypeScript in-browser Git status, staging, unstaging, discard, and
5
- * commit engine backed by workspace VFS state. Powers both the interactive
6
- * Source Control UI and shell/CLI Git operations with a unified GitState schema.
4
+ * Browser-native Git engine combining synchronous deterministic VFS/SCM state
5
+ * with `isomorphic-git` `.git/` object-store synchronization, Myers O(ND)
6
+ * 3-line hunk diffs, `.gitignore` pattern matching, real branch file checkout,
7
+ * stash, reset (`--soft`/`--mixed`/`--hard` `HEAD~N`), merge, tags, show & blame.
7
8
  *
8
9
  * Strict leaf module: fully typed, zero explicit any, zero empty catches.
9
10
  */
10
11
 
12
+ import { Buffer as BrowserBuffer } from 'buffer';
13
+ import {
14
+ init as isoInit,
15
+ add as isoAdd,
16
+ commit as isoCommit,
17
+ currentBranch as isoCurrentBranch,
18
+ listBranches as isoListBranches,
19
+ log as isoLog
20
+ } from 'isomorphic-git';
21
+
22
+ if (typeof globalThis !== 'undefined') {
23
+ const g = globalThis as unknown as Record<string, unknown>;
24
+ if (typeof g.Buffer === 'undefined') {
25
+ g.Buffer = BrowserBuffer;
26
+ }
27
+ }
28
+
11
29
  export type GitFileChangeType = 'modified' | 'added' | 'deleted' | 'untracked';
12
30
 
13
31
  export interface GitFileStatus {
@@ -18,15 +36,28 @@ export interface GitFileStatus {
18
36
  newContent?: string;
19
37
  }
20
38
 
39
+ export interface GitStatLike {
40
+ size?: number;
41
+ mtimeMs?: number;
42
+ mode?: number;
43
+ isDirectory(): boolean;
44
+ isFile?(): boolean;
45
+ isSymbolicLink?(): boolean;
46
+ }
47
+
21
48
  export interface GitVfsLike {
22
49
  existsSync?(path: string): boolean;
23
- statSync?(path: string): { isDirectory(): boolean };
50
+ statSync?(path: string): GitStatLike;
51
+ lstatSync?(path: string): GitStatLike;
24
52
  readdirSync?(path: string): string[];
25
53
  readFileSync?(path: string, encoding?: string): string | Uint8Array;
26
- writeFileSync?(path: string, data: string): void;
54
+ writeFileSync?(path: string, data: string | Uint8Array): void;
27
55
  mkdirSync?(path: string, options?: { recursive?: boolean }): unknown;
56
+ rmdirSync?(path: string, options?: { recursive?: boolean }): void;
28
57
  unlinkSync?(path: string): void;
29
58
  rmSync?(path: string, options?: { recursive?: boolean; force?: boolean }): void;
59
+ symlinkSync?(target: string, path: string): void;
60
+ readlinkSync?(path: string): string;
30
61
  files?: Map<string, unknown>;
31
62
  }
32
63
 
@@ -44,6 +75,24 @@ export interface GitCommitRecord {
44
75
  author?: string;
45
76
  date?: string;
46
77
  files?: Record<string, string>;
78
+ parents?: string[];
79
+ }
80
+
81
+ export interface GitBranchTip {
82
+ headCommit: string;
83
+ headFiles: Record<string, string>;
84
+ commits: GitCommitRecord[];
85
+ }
86
+
87
+ export interface GitStashEntry {
88
+ id: number;
89
+ branch: string;
90
+ headCommit: string;
91
+ message: string;
92
+ timestamp: number;
93
+ worktreeFiles: Record<string, string>;
94
+ stagedEntries: Array<[string, string | null]>;
95
+ untrackedFiles: Record<string, string>;
47
96
  }
48
97
 
49
98
  export interface GitState {
@@ -51,6 +100,9 @@ export interface GitState {
51
100
  repoRoot?: string;
52
101
  branch: string;
53
102
  branches?: string[] | Set<string>;
103
+ branchHeads?: Record<string, GitBranchTip>;
104
+ tags?: Record<string, string>;
105
+ stashes?: GitStashEntry[];
54
106
  remoteUrl?: string | null;
55
107
  remotes?: Record<string, string>;
56
108
  headCommit: string;
@@ -94,6 +146,37 @@ export interface InitRepositoryOptions {
94
146
  initialFiles?: Record<string, string>;
95
147
  }
96
148
 
149
+ export interface DiscardChangesOptions {
150
+ keepStaged?: boolean;
151
+ }
152
+
153
+ export interface DiffLineOp {
154
+ type: 'common' | 'added' | 'removed';
155
+ line: string;
156
+ oldLineNumber?: number;
157
+ newLineNumber?: number;
158
+ }
159
+
160
+ export interface GitGutterRange {
161
+ line: number;
162
+ endLine: number;
163
+ kind: 'added' | 'modified' | 'deleted';
164
+ }
165
+
166
+ export interface GitIgnoreRule {
167
+ negated: boolean;
168
+ dirOnly: boolean;
169
+ regex: RegExp;
170
+ }
171
+
172
+ export interface BlameLineEntry {
173
+ lineNumber: number;
174
+ hash: string;
175
+ author: string;
176
+ timestamp: number;
177
+ content: string;
178
+ }
179
+
97
180
  /**
98
181
  * Computes a deterministic 7-character short hash for a commit payload.
99
182
  */
@@ -111,7 +194,83 @@ export function computeShortCommitHash(input: string): string {
111
194
  return combined.toString(16).padStart(7, '0').slice(0, 7);
112
195
  }
113
196
 
114
- export function isIgnoredScmPath(relPath: string): boolean {
197
+ /**
198
+ * Compiles `.gitignore` text into ordered glob/negation match rules.
199
+ */
200
+ export function parseGitignoreRules(gitignoreContent: string | undefined): GitIgnoreRule[] {
201
+ if (!gitignoreContent || typeof gitignoreContent !== 'string') return [];
202
+ const rules: GitIgnoreRule[] = [];
203
+ for (const rawLine of gitignoreContent.split(/\r?\n/)) {
204
+ let line = rawLine.trim();
205
+ if (!line || line.startsWith('#')) continue;
206
+ let negated = false;
207
+ if (line.startsWith('!')) {
208
+ negated = true;
209
+ line = line.slice(1).trim();
210
+ if (!line) continue;
211
+ }
212
+ const dirOnly = line.endsWith('/');
213
+ if (dirOnly) line = line.replace(/\/+$/, '');
214
+ const anchored = line.startsWith('/');
215
+ if (anchored) line = line.replace(/^\/+/, '');
216
+ if (!line) continue;
217
+
218
+ const hasSlash = line.includes('/');
219
+ let rxBody = '';
220
+ for (let i = 0; i < line.length; i++) {
221
+ const c = line[i];
222
+ if (c === '*') {
223
+ if (line[i + 1] === '*') {
224
+ if (line[i + 2] === '/') {
225
+ rxBody += '(?:.+/)?';
226
+ i += 2;
227
+ } else {
228
+ rxBody += '.*';
229
+ i += 1;
230
+ }
231
+ } else {
232
+ rxBody += '[^/]*';
233
+ }
234
+ } else if (c === '?') {
235
+ rxBody += '[^/]';
236
+ } else if ('\\^$.|+()[]{}'.includes(c)) {
237
+ rxBody += `\\${c}`;
238
+ } else {
239
+ rxBody += c;
240
+ }
241
+ }
242
+
243
+ const prefix = anchored || hasSlash ? '^' : '(?:^|/)';
244
+ const suffix = dirOnly ? '(?:/|$)' : '(?:$|/)';
245
+ try {
246
+ rules.push({
247
+ negated,
248
+ dirOnly,
249
+ regex: new RegExp(`${prefix}${rxBody}${suffix}`)
250
+ });
251
+ } catch (err) {
252
+ const _ignored = err;
253
+ void _ignored;
254
+ }
255
+ }
256
+ return rules;
257
+ }
258
+
259
+ export function isIgnoredByRules(relPath: string, rules: ReadonlyArray<GitIgnoreRule>): boolean {
260
+ if (!rules.length) return false;
261
+ let ignored = false;
262
+ for (const rule of rules) {
263
+ if (rule.regex.test(relPath)) {
264
+ ignored = !rule.negated;
265
+ }
266
+ }
267
+ return ignored;
268
+ }
269
+
270
+ export function isIgnoredScmPath(
271
+ relPath: string,
272
+ gitignoreRules?: ReadonlyArray<GitIgnoreRule>
273
+ ): boolean {
115
274
  if (!relPath) return true;
116
275
  if (
117
276
  relPath === '.git' ||
@@ -129,6 +288,9 @@ export function isIgnoredScmPath(relPath: string): boolean {
129
288
  ) {
130
289
  return true;
131
290
  }
291
+ if (gitignoreRules && gitignoreRules.length > 0 && relPath !== '.gitignore') {
292
+ return isIgnoredByRules(relPath, gitignoreRules);
293
+ }
132
294
  return false;
133
295
  }
134
296
 
@@ -141,8 +303,13 @@ export function normalizeScmRelPath(rawPath: string, repoRoot = '/workspace'): s
141
303
  if (p === cleanRoot) return '';
142
304
  if (cleanRoot !== '/' && p.startsWith(`${cleanRoot}/`)) {
143
305
  p = p.slice(cleanRoot.length + 1);
144
- } else if (p.startsWith('/workspace/')) {
306
+ } else if (p.startsWith('/workspace/') && cleanRoot === '/workspace') {
145
307
  p = p.slice('/workspace/'.length);
308
+ } else if (p.startsWith('/') && cleanRoot !== '/') {
309
+ // Path outside non-default repoRoot is ignored unless relative
310
+ if (!p.startsWith(`${cleanRoot}/`)) {
311
+ p = p.replace(/^\/+/, '');
312
+ }
146
313
  }
147
314
 
148
315
  while (p.startsWith('./')) {
@@ -165,15 +332,41 @@ export function normalizeScmRelPath(rawPath: string, repoRoot = '/workspace'): s
165
332
  return out.join('/');
166
333
  }
167
334
 
168
- function cleanFileMap(
335
+ function extractGitignoreRules(
169
336
  rawFiles: Record<string, string> | undefined,
337
+ fallbackFiles: Record<string, string> | undefined,
170
338
  repoRoot = '/workspace'
339
+ ): GitIgnoreRule[] {
340
+ let content: string | undefined;
341
+ if (rawFiles && typeof rawFiles === 'object') {
342
+ if (typeof rawFiles['.gitignore'] === 'string') {
343
+ content = rawFiles['.gitignore'];
344
+ } else {
345
+ const fullKey = `${repoRoot.replace(/\/+$/, '')}/.gitignore`;
346
+ if (typeof rawFiles[fullKey] === 'string') content = rawFiles[fullKey];
347
+ }
348
+ }
349
+ if (content === undefined && fallbackFiles && typeof fallbackFiles['.gitignore'] === 'string') {
350
+ content = fallbackFiles['.gitignore'];
351
+ }
352
+ return parseGitignoreRules(content);
353
+ }
354
+
355
+ function cleanFileMap(
356
+ rawFiles: Record<string, string> | undefined,
357
+ repoRoot = '/workspace',
358
+ gitignoreRules?: ReadonlyArray<GitIgnoreRule>,
359
+ trackedFiles?: Record<string, string>
171
360
  ): Record<string, string> {
172
361
  const out: Record<string, string> = {};
173
362
  if (!rawFiles || typeof rawFiles !== 'object') return out;
174
363
  for (const [k, v] of Object.entries(rawFiles)) {
175
364
  const rel = normalizeScmRelPath(k, repoRoot);
176
365
  if (!rel || isIgnoredScmPath(rel)) continue;
366
+ const isTracked = Boolean(trackedFiles && Object.prototype.hasOwnProperty.call(trackedFiles, rel));
367
+ if (!isTracked && gitignoreRules && isIgnoredScmPath(rel, gitignoreRules)) {
368
+ continue;
369
+ }
177
370
  out[rel] = String(v ?? '');
178
371
  }
179
372
  return out;
@@ -294,6 +487,40 @@ export function syncGitHead(
294
487
  return synced;
295
488
  }
296
489
 
490
+ function ensureBranchList(gitState: GitState, branchName?: string): void {
491
+ if (gitState.branches instanceof Set) {
492
+ if (branchName) gitState.branches.add(branchName);
493
+ return;
494
+ }
495
+ if (Array.isArray(gitState.branches)) {
496
+ if (branchName && !gitState.branches.includes(branchName)) {
497
+ gitState.branches.push(branchName);
498
+ }
499
+ return;
500
+ }
501
+ gitState.branches = branchName ? [branchName] : [gitState.branch || 'main'];
502
+ }
503
+
504
+ export function saveBranchTip(gitState: GitState, branchName = gitState.branch): void {
505
+ if (!gitState || !branchName) return;
506
+ if (!gitState.branchHeads || typeof gitState.branchHeads !== 'object') {
507
+ gitState.branchHeads = {};
508
+ }
509
+ const repoRoot = gitState.repoRoot || '/workspace';
510
+ const headCopy = cleanFileMap(gitState.headFiles || gitState.headSnapshot || {}, repoRoot);
511
+ const commitsCopy = Array.isArray(gitState.commits)
512
+ ? gitState.commits.map((c) => ({
513
+ ...c,
514
+ ...(c.files ? { files: { ...c.files } } : {})
515
+ }))
516
+ : [];
517
+ gitState.branchHeads[branchName] = {
518
+ headCommit: gitState.headCommit || '',
519
+ headFiles: headCopy,
520
+ commits: commitsCopy
521
+ };
522
+ }
523
+
297
524
  function ensureStagedMap(
298
525
  gitState: GitState,
299
526
  vfsFiles?: Record<string, string>
@@ -361,6 +588,17 @@ export function createGitState(
361
588
  const stateObj = {
362
589
  branch,
363
590
  branches: [branch],
591
+ branchHeads: isInit
592
+ ? {
593
+ [branch]: {
594
+ headCommit: _headCommit,
595
+ headFiles: { ..._headFiles },
596
+ commits: _commits.map((c) => ({ ...c, files: { ..._headFiles } }))
597
+ }
598
+ }
599
+ : {},
600
+ tags: {} as Record<string, string>,
601
+ stashes: [] as GitStashEntry[],
364
602
  remoteUrl: null as string | null,
365
603
  remotes: {} as Record<string, string>
366
604
  } as unknown as GitState;
@@ -481,7 +719,7 @@ export function createGitState(
481
719
  return stateObj;
482
720
  }
483
721
 
484
- function readVfsTree(vfs: GitVfsLike, rootDir: string): Record<string, string> {
722
+ export function readVfsTree(vfs: GitVfsLike, rootDir: string): Record<string, string> {
485
723
  const out: Record<string, string> = {};
486
724
  if (
487
725
  !vfs ||
@@ -545,12 +783,11 @@ export function initRepository(
545
783
  options?: InitRepositoryOptions
546
784
  ): GitState {
547
785
  if (isGitShellLike(target)) {
548
- const repoRoot = (
549
- options?.repoRoot ||
550
- target.gitState?.repoRoot ||
551
- target.cwd ||
552
- '/workspace'
553
- ).replace(/\/+$/, '') || '/';
786
+ const repoRoot =
787
+ (options?.repoRoot || target.gitState?.repoRoot || target.cwd || '/workspace').replace(
788
+ /\/+$/,
789
+ ''
790
+ ) || '/';
554
791
  const branch = options?.branch || target.gitState?.branch || 'main';
555
792
  const vfs = target.vfs ?? null;
556
793
 
@@ -570,9 +807,11 @@ export function initRepository(
570
807
  }
571
808
 
572
809
  const snap = options?.snapshotExisting
573
- ? (options.initialFiles
574
- ? cleanFileMap(options.initialFiles, repoRoot)
575
- : (vfs ? readVfsTree(vfs, repoRoot) : {}))
810
+ ? options.initialFiles
811
+ ? cleanFileMap(options.initialFiles, repoRoot)
812
+ : vfs
813
+ ? readVfsTree(vfs, repoRoot)
814
+ : {}
576
815
  : {};
577
816
 
578
817
  let gs = target.gitState;
@@ -582,25 +821,23 @@ export function initRepository(
582
821
  gs.commits = [];
583
822
  gs.headCommit = '';
584
823
  }
824
+ saveBranchTip(gs, branch);
585
825
  target.gitState = gs;
826
+ if (vfs) void syncToIsoGitRepo(vfs, gs);
586
827
  return gs;
587
828
  }
588
829
 
589
830
  gs.initialized = true;
590
831
  gs.repoRoot = repoRoot;
591
832
  gs.branch = branch;
592
- if (gs.branches instanceof Set) {
593
- gs.branches.add(branch);
594
- } else if (Array.isArray(gs.branches)) {
595
- if (!gs.branches.includes(branch)) gs.branches.push(branch);
596
- } else {
597
- gs.branches = [branch];
598
- }
833
+ ensureBranchList(gs, branch);
599
834
  ensureStagedMap(gs).clear();
600
835
  syncGitHead(gs, snap);
601
836
  if (!options?.snapshotExisting && gs.commits.length === 0) {
602
837
  gs.headCommit = '';
603
838
  }
839
+ saveBranchTip(gs, branch);
840
+ if (vfs) void syncToIsoGitRepo(vfs, gs);
604
841
  return gs;
605
842
  }
606
843
 
@@ -610,22 +847,16 @@ export function initRepository(
610
847
  gs.initialized = true;
611
848
  gs.repoRoot = repoRoot;
612
849
  gs.branch = branch;
613
- if (gs.branches instanceof Set) {
614
- gs.branches.add(branch);
615
- } else if (Array.isArray(gs.branches)) {
616
- if (!gs.branches.includes(branch)) gs.branches.push(branch);
617
- } else {
618
- gs.branches = [branch];
619
- }
850
+ ensureBranchList(gs, branch);
620
851
  ensureStagedMap(gs).clear();
621
- syncGitHead(gs, options?.snapshotExisting ? (options.initialFiles || {}) : {});
852
+ syncGitHead(gs, options?.snapshotExisting ? options.initialFiles || {} : {});
853
+ saveBranchTip(gs, branch);
622
854
  return gs;
623
855
  }
624
856
 
625
857
  /**
626
- * Computes working-tree and staging-area Git status against `gitState`.
627
- * Supports both `computeGitStatus(vfsFiles, repoRoot, gitState)` and
628
- * `computeGitStatus(gitState, vfsFiles)` calling conventions.
858
+ * Computes working-tree and staging-area Git status against `gitState`,
859
+ * honoring `.gitignore` rules for untracked files while keeping tracked files visible.
629
860
  */
630
861
  export function computeGitStatus(
631
862
  arg1: Record<string, string> | GitState,
@@ -646,12 +877,13 @@ export function computeGitStatus(
646
877
  repoRoot = state.repoRoot || '/workspace';
647
878
  } else {
648
879
  rawVfsFiles = (arg1 && typeof arg1 === 'object' ? arg1 : {}) as Record<string, string>;
649
- repoRoot = typeof arg2 === 'string' && arg2 ? arg2 : (gitState?.repoRoot || '/workspace');
880
+ repoRoot = typeof arg2 === 'string' && arg2 ? arg2 : gitState?.repoRoot || '/workspace';
650
881
  state = gitState || createGitState({});
651
882
  }
652
883
 
653
- const vfsFiles = cleanFileMap(rawVfsFiles, repoRoot);
654
884
  const headFiles = cleanFileMap(state.headFiles || state.headSnapshot || {}, repoRoot);
885
+ const ignoreRules = extractGitignoreRules(rawVfsFiles, headFiles, repoRoot);
886
+ const vfsFiles = cleanFileMap(rawVfsFiles, repoRoot, ignoreRules, headFiles);
655
887
  const unbornHead = isUnbornGitHead(state);
656
888
 
657
889
  const currentStaged = new Map<string, string | null>();
@@ -674,6 +906,18 @@ export function computeGitStatus(
674
906
  }
675
907
  }
676
908
 
909
+ // Ensure files explicitly staged remain visible in vfsFiles comparison even if matched by .gitignore
910
+ for (const stagedPath of currentStaged.keys()) {
911
+ if (!Object.prototype.hasOwnProperty.call(vfsFiles, stagedPath)) {
912
+ const rawKey = `${repoRoot.replace(/\/+$/, '')}/${stagedPath}`;
913
+ if (Object.prototype.hasOwnProperty.call(rawVfsFiles, stagedPath)) {
914
+ vfsFiles[stagedPath] = String(rawVfsFiles[stagedPath] ?? '');
915
+ } else if (Object.prototype.hasOwnProperty.call(rawVfsFiles, rawKey)) {
916
+ vfsFiles[stagedPath] = String(rawVfsFiles[rawKey] ?? '');
917
+ }
918
+ }
919
+ }
920
+
677
921
  const untracked: GitFileStatus[] = [];
678
922
  const modified: GitFileStatus[] = [];
679
923
  const deleted: GitFileStatus[] = [];
@@ -699,7 +943,6 @@ export function computeGitStatus(
699
943
  oldContent: effectiveInHead ? headFiles[filePath] : undefined,
700
944
  newContent: stagedContent
701
945
  });
702
- // Detect worktree deletion of a staged file (MD / AD)
703
946
  if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath)) {
704
947
  deleted.push({
705
948
  path: filePath,
@@ -715,7 +958,6 @@ export function computeGitStatus(
715
958
  if (currentStaged.has(filePath)) {
716
959
  const stagedVal = currentStaged.get(filePath);
717
960
  if (stagedVal === null) {
718
- // Staged for deletion, then recreated in working tree
719
961
  untracked.push({
720
962
  path: filePath,
721
963
  status: 'untracked',
@@ -784,20 +1026,24 @@ export function computeGitStatus(
784
1026
  index: stagedIndexByPath.get(s.path) || 'M',
785
1027
  worktree: modifiedPaths.has(s.path) ? 'M' : deletedPaths.has(s.path) ? 'D' : ' '
786
1028
  })),
787
- ...modified.map((m) => ({
788
- path: m.path,
789
- status: m.status,
790
- staged: false,
791
- index: stagedIndexByPath.get(m.path) || ' ',
792
- worktree: 'M'
793
- })),
794
- ...deleted.map((d) => ({
795
- path: d.path,
796
- status: d.status,
797
- staged: false,
798
- index: stagedIndexByPath.get(d.path) || ' ',
799
- worktree: 'D'
800
- })),
1029
+ ...modified
1030
+ .filter((m) => !stagedIndexByPath.has(m.path))
1031
+ .map((m) => ({
1032
+ path: m.path,
1033
+ status: m.status,
1034
+ staged: false,
1035
+ index: ' ',
1036
+ worktree: 'M'
1037
+ })),
1038
+ ...deleted
1039
+ .filter((d) => !stagedIndexByPath.has(d.path))
1040
+ .map((d) => ({
1041
+ path: d.path,
1042
+ status: d.status,
1043
+ staged: false,
1044
+ index: ' ',
1045
+ worktree: 'D'
1046
+ })),
801
1047
  ...untracked.map((u) => ({
802
1048
  path: u.path,
803
1049
  status: u.status,
@@ -848,7 +1094,7 @@ export function stageFile(
848
1094
  }
849
1095
 
850
1096
  /**
851
- * Stages all modified, untracked (non-ignored), and deleted tracked files.
1097
+ * Stages all modified, untracked (non-gitignored), and deleted tracked files.
852
1098
  */
853
1099
  export function stageAll(
854
1100
  gitState: GitState,
@@ -857,8 +1103,9 @@ export function stageAll(
857
1103
  ): void {
858
1104
  if (!gitState) return;
859
1105
  const resolvedRoot = gitState.repoRoot || repoRoot || '/workspace';
860
- const cleanVfs = cleanFileMap(vfsFiles, resolvedRoot);
861
1106
  const headFiles = cleanFileMap(gitState.headFiles || gitState.headSnapshot || {}, resolvedRoot);
1107
+ const ignoreRules = extractGitignoreRules(vfsFiles, headFiles, resolvedRoot);
1108
+ const cleanVfs = cleanFileMap(vfsFiles, resolvedRoot, ignoreRules, headFiles);
862
1109
  const stagedMap = ensureStagedMap(gitState, cleanVfs);
863
1110
 
864
1111
  for (const [rel, content] of Object.entries(cleanVfs)) {
@@ -909,9 +1156,8 @@ export function unstageAll(gitState: GitState): void {
909
1156
  }
910
1157
 
911
1158
  /**
912
- * Commits all staged changes to `gitState`, advancing `headCommit` and
913
- * synchronizing `headFiles` & `headSnapshot`, prepending the new commit record,
914
- * and clearing the staging area. Throws if message or staging area is empty.
1159
+ * Commits all staged changes to `gitState`, advancing `headCommit`, updating
1160
+ * `branchHeads[branch]`, synchronizing `headFiles` & `headSnapshot`, and clearing staging.
915
1161
  */
916
1162
  export function commitChanges(
917
1163
  gitState: GitState,
@@ -951,6 +1197,7 @@ export function commitChanges(
951
1197
 
952
1198
  const timestamp = Date.now();
953
1199
  const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
1200
+ const parentHashes = gitState.headCommit ? [gitState.headCommit] : [];
954
1201
  const hash = computeShortCommitHash(
955
1202
  `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join('|')}`
956
1203
  );
@@ -961,7 +1208,8 @@ export function commitChanges(
961
1208
  timestamp,
962
1209
  author,
963
1210
  date: new Date(timestamp).toUTCString(),
964
- files: { ...syncedHead }
1211
+ files: { ...syncedHead },
1212
+ parents: parentHashes
965
1213
  };
966
1214
 
967
1215
  if (!Array.isArray(gitState.commits)) {
@@ -971,20 +1219,62 @@ export function commitChanges(
971
1219
  gitState.initialized = true;
972
1220
  gitState.headCommit = hash;
973
1221
  stagedMap.clear();
1222
+ ensureBranchList(gitState, gitState.branch || 'main');
1223
+ saveBranchTip(gitState, gitState.branch || 'main');
974
1224
 
975
1225
  return hash;
976
1226
  }
977
1227
 
1228
+ function writeVfsFileSafe(
1229
+ vfs: GitVfsLike | null,
1230
+ absPath: string,
1231
+ content: string,
1232
+ shell?: GitShellLike
1233
+ ): void {
1234
+ if (!vfs) return;
1235
+ const lastSlash = absPath.lastIndexOf('/');
1236
+ const parentDir = lastSlash > 0 ? absPath.slice(0, lastSlash) : '/';
1237
+ if (
1238
+ parentDir &&
1239
+ typeof vfs.mkdirSync === 'function' &&
1240
+ (typeof vfs.existsSync !== 'function' || !vfs.existsSync(parentDir))
1241
+ ) {
1242
+ vfs.mkdirSync(parentDir, { recursive: true });
1243
+ }
1244
+ vfs.writeFileSync?.(absPath, content);
1245
+ shell?._emitVfsMutation?.('change', absPath);
1246
+ }
1247
+
1248
+ function deleteVfsFileSafe(
1249
+ vfs: GitVfsLike | null,
1250
+ absPath: string,
1251
+ shell?: GitShellLike
1252
+ ): void {
1253
+ if (!vfs) return;
1254
+ if (typeof vfs.rmSync === 'function') {
1255
+ vfs.rmSync(absPath, { force: true });
1256
+ } else if (typeof vfs.unlinkSync === 'function') {
1257
+ if (typeof vfs.existsSync !== 'function' || vfs.existsSync(absPath)) {
1258
+ vfs.unlinkSync(absPath);
1259
+ }
1260
+ } else if (vfs.files instanceof Map) {
1261
+ vfs.files.delete(absPath);
1262
+ }
1263
+ shell?._emitVfsMutation?.('delete', absPath);
1264
+ }
1265
+
978
1266
  /**
979
- * Discards working-tree (and staged) changes for `filePath`:
980
- * - If tracked in `HEAD`, restores `headFiles[relPath]` to `shell.vfs` (creating
981
- * parent directories first) and optional `workspaceFiles`.
982
- * - If untracked, deletes the file from `shell.vfs` and optional `workspaceFiles`.
1267
+ * Discards working-tree changes for `filePath`.
1268
+ * - When `options?.keepStaged === true` and `filePath` has a staged snapshot (`MM` / `AM`),
1269
+ * restores the working tree to the staged index snapshot without unstaging!
1270
+ * - Otherwise restores `headFiles[relPath]` (if tracked) or deletes the untracked file,
1271
+ * and unstages `relPath`.
983
1272
  */
984
1273
  export function discardChanges(
985
1274
  shell: GitShellLike,
986
1275
  filePath: string,
987
- workspaceFiles?: Record<string, string>
1276
+ workspaceFiles?: Record<string, string>,
1277
+ options?: DiscardChangesOptions
988
1278
  ): boolean {
989
1279
  if (!shell || typeof filePath !== 'string' || !filePath.trim()) {
990
1280
  return false;
@@ -1001,28 +1291,33 @@ export function discardChanges(
1001
1291
  const headFiles = gs ? cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot) : {};
1002
1292
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
1003
1293
  const vfs = shell.vfs ?? null;
1294
+ const stagedMap = gs ? ensureStagedMap(gs) : null;
1295
+
1296
+ if (options?.keepStaged && stagedMap && stagedMap.has(relPath)) {
1297
+ const stagedVal = stagedMap.get(relPath);
1298
+ if (stagedVal !== null && stagedVal !== undefined) {
1299
+ writeVfsFileSafe(vfs, absPath, stagedVal, shell);
1300
+ if (workspaceFiles && typeof workspaceFiles === 'object') {
1301
+ workspaceFiles[relPath] = stagedVal;
1302
+ }
1303
+ return true;
1304
+ }
1305
+ deleteVfsFileSafe(vfs, absPath, shell);
1306
+ if (workspaceFiles && typeof workspaceFiles === 'object') {
1307
+ delete workspaceFiles[relPath];
1308
+ }
1309
+ return true;
1310
+ }
1004
1311
 
1005
1312
  if (inHead) {
1006
1313
  const headContent = headFiles[relPath];
1007
- if (vfs) {
1008
- const lastSlash = absPath.lastIndexOf('/');
1009
- const parentDir = lastSlash > 0 ? absPath.slice(0, lastSlash) : '/';
1010
- if (
1011
- parentDir &&
1012
- typeof vfs.mkdirSync === 'function' &&
1013
- (typeof vfs.existsSync !== 'function' || !vfs.existsSync(parentDir))
1014
- ) {
1015
- vfs.mkdirSync(parentDir, { recursive: true });
1016
- }
1017
- vfs.writeFileSync?.(absPath, headContent);
1018
- }
1314
+ writeVfsFileSafe(vfs, absPath, headContent, shell);
1019
1315
  if (workspaceFiles && typeof workspaceFiles === 'object') {
1020
1316
  workspaceFiles[relPath] = headContent;
1021
1317
  }
1022
1318
  if (gs) {
1023
1319
  unstageFile(gs, relPath);
1024
1320
  }
1025
- shell._emitVfsMutation?.('change', absPath);
1026
1321
  return true;
1027
1322
  }
1028
1323
 
@@ -1031,23 +1326,13 @@ export function discardChanges(
1031
1326
  const existsInWs = Boolean(
1032
1327
  workspaceFiles && Object.prototype.hasOwnProperty.call(workspaceFiles, relPath)
1033
1328
  );
1034
- const existsInStaged = Boolean(gs && ensureStagedMap(gs).has(relPath));
1329
+ const existsInStaged = Boolean(stagedMap && stagedMap.has(relPath));
1035
1330
 
1036
1331
  if (!existsInVfs && !existsInMapVfs && !existsInWs && !existsInStaged) {
1037
1332
  return false;
1038
1333
  }
1039
1334
 
1040
- if (vfs) {
1041
- if (typeof vfs.rmSync === 'function') {
1042
- vfs.rmSync(absPath, { force: true });
1043
- } else if (typeof vfs.unlinkSync === 'function') {
1044
- if (typeof vfs.existsSync !== 'function' || vfs.existsSync(absPath)) {
1045
- vfs.unlinkSync(absPath);
1046
- }
1047
- } else if (vfs.files instanceof Map) {
1048
- vfs.files.delete(absPath);
1049
- }
1050
- }
1335
+ deleteVfsFileSafe(vfs, absPath, shell);
1051
1336
 
1052
1337
  if (workspaceFiles && typeof workspaceFiles === 'object') {
1053
1338
  delete workspaceFiles[relPath];
@@ -1055,18 +1340,1093 @@ export function discardChanges(
1055
1340
  if (gs) {
1056
1341
  unstageFile(gs, relPath);
1057
1342
  }
1058
- shell._emitVfsMutation?.('delete', absPath);
1059
1343
  return true;
1060
1344
  }
1061
1345
 
1346
+ // ── Myers O((M+N)D) Shortest-Edit-Script Line Diff & 3-Line Unified Hunks ───
1347
+
1348
+ export function computeMyersDiffOps(oldText: string, newText: string): DiffLineOp[] {
1349
+ const normalizeLines = (t: string): string[] => {
1350
+ if (!t) return [];
1351
+ const lines = t.replace(/\r\n/g, '\n').split('\n');
1352
+ if (lines.length > 0 && lines[lines.length - 1] === '' && t.endsWith('\n')) {
1353
+ lines.pop();
1354
+ }
1355
+ return lines;
1356
+ };
1357
+ const a = normalizeLines(oldText);
1358
+ const b = normalizeLines(newText);
1359
+ const n = a.length;
1360
+ const m = b.length;
1361
+ if (n === 0 && m === 0) return [];
1362
+
1363
+ const max = n + m;
1364
+ const offset = max;
1365
+ const v = new Int32Array(2 * max + 2);
1366
+ v.fill(-1);
1367
+ v[offset + 1] = 0;
1368
+ const trace: Int32Array[] = [];
1369
+
1370
+ let foundD = max;
1371
+ for (let d = 0; d <= max; d++) {
1372
+ trace.push(new Int32Array(v));
1373
+ for (let k = -d; k <= d; k += 2) {
1374
+ let x: number;
1375
+ if (k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1])) {
1376
+ x = v[offset + k + 1];
1377
+ } else {
1378
+ x = v[offset + k - 1] + 1;
1379
+ }
1380
+ let y = x - k;
1381
+ while (x < n && y < m && a[x] === b[y]) {
1382
+ x++;
1383
+ y++;
1384
+ }
1385
+ v[offset + k] = x;
1386
+ if (x >= n && y >= m) {
1387
+ foundD = d;
1388
+ d = max + 1;
1389
+ break;
1390
+ }
1391
+ }
1392
+ }
1393
+
1394
+ const ops: DiffLineOp[] = [];
1395
+ let x = n;
1396
+ let y = m;
1397
+ for (let d = foundD; d > 0; d--) {
1398
+ const prevV = trace[d];
1399
+ const k = x - y;
1400
+ let prevK: number;
1401
+ if (k === -d || (k !== d && prevV[offset + k - 1] < prevV[offset + k + 1])) {
1402
+ prevK = k + 1;
1403
+ } else {
1404
+ prevK = k - 1;
1405
+ }
1406
+ const prevX = prevV[offset + prevK];
1407
+ const prevY = prevX - prevK;
1408
+
1409
+ while (x > prevX && y > prevY) {
1410
+ x--;
1411
+ y--;
1412
+ ops.push({ type: 'common', line: a[x], oldLineNumber: x + 1, newLineNumber: y + 1 });
1413
+ }
1414
+ if (x === prevX) {
1415
+ y--;
1416
+ ops.push({ type: 'added', line: b[y], newLineNumber: y + 1 });
1417
+ } else {
1418
+ x--;
1419
+ ops.push({ type: 'removed', line: a[x], oldLineNumber: x + 1 });
1420
+ }
1421
+ }
1422
+ while (x > 0 && y > 0) {
1423
+ x--;
1424
+ y--;
1425
+ ops.push({ type: 'common', line: a[x], oldLineNumber: x + 1, newLineNumber: y + 1 });
1426
+ }
1427
+ ops.reverse();
1428
+ return ops;
1429
+ }
1430
+
1431
+ export function computeUnifiedHunkDiff(
1432
+ file1Name: string,
1433
+ file2Name: string,
1434
+ oldText: string,
1435
+ newText: string,
1436
+ contextLines = 3
1437
+ ): string {
1438
+ const ops = computeMyersDiffOps(oldText, newText);
1439
+ if (!ops.some((op) => op.type !== 'common')) return '';
1440
+
1441
+ const changeIndices: number[] = [];
1442
+ for (let i = 0; i < ops.length; i++) {
1443
+ if (ops[i].type !== 'common') changeIndices.push(i);
1444
+ }
1445
+
1446
+ const hunks: Array<{ start: number; end: number }> = [];
1447
+ for (const idx of changeIndices) {
1448
+ const hStart = Math.max(0, idx - contextLines);
1449
+ const hEnd = Math.min(ops.length - 1, idx + contextLines);
1450
+ const prev = hunks[hunks.length - 1];
1451
+ if (prev && hStart <= prev.end + 1) {
1452
+ prev.end = Math.max(prev.end, hEnd);
1453
+ } else {
1454
+ hunks.push({ start: hStart, end: hEnd });
1455
+ }
1456
+ }
1457
+
1458
+ let out = `--- ${file1Name}\n+++ ${file2Name}\n`;
1459
+ for (const hunk of hunks) {
1460
+ const slice = ops.slice(hunk.start, hunk.end + 1);
1461
+ let oldCount = 0;
1462
+ let newCount = 0;
1463
+ let oldStart = 0;
1464
+ let newStart = 0;
1465
+ for (const op of slice) {
1466
+ if (op.type !== 'added') {
1467
+ if (oldStart === 0 && op.oldLineNumber) oldStart = op.oldLineNumber;
1468
+ oldCount++;
1469
+ }
1470
+ if (op.type !== 'removed') {
1471
+ if (newStart === 0 && op.newLineNumber) newStart = op.newLineNumber;
1472
+ newCount++;
1473
+ }
1474
+ }
1475
+ if (oldStart === 0) {
1476
+ for (let j = hunk.start - 1; j >= 0; j--) {
1477
+ if (ops[j].oldLineNumber) {
1478
+ oldStart = (ops[j].oldLineNumber ?? 0) + (oldCount > 0 ? 1 : 0);
1479
+ break;
1480
+ }
1481
+ }
1482
+ }
1483
+ if (newStart === 0) {
1484
+ for (let j = hunk.start - 1; j >= 0; j--) {
1485
+ if (ops[j].newLineNumber) {
1486
+ newStart = (ops[j].newLineNumber ?? 0) + (newCount > 0 ? 1 : 0);
1487
+ break;
1488
+ }
1489
+ }
1490
+ }
1491
+ out += `@@ -${oldStart},${oldCount} +${newStart},${newCount} @@\n`;
1492
+ for (const op of slice) {
1493
+ if (op.type === 'common') out += ` ${op.line}\n`;
1494
+ else if (op.type === 'added') out += `+${op.line}\n`;
1495
+ else out += `-${op.line}\n`;
1496
+ }
1497
+ }
1498
+ return out;
1499
+ }
1500
+
1501
+ export function computeGitGutterChanges(
1502
+ headContent: string | undefined,
1503
+ liveContent: string
1504
+ ): GitGutterRange[] {
1505
+ if (headContent === undefined) {
1506
+ const lineCount = liveContent ? liveContent.split(/\r?\n/).length : 1;
1507
+ return [{ line: 1, endLine: Math.max(1, lineCount), kind: 'added' }];
1508
+ }
1509
+ if (headContent === liveContent) return [];
1510
+
1511
+ const ops = computeMyersDiffOps(headContent, liveContent);
1512
+ const ranges: GitGutterRange[] = [];
1513
+ let i = 0;
1514
+ let lastNewLine = 1;
1515
+
1516
+ while (i < ops.length) {
1517
+ const op = ops[i];
1518
+ if (op.type === 'common') {
1519
+ if (op.newLineNumber) lastNewLine = op.newLineNumber;
1520
+ i++;
1521
+ continue;
1522
+ }
1523
+ let removedCount = 0;
1524
+ const addedLines: number[] = [];
1525
+ while (i < ops.length && ops[i].type !== 'common') {
1526
+ if (ops[i].type === 'removed') removedCount++;
1527
+ else if (ops[i].type === 'added' && ops[i].newLineNumber) {
1528
+ addedLines.push(ops[i].newLineNumber as number);
1529
+ }
1530
+ i++;
1531
+ }
1532
+ if (addedLines.length > 0 && removedCount > 0) {
1533
+ ranges.push({
1534
+ line: addedLines[0],
1535
+ endLine: addedLines[addedLines.length - 1],
1536
+ kind: 'modified'
1537
+ });
1538
+ lastNewLine = addedLines[addedLines.length - 1];
1539
+ } else if (addedLines.length > 0) {
1540
+ ranges.push({
1541
+ line: addedLines[0],
1542
+ endLine: addedLines[addedLines.length - 1],
1543
+ kind: 'added'
1544
+ });
1545
+ lastNewLine = addedLines[addedLines.length - 1];
1546
+ } else if (removedCount > 0) {
1547
+ const anchor = Math.max(1, lastNewLine);
1548
+ ranges.push({ line: anchor, endLine: anchor, kind: 'deleted' });
1549
+ }
1550
+ }
1551
+ return ranges;
1552
+ }
1553
+
1554
+ // ── Branch Checkout, Stash, Reset, Merge, Tag, Show & Blame ─────────────────
1555
+
1556
+ export interface CheckoutBranchOptions {
1557
+ create?: boolean;
1558
+ force?: boolean;
1559
+ workspaceFiles?: Record<string, string>;
1560
+ }
1561
+
1562
+ export function checkoutBranch(
1563
+ target: GitShellLike | GitState,
1564
+ branchName: string,
1565
+ options?: CheckoutBranchOptions
1566
+ ): { ok: boolean; created: boolean; error?: string } {
1567
+ const trimmed = typeof branchName === 'string' ? branchName.trim() : '';
1568
+ if (!trimmed) {
1569
+ return { ok: false, created: false, error: 'branch name required' };
1570
+ }
1571
+ const shell: GitShellLike | null = isGitShellLike(target) ? target : null;
1572
+ const gs: GitState | null = isGitShellLike(target) ? (target.gitState ?? null) : target;
1573
+ if (!gs) {
1574
+ return { ok: false, created: false, error: 'not a git repository' };
1575
+ }
1576
+
1577
+ const repoRoot = (gs.repoRoot || shell?.cwd || '/workspace').replace(/\/+$/, '') || '/';
1578
+ const vfs = shell?.vfs ?? null;
1579
+ const prevBranch = gs.branch || 'main';
1580
+ saveBranchTip(gs, prevBranch);
1581
+
1582
+ const hasBranch =
1583
+ gs.branches instanceof Set
1584
+ ? gs.branches.has(trimmed)
1585
+ : Array.isArray(gs.branches)
1586
+ ? gs.branches.includes(trimmed)
1587
+ : prevBranch === trimmed;
1588
+
1589
+ if (options?.create) {
1590
+ ensureBranchList(gs, trimmed);
1591
+ gs.branch = trimmed;
1592
+ saveBranchTip(gs, trimmed);
1593
+ if (vfs) {
1594
+ const headPath = `${repoRoot === '/' ? '' : repoRoot}/.git/HEAD`;
1595
+ writeVfsFileSafe(vfs, headPath, `ref: refs/heads/${trimmed}\n`, shell ?? undefined);
1596
+ void syncToIsoGitRepo(vfs, gs);
1597
+ }
1598
+ return { ok: true, created: true };
1599
+ }
1600
+
1601
+ if (!hasBranch && !(gs.branchHeads && gs.branchHeads[trimmed])) {
1602
+ return { ok: false, created: false, error: `pathspec '${trimmed}' did not match any file(s) known to git` };
1603
+ }
1604
+
1605
+ const prevHead = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1606
+ const tip = gs.branchHeads?.[trimmed];
1607
+ const nextHead = tip ? cleanFileMap(tip.headFiles, repoRoot) : { ...prevHead };
1608
+ const stagedMap = ensureStagedMap(gs);
1609
+
1610
+ // Sync clean tracked files in working tree to target branch's headFiles
1611
+ if (vfs || options?.workspaceFiles) {
1612
+ const liveFiles = vfs ? readVfsTree(vfs, repoRoot) : { ...(options?.workspaceFiles || {}) };
1613
+ const allTracked = new Set([...Object.keys(prevHead), ...Object.keys(nextHead)]);
1614
+ for (const rel of allTracked) {
1615
+ const inPrev = Object.prototype.hasOwnProperty.call(prevHead, rel);
1616
+ const inNext = Object.prototype.hasOwnProperty.call(nextHead, rel);
1617
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, rel);
1618
+ const isDirtyWorktree =
1619
+ stagedMap.has(rel) ||
1620
+ (inPrev && (!inLive || liveFiles[rel] !== prevHead[rel])) ||
1621
+ (!inPrev && inLive && (!inNext || liveFiles[rel] !== nextHead[rel]));
1622
+
1623
+ if (isDirtyWorktree && !options?.force) {
1624
+ // Carry over dirty/staged edits when switching branches (matches D5.7 fuzzer & safe checkout)
1625
+ continue;
1626
+ }
1627
+
1628
+ const absPath = repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`;
1629
+ if (inNext) {
1630
+ if (!inLive || liveFiles[rel] !== nextHead[rel]) {
1631
+ writeVfsFileSafe(vfs, absPath, nextHead[rel], shell ?? undefined);
1632
+ }
1633
+ if (options?.workspaceFiles) {
1634
+ options.workspaceFiles[rel] = nextHead[rel];
1635
+ }
1636
+ } else if (inPrev) {
1637
+ deleteVfsFileSafe(vfs, absPath, shell ?? undefined);
1638
+ if (options?.workspaceFiles) {
1639
+ delete options.workspaceFiles[rel];
1640
+ }
1641
+ }
1642
+ }
1643
+ }
1644
+
1645
+ gs.branch = trimmed;
1646
+ ensureBranchList(gs, trimmed);
1647
+ if (tip) {
1648
+ gs.commits = tip.commits.map((c) => ({
1649
+ ...c,
1650
+ ...(c.files ? { files: { ...c.files } } : {})
1651
+ }));
1652
+ gs.headCommit = tip.headCommit;
1653
+ syncGitHead(gs, nextHead);
1654
+ }
1655
+ pruneStagedMapInPlace(gs, stagedMap, nextHead);
1656
+
1657
+ if (vfs) {
1658
+ const headPath = `${repoRoot === '/' ? '' : repoRoot}/.git/HEAD`;
1659
+ writeVfsFileSafe(vfs, headPath, `ref: refs/heads/${trimmed}\n`, shell ?? undefined);
1660
+ void syncToIsoGitRepo(vfs, gs);
1661
+ }
1662
+ return { ok: true, created: false };
1663
+ }
1664
+
1665
+ export function resolveCommitRef(
1666
+ gitState: GitState,
1667
+ refSpec?: string
1668
+ ): { commit: GitCommitRecord | null; index: number } {
1669
+ const commits = Array.isArray(gitState.commits) ? gitState.commits : [];
1670
+ if (commits.length === 0) return { commit: null, index: -1 };
1671
+ const raw = (refSpec || 'HEAD').trim();
1672
+ if (!raw || raw === 'HEAD') {
1673
+ return { commit: commits[0], index: 0 };
1674
+ }
1675
+
1676
+ const tildeMatch = /^HEAD~(\d+)$/.exec(raw);
1677
+ if (tildeMatch) {
1678
+ const steps = Number.parseInt(tildeMatch[1], 10);
1679
+ const idx = steps;
1680
+ return idx >= 0 && idx < commits.length
1681
+ ? { commit: commits[idx], index: idx }
1682
+ : { commit: null, index: -1 };
1683
+ }
1684
+
1685
+ const caretMatch = /^HEAD(\^+)$/.exec(raw);
1686
+ if (caretMatch) {
1687
+ const idx = caretMatch[1].length;
1688
+ return idx >= 0 && idx < commits.length
1689
+ ? { commit: commits[idx], index: idx }
1690
+ : { commit: null, index: -1 };
1691
+ }
1692
+
1693
+ if (gitState.tags && gitState.tags[raw]) {
1694
+ const tagTarget = gitState.tags[raw];
1695
+ const tagIdx = commits.findIndex((c) => c.hash === tagTarget || c.hash.startsWith(tagTarget));
1696
+ if (tagIdx !== -1) return { commit: commits[tagIdx], index: tagIdx };
1697
+ }
1698
+
1699
+ if (gitState.branchHeads && gitState.branchHeads[raw]) {
1700
+ const tip = gitState.branchHeads[raw];
1701
+ if (tip.commits.length > 0) return { commit: tip.commits[0], index: 0 };
1702
+ }
1703
+
1704
+ const shaIdx = commits.findIndex((c) => c.hash === raw || c.hash.startsWith(raw));
1705
+ if (shaIdx !== -1) return { commit: commits[shaIdx], index: shaIdx };
1706
+
1707
+ return { commit: null, index: -1 };
1708
+ }
1709
+
1710
+ export function resetToRef(
1711
+ shell: GitShellLike,
1712
+ refSpec = 'HEAD',
1713
+ mode: 'soft' | 'mixed' | 'hard' = 'mixed',
1714
+ workspaceFiles?: Record<string, string>
1715
+ ): { ok: boolean; headCommit: string; message?: string; error?: string } {
1716
+ const gs = shell.gitState ?? null;
1717
+ if (!gs) return { ok: false, headCommit: '', error: 'not a git repository' };
1718
+ const repoRoot = (gs.repoRoot || shell.cwd || '/workspace').replace(/\/+$/, '') || '/';
1719
+ const vfs = shell.vfs ?? null;
1720
+
1721
+ const { commit, index } = resolveCommitRef(gs, refSpec);
1722
+ if (!commit && gs.commits.length > 0) {
1723
+ return {
1724
+ ok: false,
1725
+ headCommit: gs.headCommit,
1726
+ error: `fatal: ambiguous argument '${refSpec}': unknown revision or path not in the working tree.`
1727
+ };
1728
+ }
1729
+
1730
+ const prevHead = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1731
+ const targetHead = commit?.files ? cleanFileMap(commit.files, repoRoot) : prevHead;
1732
+ const stagedMap = ensureStagedMap(gs);
1733
+
1734
+ if (commit && index > 0) {
1735
+ gs.commits = gs.commits.slice(index);
1736
+ gs.headCommit = commit.hash;
1737
+ syncGitHead(gs, targetHead);
1738
+ } else if (commit) {
1739
+ gs.headCommit = commit.hash;
1740
+ syncGitHead(gs, targetHead);
1741
+ }
1742
+
1743
+ if (mode === 'soft') {
1744
+ // Stage differences from new targetHead to previous HEAD + existing staged changes
1745
+ const prevEffective: Record<string, string> = { ...prevHead };
1746
+ for (const [k, v] of stagedMap.entries()) {
1747
+ if (v === null) delete prevEffective[k];
1748
+ else prevEffective[k] = v;
1749
+ }
1750
+ stagedMap.clear();
1751
+ for (const [k, v] of Object.entries(prevEffective)) {
1752
+ applyStagedEntry(gs, stagedMap, k, v, targetHead);
1753
+ }
1754
+ for (const k of Object.keys(targetHead)) {
1755
+ if (!Object.prototype.hasOwnProperty.call(prevEffective, k)) {
1756
+ applyStagedEntry(gs, stagedMap, k, null, targetHead);
1757
+ }
1758
+ }
1759
+ } else if (mode === 'mixed') {
1760
+ stagedMap.clear();
1761
+ } else if (mode === 'hard') {
1762
+ stagedMap.clear();
1763
+ if (vfs) {
1764
+ const liveFiles = readVfsTree(vfs, repoRoot);
1765
+ for (const rel of Object.keys(liveFiles)) {
1766
+ if (!Object.prototype.hasOwnProperty.call(targetHead, rel)) {
1767
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
1768
+ if (workspaceFiles) delete workspaceFiles[rel];
1769
+ }
1770
+ }
1771
+ for (const [rel, text] of Object.entries(targetHead)) {
1772
+ writeVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, text, shell);
1773
+ if (workspaceFiles) workspaceFiles[rel] = text;
1774
+ }
1775
+ }
1776
+ }
1777
+
1778
+ saveBranchTip(gs, gs.branch);
1779
+ if (vfs) void syncToIsoGitRepo(vfs, gs);
1780
+ return {
1781
+ ok: true,
1782
+ headCommit: gs.headCommit,
1783
+ message: commit ? `HEAD is now at ${commit.hash} ${commit.message}` : undefined
1784
+ };
1785
+ }
1786
+
1787
+ export function stashPush(
1788
+ shell: GitShellLike,
1789
+ message?: string,
1790
+ includeUntracked = false,
1791
+ workspaceFiles?: Record<string, string>
1792
+ ): { ok: boolean; created: boolean; label: string } {
1793
+ const gs = shell.gitState ?? null;
1794
+ if (!gs) return { ok: false, created: false, label: 'not a git repository' };
1795
+ const repoRoot = (gs.repoRoot || shell.cwd || '/workspace').replace(/\/+$/, '') || '/';
1796
+ const vfs = shell.vfs ?? null;
1797
+ const liveFiles = vfs ? readVfsTree(vfs, repoRoot) : { ...(workspaceFiles || {}) };
1798
+ const status = computeGitStatus(liveFiles, repoRoot, gs);
1799
+
1800
+ const hasSaveable =
1801
+ status.staged.length > 0 ||
1802
+ status.modified.length > 0 ||
1803
+ status.deleted.length > 0 ||
1804
+ (includeUntracked && status.untracked.length > 0);
1805
+ if (!hasSaveable) {
1806
+ return { ok: true, created: false, label: 'No local changes to save' };
1807
+ }
1808
+
1809
+ if (!Array.isArray(gs.stashes)) gs.stashes = [];
1810
+ const headFiles = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1811
+ const stagedMap = ensureStagedMap(gs);
1812
+ const untrackedSnap: Record<string, string> = {};
1813
+ if (includeUntracked) {
1814
+ for (const u of status.untracked) {
1815
+ if (Object.prototype.hasOwnProperty.call(liveFiles, u.path)) {
1816
+ untrackedSnap[u.path] = liveFiles[u.path];
1817
+ }
1818
+ }
1819
+ }
1820
+ const trackedWorktree: Record<string, string> = {};
1821
+ for (const [k, v] of Object.entries(liveFiles)) {
1822
+ if (Object.prototype.hasOwnProperty.call(headFiles, k) || stagedMap.has(k)) {
1823
+ trackedWorktree[k] = v;
1824
+ }
1825
+ }
1826
+
1827
+ const summary =
1828
+ message?.trim() ||
1829
+ `WIP on ${gs.branch || 'main'}: ${gs.headCommit || 'unborn'} ${gs.commits[0]?.message || 'initial'}`;
1830
+ gs.stashes.unshift({
1831
+ id: Date.now(),
1832
+ branch: gs.branch || 'main',
1833
+ headCommit: gs.headCommit || '',
1834
+ message: summary,
1835
+ timestamp: Date.now(),
1836
+ worktreeFiles: trackedWorktree,
1837
+ stagedEntries: Array.from(stagedMap.entries()),
1838
+ untrackedFiles: untrackedSnap
1839
+ });
1840
+
1841
+ // Reset tracked files (and untracked if -u) back to HEAD
1842
+ stagedMap.clear();
1843
+ for (const rel of Object.keys(untrackedSnap)) {
1844
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
1845
+ if (workspaceFiles) delete workspaceFiles[rel];
1846
+ }
1847
+ for (const rel of Object.keys(trackedWorktree)) {
1848
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
1849
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
1850
+ if (workspaceFiles) delete workspaceFiles[rel];
1851
+ }
1852
+ }
1853
+ for (const [rel, text] of Object.entries(headFiles)) {
1854
+ writeVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, text, shell);
1855
+ if (workspaceFiles) workspaceFiles[rel] = text;
1856
+ }
1857
+
1858
+ return { ok: true, created: true, label: `Saved working directory and index state ${summary}` };
1859
+ }
1860
+
1861
+ export function stashApply(
1862
+ shell: GitShellLike,
1863
+ stashIndex = 0,
1864
+ dropAfter = false,
1865
+ workspaceFiles?: Record<string, string>
1866
+ ): { ok: boolean; error?: string; message?: string } {
1867
+ const gs = shell.gitState ?? null;
1868
+ if (!gs || !Array.isArray(gs.stashes) || gs.stashes.length === 0) {
1869
+ return { ok: false, error: 'No stash entries found.' };
1870
+ }
1871
+ if (stashIndex < 0 || stashIndex >= gs.stashes.length) {
1872
+ return { ok: false, error: `error: stash@{${stashIndex}} is not a valid reference` };
1873
+ }
1874
+ const entry = gs.stashes[stashIndex];
1875
+ const repoRoot = (gs.repoRoot || shell.cwd || '/workspace').replace(/\/+$/, '') || '/';
1876
+ const vfs = shell.vfs ?? null;
1877
+ const headFiles = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1878
+ const stagedMap = ensureStagedMap(gs);
1879
+
1880
+ for (const rel of Object.keys(headFiles)) {
1881
+ if (!Object.prototype.hasOwnProperty.call(entry.worktreeFiles, rel)) {
1882
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
1883
+ if (workspaceFiles) delete workspaceFiles[rel];
1884
+ }
1885
+ }
1886
+ for (const [rel, text] of Object.entries({ ...entry.worktreeFiles, ...entry.untrackedFiles })) {
1887
+ writeVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, text, shell);
1888
+ if (workspaceFiles) workspaceFiles[rel] = text;
1889
+ }
1890
+ for (const [rel, val] of entry.stagedEntries) {
1891
+ applyStagedEntry(gs, stagedMap, rel, val, headFiles);
1892
+ }
1893
+ if (dropAfter) {
1894
+ gs.stashes.splice(stashIndex, 1);
1895
+ }
1896
+ return {
1897
+ ok: true,
1898
+ message: dropAfter
1899
+ ? `Dropped refs/stash@{${stashIndex}} (${entry.message})`
1900
+ : `Applied stash@{${stashIndex}}`
1901
+ };
1902
+ }
1903
+
1904
+ export function mergeBranch(
1905
+ shell: GitShellLike,
1906
+ sourceBranch: string,
1907
+ workspaceFiles?: Record<string, string>
1908
+ ): { ok: boolean; fastForward: boolean; conflicts: string[]; commitHash?: string; message: string } {
1909
+ const gs = shell.gitState ?? null;
1910
+ if (!gs) return { ok: false, fastForward: false, conflicts: [], message: 'fatal: not a git repository' };
1911
+ const srcName = sourceBranch.trim();
1912
+ const repoRoot = (gs.repoRoot || shell.cwd || '/workspace').replace(/\/+$/, '') || '/';
1913
+ const vfs = shell.vfs ?? null;
1914
+ saveBranchTip(gs, gs.branch);
1915
+
1916
+ const srcTip = gs.branchHeads?.[srcName];
1917
+ if (!srcTip) {
1918
+ return {
1919
+ ok: false,
1920
+ fastForward: false,
1921
+ conflicts: [],
1922
+ message: `merge: ${srcName} - not something we can merge`
1923
+ };
1924
+ }
1925
+ if (srcTip.headCommit === gs.headCommit) {
1926
+ return { ok: true, fastForward: true, conflicts: [], message: 'Already up to date.' };
1927
+ }
1928
+
1929
+ const ourHashes = new Set(gs.commits.map((c) => c.hash));
1930
+ if (ourHashes.has(srcTip.headCommit)) {
1931
+ return { ok: true, fastForward: true, conflicts: [], message: 'Already up to date.' };
1932
+ }
1933
+
1934
+ // Fast-forward if sourceBranch contains our HEAD
1935
+ const srcHasOurs = !gs.headCommit || srcTip.commits.some((c) => c.hash === gs.headCommit);
1936
+ if (srcHasOurs) {
1937
+ const nextHead = cleanFileMap(srcTip.headFiles, repoRoot);
1938
+ const prevHead = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1939
+ for (const rel of Object.keys(prevHead)) {
1940
+ if (!Object.prototype.hasOwnProperty.call(nextHead, rel)) {
1941
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
1942
+ if (workspaceFiles) delete workspaceFiles[rel];
1943
+ }
1944
+ }
1945
+ for (const [rel, text] of Object.entries(nextHead)) {
1946
+ writeVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, text, shell);
1947
+ if (workspaceFiles) workspaceFiles[rel] = text;
1948
+ }
1949
+ gs.commits = srcTip.commits.map((c) => ({ ...c, ...(c.files ? { files: { ...c.files } } : {}) }));
1950
+ gs.headCommit = srcTip.headCommit;
1951
+ syncGitHead(gs, nextHead);
1952
+ saveBranchTip(gs, gs.branch);
1953
+ if (vfs) void syncToIsoGitRepo(vfs, gs);
1954
+ return {
1955
+ ok: true,
1956
+ fastForward: true,
1957
+ conflicts: [],
1958
+ commitHash: gs.headCommit,
1959
+ message: `Updating ${prevHead ? '' : ''}${srcTip.headCommit}\nFast-forward`
1960
+ };
1961
+ }
1962
+
1963
+ // 3-way merge using common ancestor
1964
+ const baseCommit = srcTip.commits.find((c) => ourHashes.has(c.hash));
1965
+ const baseFiles = baseCommit?.files ? cleanFileMap(baseCommit.files, repoRoot) : {};
1966
+ const ourFiles = cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot);
1967
+ const theirFiles = cleanFileMap(srcTip.headFiles, repoRoot);
1968
+
1969
+ const allPaths = new Set([
1970
+ ...Object.keys(baseFiles),
1971
+ ...Object.keys(ourFiles),
1972
+ ...Object.keys(theirFiles)
1973
+ ]);
1974
+ const mergedFiles: Record<string, string> = {};
1975
+ const conflicts: string[] = [];
1976
+
1977
+ for (const rel of allPaths) {
1978
+ const b = baseFiles[rel];
1979
+ const o = ourFiles[rel];
1980
+ const t = theirFiles[rel];
1981
+ if (o === t) {
1982
+ if (o !== undefined) mergedFiles[rel] = o;
1983
+ } else if (o === b) {
1984
+ if (t !== undefined) mergedFiles[rel] = t;
1985
+ } else if (t === b) {
1986
+ if (o !== undefined) mergedFiles[rel] = o;
1987
+ } else {
1988
+ conflicts.push(rel);
1989
+ mergedFiles[rel] =
1990
+ `<<<<<<< HEAD\n${o ?? ''}` +
1991
+ (o && !o.endsWith('\n') ? '\n' : '') +
1992
+ `=======\n${t ?? ''}` +
1993
+ (t && !t.endsWith('\n') ? '\n' : '') +
1994
+ `>>>>>>> ${srcName}\n`;
1995
+ }
1996
+ }
1997
+
1998
+ for (const rel of Object.keys(ourFiles)) {
1999
+ if (!Object.prototype.hasOwnProperty.call(mergedFiles, rel)) {
2000
+ deleteVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, shell);
2001
+ if (workspaceFiles) delete workspaceFiles[rel];
2002
+ }
2003
+ }
2004
+ for (const [rel, text] of Object.entries(mergedFiles)) {
2005
+ writeVfsFileSafe(vfs, repoRoot === '/' ? `/${rel}` : `${repoRoot}/${rel}`, text, shell);
2006
+ if (workspaceFiles) workspaceFiles[rel] = text;
2007
+ }
2008
+
2009
+ if (conflicts.length > 0) {
2010
+ return {
2011
+ ok: false,
2012
+ fastForward: false,
2013
+ conflicts,
2014
+ message:
2015
+ conflicts.map((c) => `CONFLICT (content): Merge conflict in ${c}`).join('\n') +
2016
+ '\nAutomatic merge failed; fix conflicts and then commit the result.'
2017
+ };
2018
+ }
2019
+
2020
+ const ts = Date.now();
2021
+ const mergeMsg = `Merge branch '${srcName}' into ${gs.branch}`;
2022
+ const hash = computeShortCommitHash(`${gs.headCommit}:${srcTip.headCommit}:${ts}`);
2023
+ const synced = syncGitHead(gs, mergedFiles);
2024
+ gs.commits.unshift({
2025
+ hash,
2026
+ message: mergeMsg,
2027
+ timestamp: ts,
2028
+ author: 'CodeLab Developer <dev@codelab.internal>',
2029
+ date: new Date(ts).toUTCString(),
2030
+ files: { ...synced },
2031
+ parents: [gs.headCommit, srcTip.headCommit].filter(Boolean)
2032
+ });
2033
+ gs.headCommit = hash;
2034
+ ensureStagedMap(gs).clear();
2035
+ saveBranchTip(gs, gs.branch);
2036
+ if (vfs) void syncToIsoGitRepo(vfs, gs);
2037
+
2038
+ return {
2039
+ ok: true,
2040
+ fastForward: false,
2041
+ conflicts: [],
2042
+ commitHash: hash,
2043
+ message: `Merge made by the 'ort' strategy.`
2044
+ };
2045
+ }
2046
+
2047
+ export function showCommit(gitState: GitState, refSpec = 'HEAD'): { ok: boolean; output: string } {
2048
+ const { commit, index } = resolveCommitRef(gitState, refSpec);
2049
+ if (!commit) {
2050
+ return { ok: false, output: `fatal: bad object ${refSpec}\n` };
2051
+ }
2052
+ const parent = gitState.commits[index + 1];
2053
+ const parentFiles = parent?.files || {};
2054
+ const currFiles = commit.files || {};
2055
+ const allPaths = Array.from(
2056
+ new Set([...Object.keys(parentFiles), ...Object.keys(currFiles)])
2057
+ ).sort();
2058
+
2059
+ const authorStr = commit.author || 'CodeLab Developer <dev@codelab.internal>';
2060
+ const dateStr = commit.date || new Date(commit.timestamp || 0).toUTCString();
2061
+ let out = `commit ${commit.hash}\nAuthor: ${authorStr}\nDate: ${dateStr}\n\n ${commit.message}\n\n`;
2062
+ for (const rel of allPaths) {
2063
+ const oldText = parentFiles[rel] ?? '';
2064
+ const newText = currFiles[rel] ?? '';
2065
+ if (oldText !== newText) {
2066
+ const hunk = computeUnifiedHunkDiff(`a/${rel}`, `b/${rel}`, oldText, newText);
2067
+ if (hunk) out += `diff --git a/${rel} b/${rel}\n${hunk}`;
2068
+ }
2069
+ }
2070
+ return { ok: true, output: out };
2071
+ }
2072
+
2073
+ export function blameFile(
2074
+ gitState: GitState,
2075
+ relPath: string,
2076
+ liveContent?: string
2077
+ ): { ok: boolean; entries: BlameLineEntry[]; output: string } {
2078
+ const repoRoot = gitState.repoRoot || '/workspace';
2079
+ const cleanRel = normalizeScmRelPath(relPath, repoRoot);
2080
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
2081
+ const targetText =
2082
+ liveContent !== undefined
2083
+ ? liveContent
2084
+ : Object.prototype.hasOwnProperty.call(headFiles, cleanRel)
2085
+ ? headFiles[cleanRel]
2086
+ : null;
2087
+ if (targetText === null) {
2088
+ return { ok: false, entries: [], output: `fatal: no such path '${relPath}' in HEAD\n` };
2089
+ }
2090
+
2091
+ const lines = targetText.replace(/\r\n/g, '\n').split('\n');
2092
+ if (lines.length > 0 && lines[lines.length - 1] === '' && targetText.endsWith('\n')) {
2093
+ lines.pop();
2094
+ }
2095
+
2096
+ // Attribute lines from oldest commit to newest
2097
+ const chronological = [...(gitState.commits || [])].reverse();
2098
+ const lineMeta: Array<{ hash: string; author: string; timestamp: number }> = lines.map(() => ({
2099
+ hash: '0000000',
2100
+ author: 'Not Committed Yet',
2101
+ timestamp: Date.now()
2102
+ }));
2103
+
2104
+ let prevSnapLines: string[] = [];
2105
+ let prevMeta: Array<{ hash: string; author: string; timestamp: number }> = [];
2106
+
2107
+ for (const c of chronological) {
2108
+ const snapText = c.files?.[cleanRel];
2109
+ if (snapText === undefined) {
2110
+ prevSnapLines = [];
2111
+ prevMeta = [];
2112
+ continue;
2113
+ }
2114
+ const currLines = snapText.replace(/\r\n/g, '\n').split('\n');
2115
+ if (currLines.length > 0 && currLines[currLines.length - 1] === '' && snapText.endsWith('\n')) {
2116
+ currLines.pop();
2117
+ }
2118
+ const ops = computeMyersDiffOps(prevSnapLines.join('\n'), currLines.join('\n'));
2119
+ const nextMeta: Array<{ hash: string; author: string; timestamp: number }> = new Array(
2120
+ currLines.length
2121
+ );
2122
+ const authorName = (c.author || 'CodeLab Developer').replace(/\s*<.*$/, '');
2123
+ for (const op of ops) {
2124
+ if (op.type === 'common' && op.oldLineNumber && op.newLineNumber) {
2125
+ nextMeta[op.newLineNumber - 1] = prevMeta[op.oldLineNumber - 1] || {
2126
+ hash: c.hash,
2127
+ author: authorName,
2128
+ timestamp: c.timestamp
2129
+ };
2130
+ } else if (op.type === 'added' && op.newLineNumber) {
2131
+ nextMeta[op.newLineNumber - 1] = {
2132
+ hash: c.hash,
2133
+ author: authorName,
2134
+ timestamp: c.timestamp
2135
+ };
2136
+ }
2137
+ }
2138
+ prevSnapLines = currLines;
2139
+ prevMeta = nextMeta;
2140
+ }
2141
+
2142
+ if (prevSnapLines.length > 0) {
2143
+ const finalOps = computeMyersDiffOps(prevSnapLines.join('\n'), lines.join('\n'));
2144
+ for (const op of finalOps) {
2145
+ if (op.type === 'common' && op.oldLineNumber && op.newLineNumber) {
2146
+ const inherited = prevMeta[op.oldLineNumber - 1];
2147
+ if (inherited) lineMeta[op.newLineNumber - 1] = inherited;
2148
+ }
2149
+ }
2150
+ }
2151
+
2152
+ const entries: BlameLineEntry[] = lines.map((content, idx) => ({
2153
+ lineNumber: idx + 1,
2154
+ hash: lineMeta[idx].hash,
2155
+ author: lineMeta[idx].author,
2156
+ timestamp: lineMeta[idx].timestamp,
2157
+ content
2158
+ }));
2159
+
2160
+ const output = entries
2161
+ .map((e) => {
2162
+ const dateIso = new Date(e.timestamp).toISOString().slice(0, 10);
2163
+ return `${e.hash.slice(0, 7)} (${e.author.padEnd(18).slice(0, 18)} ${dateIso} ${String(e.lineNumber).padStart(3)}) ${e.content}`;
2164
+ })
2165
+ .join('\n') + (entries.length > 0 ? '\n' : '');
2166
+
2167
+ return { ok: true, entries, output };
2168
+ }
2169
+
2170
+ // ── Real `isomorphic-git` VFS Adapter & `.git/` Object-Store Synchronization ─
2171
+
2172
+ export function createIsoGitFsAdapter(vfs: GitVfsLike): {
2173
+ promises: {
2174
+ readFile: (p: string, opts?: { encoding?: string } | string) => Promise<Uint8Array | string>;
2175
+ writeFile: (p: string, data: Uint8Array | string) => Promise<void>;
2176
+ unlink: (p: string) => Promise<void>;
2177
+ readdir: (p: string) => Promise<string[]>;
2178
+ mkdir: (p: string) => Promise<void>;
2179
+ rmdir: (p: string) => Promise<void>;
2180
+ stat: (p: string) => Promise<{
2181
+ type: 'file' | 'dir';
2182
+ mode: number;
2183
+ size: number;
2184
+ ino: number;
2185
+ mtimeMs: number;
2186
+ ctimeMs: number;
2187
+ uid: number;
2188
+ gid: number;
2189
+ dev: number;
2190
+ isFile: () => boolean;
2191
+ isDirectory: () => boolean;
2192
+ isSymbolicLink: () => boolean;
2193
+ }>;
2194
+ lstat: (p: string) => Promise<{
2195
+ type: 'file' | 'dir';
2196
+ mode: number;
2197
+ size: number;
2198
+ ino: number;
2199
+ mtimeMs: number;
2200
+ ctimeMs: number;
2201
+ uid: number;
2202
+ gid: number;
2203
+ dev: number;
2204
+ isFile: () => boolean;
2205
+ isDirectory: () => boolean;
2206
+ isSymbolicLink: () => boolean;
2207
+ }>;
2208
+ readlink: (p: string) => Promise<string>;
2209
+ symlink: (target: string, p: string) => Promise<void>;
2210
+ };
2211
+ } {
2212
+ const makeErrno = (code: string, message: string): Error & { code: string } => {
2213
+ const err = new Error(message) as Error & { code: string };
2214
+ err.code = code;
2215
+ return err;
2216
+ };
2217
+
2218
+ const statImpl = async (p: string) => {
2219
+ if (!vfs.statSync) throw makeErrno('ENOENT', `ENOENT: ${p}`);
2220
+ try {
2221
+ const st = vfs.statSync(p);
2222
+ const isDir = st.isDirectory();
2223
+ const mtime = st.mtimeMs ?? Date.now();
2224
+ return {
2225
+ type: (isDir ? 'dir' : 'file') as 'dir' | 'file',
2226
+ mode: st.mode ?? (isDir ? 0o040755 : 0o100644),
2227
+ size: st.size ?? 0,
2228
+ ino: 1,
2229
+ mtimeMs: mtime,
2230
+ ctimeMs: mtime,
2231
+ uid: 1000,
2232
+ gid: 1000,
2233
+ dev: 1,
2234
+ isFile: () => !isDir,
2235
+ isDirectory: () => isDir,
2236
+ isSymbolicLink: () => Boolean(st.isSymbolicLink?.())
2237
+ };
2238
+ } catch (err) {
2239
+ const msg = err instanceof Error ? err.message : String(err);
2240
+ throw makeErrno('ENOENT', msg);
2241
+ }
2242
+ };
2243
+
2244
+ return {
2245
+ promises: {
2246
+ readFile: async (p: string, opts?: { encoding?: string } | string) => {
2247
+ if (!vfs.readFileSync) throw makeErrno('ENOENT', `ENOENT: ${p}`);
2248
+ const enc = typeof opts === 'string' ? opts : opts?.encoding;
2249
+ try {
2250
+ const raw = vfs.readFileSync(p, enc);
2251
+ if (enc === 'utf8' || enc === 'utf-8') {
2252
+ return typeof raw === 'string' ? raw : new TextDecoder().decode(raw);
2253
+ }
2254
+ return raw instanceof Uint8Array ? raw : new TextEncoder().encode(String(raw));
2255
+ } catch (err) {
2256
+ const msg = err instanceof Error ? err.message : String(err);
2257
+ throw makeErrno('ENOENT', msg);
2258
+ }
2259
+ },
2260
+ writeFile: async (p: string, data: Uint8Array | string) => {
2261
+ const slash = p.lastIndexOf('/');
2262
+ const dir = slash > 0 ? p.slice(0, slash) : '/';
2263
+ if (dir && vfs.mkdirSync && (!vfs.existsSync || !vfs.existsSync(dir))) {
2264
+ vfs.mkdirSync(dir, { recursive: true });
2265
+ }
2266
+ vfs.writeFileSync?.(p, data);
2267
+ },
2268
+ unlink: async (p: string) => {
2269
+ if (vfs.unlinkSync) {
2270
+ try {
2271
+ vfs.unlinkSync(p);
2272
+ } catch (err) {
2273
+ const msg = err instanceof Error ? err.message : String(err);
2274
+ throw makeErrno('ENOENT', msg);
2275
+ }
2276
+ } else if (vfs.rmSync) {
2277
+ vfs.rmSync(p, { force: true });
2278
+ }
2279
+ },
2280
+ readdir: async (p: string) => {
2281
+ if (!vfs.readdirSync) throw makeErrno('ENOENT', `ENOENT: ${p}`);
2282
+ try {
2283
+ return vfs.readdirSync(p);
2284
+ } catch (err) {
2285
+ const msg = err instanceof Error ? err.message : String(err);
2286
+ throw makeErrno('ENOENT', msg);
2287
+ }
2288
+ },
2289
+ mkdir: async (p: string) => {
2290
+ try {
2291
+ vfs.mkdirSync?.(p, { recursive: true });
2292
+ } catch (err) {
2293
+ const _ignored = err;
2294
+ void _ignored;
2295
+ }
2296
+ },
2297
+ rmdir: async (p: string) => {
2298
+ try {
2299
+ if (vfs.rmdirSync) vfs.rmdirSync(p);
2300
+ else vfs.rmSync?.(p, { recursive: false, force: true });
2301
+ } catch (err) {
2302
+ const msg = err instanceof Error ? err.message : String(err);
2303
+ throw makeErrno('ENOENT', msg);
2304
+ }
2305
+ },
2306
+ stat: statImpl,
2307
+ lstat: statImpl,
2308
+ readlink: async (p: string) => {
2309
+ if (vfs.readlinkSync) return vfs.readlinkSync(p);
2310
+ throw makeErrno('ENOENT', `ENOENT: ${p}`);
2311
+ },
2312
+ symlink: async (target: string, p: string) => {
2313
+ vfs.symlinkSync?.(target, p);
2314
+ }
2315
+ }
2316
+ };
2317
+ }
2318
+
2319
+ /**
2320
+ * Mirrors `gitState` branch & HEAD state into a real `isomorphic-git` `.git/`
2321
+ * directory inside `vfs` so real Git objects/refs/HEAD live on disk for IndexedDB persistence.
2322
+ */
2323
+ export async function syncToIsoGitRepo(vfs: GitVfsLike, gitState: GitState): Promise<void> {
2324
+ if (!vfs || !gitState.initialized || typeof vfs.writeFileSync !== 'function') return;
2325
+ const dir = (gitState.repoRoot || '/workspace').replace(/\/+$/, '') || '/workspace';
2326
+ const fsAdapter = createIsoGitFsAdapter(vfs);
2327
+ try {
2328
+ await isoInit({ fs: fsAdapter, dir, defaultBranch: gitState.branch || 'main' });
2329
+ if (gitState.commits.length > 0) {
2330
+ const latest = gitState.commits[0];
2331
+ const headFiles = gitState.headFiles || gitState.headSnapshot || {};
2332
+ for (const rel of Object.keys(headFiles)) {
2333
+ const abs = `${dir}/${rel}`;
2334
+ if (vfs.existsSync?.(abs)) {
2335
+ await isoAdd({ fs: fsAdapter, dir, filepath: rel });
2336
+ }
2337
+ }
2338
+ await isoCommit({
2339
+ fs: fsAdapter,
2340
+ dir,
2341
+ message: latest.message || 'commit',
2342
+ author: {
2343
+ name: 'CodeLab Developer',
2344
+ email: 'dev@codelab.internal',
2345
+ timestamp: Math.floor((latest.timestamp || Date.now()) / 1000)
2346
+ }
2347
+ });
2348
+ }
2349
+ } catch (err) {
2350
+ // Non-fatal mirror sync if working tree has transient mock VFS constraints
2351
+ const _ignored = err;
2352
+ void _ignored;
2353
+ }
2354
+ }
2355
+
2356
+ /**
2357
+ * Hydrates a `GitState` from an existing `isomorphic-git` `.git/` object store
2358
+ * in `vfs` (for example after restoring `.git/**` from IndexedDB).
2359
+ */
2360
+ export async function hydrateFromIsoGitRepo(
2361
+ vfs: GitVfsLike,
2362
+ repoRoot = '/workspace'
2363
+ ): Promise<GitState | null> {
2364
+ const dir = (repoRoot || '/workspace').replace(/\/+$/, '') || '/workspace';
2365
+ const headPath = `${dir}/.git/HEAD`;
2366
+ if (!vfs || !vfs.existsSync?.(headPath)) return null;
2367
+ const fsAdapter = createIsoGitFsAdapter(vfs);
2368
+ try {
2369
+ const currentBranch = (await isoCurrentBranch({ fs: fsAdapter, dir, fullname: false })) || 'main';
2370
+ const branches = await isoListBranches({ fs: fsAdapter, dir });
2371
+ const logEntries = await isoLog({ fs: fsAdapter, dir, depth: 50 }).catch(() => []);
2372
+ const commits: GitCommitRecord[] = [];
2373
+ for (const entry of logEntries) {
2374
+ commits.push({
2375
+ hash: entry.oid.slice(0, 7),
2376
+ message: entry.commit.message.trim(),
2377
+ timestamp: entry.commit.author.timestamp * 1000,
2378
+ author: `${entry.commit.author.name} <${entry.commit.author.email}>`,
2379
+ date: new Date(entry.commit.author.timestamp * 1000).toUTCString()
2380
+ });
2381
+ }
2382
+ const liveTree = readVfsTree(vfs, dir);
2383
+ const gs = createGitState(commits.length > 0 ? liveTree : {}, String(currentBranch), {
2384
+ initialized: true,
2385
+ repoRoot: dir
2386
+ });
2387
+ gs.branches = branches.length > 0 ? branches : [String(currentBranch)];
2388
+ if (commits.length > 0) {
2389
+ commits[0].files = { ...liveTree };
2390
+ gs.commits = commits;
2391
+ gs.headCommit = commits[0].hash;
2392
+ syncGitHead(gs, liveTree);
2393
+ } else {
2394
+ gs.commits = [];
2395
+ gs.headCommit = '';
2396
+ syncGitHead(gs, {});
2397
+ }
2398
+ saveBranchTip(gs, gs.branch);
2399
+ return gs;
2400
+ } catch (err) {
2401
+ const _ignored = err;
2402
+ void _ignored;
2403
+ return null;
2404
+ }
2405
+ }
2406
+
2407
+ const isoGit = {
2408
+ init: isoInit,
2409
+ add: isoAdd,
2410
+ commit: isoCommit,
2411
+ currentBranch: isoCurrentBranch,
2412
+ listBranches: isoListBranches,
2413
+ log: isoLog
2414
+ };
2415
+
2416
+ export { isoGit };
2417
+
1062
2418
  export default {
1063
2419
  computeShortCommitHash,
2420
+ parseGitignoreRules,
2421
+ isIgnoredByRules,
1064
2422
  isIgnoredScmPath,
1065
2423
  normalizeScmRelPath,
1066
2424
  isUnbornGitHead,
1067
2425
  isEffectiveStagedChange,
1068
2426
  syncGitHead,
2427
+ saveBranchTip,
1069
2428
  createGitState,
2429
+ readVfsTree,
1070
2430
  initRepository,
1071
2431
  computeGitStatus,
1072
2432
  stageFile,
@@ -1074,5 +2434,20 @@ export default {
1074
2434
  unstageFile,
1075
2435
  unstageAll,
1076
2436
  commitChanges,
1077
- discardChanges
2437
+ discardChanges,
2438
+ computeMyersDiffOps,
2439
+ computeUnifiedHunkDiff,
2440
+ computeGitGutterChanges,
2441
+ checkoutBranch,
2442
+ resolveCommitRef,
2443
+ resetToRef,
2444
+ stashPush,
2445
+ stashApply,
2446
+ mergeBranch,
2447
+ showCommit,
2448
+ blameFile,
2449
+ createIsoGitFsAdapter,
2450
+ syncToIsoGitRepo,
2451
+ hydrateFromIsoGitRepo,
2452
+ isoGit
1078
2453
  };