@innovatorved/code-lab 0.7.1 → 0.7.2

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 (71) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +10 -0
  3. package/README.md +5 -5
  4. package/dist/code-lab-sql.esm.js +2 -2
  5. package/dist/code-lab-sql.umd.js +3 -3
  6. package/dist/code-lab.css +1 -1
  7. package/dist/code-lab.d.ts +47 -38
  8. package/dist/code-lab.esm.js +918 -884
  9. package/dist/code-lab.js +917 -881
  10. package/dist/extensions/cpp.esm.js +33 -33
  11. package/dist/extensions/cpp.js +33 -33
  12. package/dist/extensions/python.esm.js +79 -49
  13. package/dist/extensions/python.js +79 -49
  14. package/dist/index.d.ts +1 -1
  15. package/dist/logger.d.ts +4 -20
  16. package/dist/modular-kernel.d.ts +0 -1
  17. package/dist/packages/core/src/errors.d.ts +5 -1
  18. package/dist/packages/fs/src/backends.d.ts +0 -27
  19. package/dist/packages/fs/src/index.d.ts +1 -1
  20. package/dist/packages/ui/src/html.d.ts +1 -0
  21. package/dist/packages/ui/src/index.d.ts +1 -0
  22. package/dist/{apps/web/src/index.d.ts → packages/ui/src/kernel.d.ts} +3 -2
  23. package/dist/packages/ui/src/observability.d.ts +1 -1
  24. package/dist/packages/ui/src/settings-dialog.d.ts +0 -1
  25. package/dist/preview-sw.js +1 -1
  26. package/dist/runtime.d.ts +3 -0
  27. package/dist/runtime.esm.js +2 -2
  28. package/dist/runtime.js +2 -2
  29. package/dist/schemas.d.ts +1 -1
  30. package/dist/shell.esm.js +277 -285
  31. package/dist/shell.js +277 -285
  32. package/dist/terminal.esm.js +2 -2
  33. package/dist/terminal.js +2 -2
  34. package/dist/workbench/editor.d.ts +0 -4
  35. package/dist/workbench/index.d.ts +0 -2
  36. package/dist/workbench/intellisense.d.ts +0 -1
  37. package/dist/workbench/xterm-adapter.d.ts +0 -1
  38. package/package.json +2 -4
  39. package/src/code-lab.css +0 -8086
  40. package/src/csp.ts +0 -590
  41. package/src/diagnostics.ts +0 -287
  42. package/src/extensions/cpp.ts +0 -2371
  43. package/src/extensions/guided-lab.ts +0 -68
  44. package/src/extensions/javascript.ts +0 -54
  45. package/src/extensions/python.ts +0 -1743
  46. package/src/extensions/typescript.ts +0 -85
  47. package/src/extensions/umbrella.ts +0 -5
  48. package/src/html.ts +0 -88
  49. package/src/index.ts +0 -129
  50. package/src/logger.ts +0 -139
  51. package/src/modular-kernel.ts +0 -7
  52. package/src/preview-sw.js +0 -296
  53. package/src/runtime/test-harness.ts +0 -57
  54. package/src/runtime.ts +0 -10565
  55. package/src/sample.html +0 -304
  56. package/src/schemas.ts +0 -366
  57. package/src/scm.ts +0 -2453
  58. package/src/search.ts +0 -433
  59. package/src/shell.ts +0 -10990
  60. package/src/storage.ts +0 -773
  61. package/src/terminal.ts +0 -1402
  62. package/src/workbench/command-palette.ts +0 -101
  63. package/src/workbench/diff-editor.ts +0 -472
  64. package/src/workbench/editor.ts +0 -49
  65. package/src/workbench/icons.ts +0 -255
  66. package/src/workbench/index.ts +0 -29
  67. package/src/workbench/intellisense.ts +0 -1884
  68. package/src/workbench/share.ts +0 -128
  69. package/src/workbench/xterm-adapter.ts +0 -1571
  70. package/src/workbench.ts +0 -21825
  71. package/src/zip.ts +0 -348
package/src/scm.ts DELETED
@@ -1,2453 +0,0 @@
1
- /**
2
- * @innovatorved/code-lab — Interactive Git Source Control (SCM) Engine
3
- * ============================================================================
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.
8
- *
9
- * Strict leaf module: fully typed, zero explicit any, zero empty catches.
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
-
29
- export type GitFileChangeType = 'modified' | 'added' | 'deleted' | 'untracked';
30
-
31
- export interface GitFileStatus {
32
- path: string;
33
- status: GitFileChangeType;
34
- staged: boolean;
35
- oldContent?: string;
36
- newContent?: string;
37
- }
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
-
48
- export interface GitVfsLike {
49
- existsSync?(path: string): boolean;
50
- statSync?(path: string): GitStatLike;
51
- lstatSync?(path: string): GitStatLike;
52
- readdirSync?(path: string): string[];
53
- readFileSync?(path: string, encoding?: string): string | Uint8Array;
54
- writeFileSync?(path: string, data: string | Uint8Array): void;
55
- mkdirSync?(path: string, options?: { recursive?: boolean }): unknown;
56
- rmdirSync?(path: string, options?: { recursive?: boolean }): void;
57
- unlinkSync?(path: string): void;
58
- rmSync?(path: string, options?: { recursive?: boolean; force?: boolean }): void;
59
- symlinkSync?(target: string, path: string): void;
60
- readlinkSync?(path: string): string;
61
- files?: Map<string, unknown>;
62
- }
63
-
64
- export interface GitShellLike {
65
- cwd?: string;
66
- vfs?: GitVfsLike | null;
67
- gitState?: GitState | null;
68
- _emitVfsMutation?(type: string, absPath: string): void;
69
- }
70
-
71
- export interface GitCommitRecord {
72
- hash: string;
73
- message: string;
74
- timestamp: number;
75
- author?: string;
76
- date?: string;
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>;
96
- }
97
-
98
- export interface GitState {
99
- initialized?: boolean;
100
- repoRoot?: string;
101
- branch: string;
102
- branches?: string[] | Set<string>;
103
- branchHeads?: Record<string, GitBranchTip>;
104
- tags?: Record<string, string>;
105
- stashes?: GitStashEntry[];
106
- remoteUrl?: string | null;
107
- remotes?: Record<string, string>;
108
- headCommit: string;
109
- headFiles: Record<string, string>;
110
- headSnapshot?: Record<string, string>;
111
- staged: Map<string, string | null> | Set<string>;
112
- stagedFiles?: Map<string, string | null>;
113
- commits: GitCommitRecord[];
114
- }
115
-
116
- export interface GitStatusEntry {
117
- path: string;
118
- status: GitFileChangeType;
119
- staged: boolean;
120
- index: string;
121
- worktree: string;
122
- }
123
-
124
- export interface GitStatusResult {
125
- branch: string;
126
- headCommit: string;
127
- untracked: GitFileStatus[];
128
- modified: GitFileStatus[];
129
- deleted: GitFileStatus[];
130
- staged: GitFileStatus[];
131
- unstaged: GitFileStatus[];
132
- entries: GitStatusEntry[];
133
- hasChanges: boolean;
134
- isClean: boolean;
135
- }
136
-
137
- export interface CreateGitStateOptions {
138
- initialized?: boolean;
139
- repoRoot?: string;
140
- }
141
-
142
- export interface InitRepositoryOptions {
143
- branch?: string;
144
- repoRoot?: string;
145
- snapshotExisting?: boolean;
146
- initialFiles?: Record<string, string>;
147
- }
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
-
180
- /**
181
- * Computes a deterministic 7-character short hash for a commit payload.
182
- */
183
- export function computeShortCommitHash(input: string): string {
184
- let h1 = 0xdeadbeef ^ input.length;
185
- let h2 = 0x41c6ce57 ^ input.length;
186
- for (let i = 0; i < input.length; i++) {
187
- const ch = input.charCodeAt(i);
188
- h1 = Math.imul(h1 ^ ch, 2654435761);
189
- h2 = Math.imul(h2 ^ ch, 1597334677);
190
- }
191
- h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
192
- h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
193
- const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
194
- return combined.toString(16).padStart(7, '0').slice(0, 7);
195
- }
196
-
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 {
274
- if (!relPath) return true;
275
- if (
276
- relPath === '.git' ||
277
- relPath.startsWith('.git/') ||
278
- relPath.includes('/.git/') ||
279
- relPath.endsWith('/.git')
280
- ) {
281
- return true;
282
- }
283
- if (
284
- relPath === 'node_modules' ||
285
- relPath.startsWith('node_modules/') ||
286
- relPath.includes('/node_modules/') ||
287
- relPath.endsWith('/node_modules')
288
- ) {
289
- return true;
290
- }
291
- if (gitignoreRules && gitignoreRules.length > 0 && relPath !== '.gitignore') {
292
- return isIgnoredByRules(relPath, gitignoreRules);
293
- }
294
- return false;
295
- }
296
-
297
- export function normalizeScmRelPath(rawPath: string, repoRoot = '/workspace'): string {
298
- if (typeof rawPath !== 'string') return '';
299
- let p = rawPath.trim().replace(/\\/g, '/');
300
- if (!p) return '';
301
-
302
- const cleanRoot = (repoRoot || '/workspace').replace(/\\/g, '/').replace(/\/+$/, '') || '/';
303
- if (p === cleanRoot) return '';
304
- if (cleanRoot !== '/' && p.startsWith(`${cleanRoot}/`)) {
305
- p = p.slice(cleanRoot.length + 1);
306
- } else if (p.startsWith('/workspace/') && cleanRoot === '/workspace') {
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
- }
313
- }
314
-
315
- while (p.startsWith('./')) {
316
- p = p.slice(2);
317
- }
318
- if (p.startsWith('/')) {
319
- p = p.replace(/^\/+/, '');
320
- }
321
-
322
- const out: string[] = [];
323
- for (const seg of p.split('/')) {
324
- if (!seg || seg === '.') continue;
325
- if (seg === '..') {
326
- if (out.length === 0) return '';
327
- out.pop();
328
- continue;
329
- }
330
- out.push(seg);
331
- }
332
- return out.join('/');
333
- }
334
-
335
- function extractGitignoreRules(
336
- rawFiles: Record<string, string> | undefined,
337
- fallbackFiles: Record<string, string> | undefined,
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>
360
- ): Record<string, string> {
361
- const out: Record<string, string> = {};
362
- if (!rawFiles || typeof rawFiles !== 'object') return out;
363
- for (const [k, v] of Object.entries(rawFiles)) {
364
- const rel = normalizeScmRelPath(k, repoRoot);
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
- }
370
- out[rel] = String(v ?? '');
371
- }
372
- return out;
373
- }
374
-
375
- export function isUnbornGitHead(gitState: GitState | null | undefined): boolean {
376
- return (
377
- (!Array.isArray(gitState?.commits) || gitState.commits.length === 0) &&
378
- !gitState?.headCommit
379
- );
380
- }
381
-
382
- export function isEffectiveStagedChange(
383
- gitState: GitState | null | undefined,
384
- relPath: string,
385
- stagedVal: string | null | undefined,
386
- resolvedHeadFiles?: Record<string, string>
387
- ): boolean {
388
- if (!relPath || isIgnoredScmPath(relPath)) return false;
389
- const repoRoot = gitState?.repoRoot || '/workspace';
390
- const headFiles =
391
- resolvedHeadFiles ?? cleanFileMap(gitState?.headFiles || gitState?.headSnapshot || {}, repoRoot);
392
- const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
393
- const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
394
-
395
- if (normalizedVal === null) {
396
- return inHead;
397
- }
398
- if (!inHead || isUnbornGitHead(gitState)) {
399
- return true;
400
- }
401
- return normalizedVal !== headFiles[relPath];
402
- }
403
-
404
- function applyStagedEntry(
405
- gitState: GitState | null | undefined,
406
- map: Map<string, string | null>,
407
- rawPath: string,
408
- rawVal: string | null | undefined,
409
- resolvedHeadFiles?: Record<string, string>
410
- ): void {
411
- const repoRoot = gitState?.repoRoot || '/workspace';
412
- const rel = normalizeScmRelPath(rawPath, repoRoot);
413
- if (!rel || isIgnoredScmPath(rel)) return;
414
- const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
415
- if (isEffectiveStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
416
- map.set(rel, normalizedVal);
417
- } else {
418
- map.delete(rel);
419
- }
420
- }
421
-
422
- function pruneStagedMapInPlace(
423
- gitState: GitState | null | undefined,
424
- map: Map<string, string | null>,
425
- resolvedHeadFiles?: Record<string, string>
426
- ): void {
427
- const repoRoot = gitState?.repoRoot || '/workspace';
428
- const headFiles =
429
- resolvedHeadFiles ?? cleanFileMap(gitState?.headFiles || gitState?.headSnapshot || {}, repoRoot);
430
- for (const [rawK, rawV] of Array.from(map.entries())) {
431
- const rel = normalizeScmRelPath(rawK, repoRoot);
432
- if (rel !== rawK) {
433
- map.delete(rawK);
434
- }
435
- if (!rel || isIgnoredScmPath(rel)) {
436
- map.delete(rawK);
437
- continue;
438
- }
439
- const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
440
- if (isEffectiveStagedChange(gitState, rel, normalizedVal, headFiles)) {
441
- map.set(rel, normalizedVal);
442
- } else {
443
- map.delete(rel);
444
- }
445
- }
446
- }
447
-
448
- function attachSetCompatShim(
449
- map: Map<string, string | null>,
450
- gitState?: GitState,
451
- resolveContent?: (relPath: string) => string | null
452
- ): Map<string, string | null> {
453
- const mapObj = map as unknown as Record<string, unknown>;
454
- if (typeof mapObj.add !== 'function') {
455
- Object.defineProperty(map, 'add', {
456
- value: (rawPath: string) => {
457
- const repoRoot = gitState?.repoRoot || '/workspace';
458
- const rel = normalizeScmRelPath(rawPath, repoRoot);
459
- if (rel && !isIgnoredScmPath(rel)) {
460
- const val = resolveContent ? resolveContent(rel) : null;
461
- applyStagedEntry(gitState, map, rel, val);
462
- }
463
- return map;
464
- },
465
- enumerable: false,
466
- configurable: true,
467
- writable: true
468
- });
469
- }
470
- return map;
471
- }
472
-
473
- /**
474
- * Synchronizes `gitState.headFiles` and `gitState.headSnapshot` so both
475
- * properties reference the exact same clean `Record<string, string>` object.
476
- */
477
- export function syncGitHead(
478
- gitState: GitState,
479
- nextHead?: Record<string, string>
480
- ): Record<string, string> {
481
- const repoRoot = gitState.repoRoot || '/workspace';
482
- const source =
483
- nextHead !== undefined ? nextHead : (gitState.headFiles || gitState.headSnapshot || {});
484
- const synced = cleanFileMap(source, repoRoot);
485
- gitState.headFiles = synced;
486
- gitState.headSnapshot = synced;
487
- return synced;
488
- }
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
-
524
- function ensureStagedMap(
525
- gitState: GitState,
526
- vfsFiles?: Record<string, string>
527
- ): Map<string, string | null> {
528
- const repoRoot = gitState.repoRoot || '/workspace';
529
- const head = cleanFileMap(gitState.headFiles || gitState.headSnapshot || {}, repoRoot);
530
- const resolveContent = (rel: string): string | null => {
531
- if (vfsFiles) {
532
- return Object.prototype.hasOwnProperty.call(vfsFiles, rel) ? vfsFiles[rel] : null;
533
- }
534
- return Object.prototype.hasOwnProperty.call(head, rel) ? head[rel] : null;
535
- };
536
-
537
- if (gitState.staged instanceof Map) {
538
- const shimmed = attachSetCompatShim(gitState.staged, gitState, resolveContent);
539
- pruneStagedMapInPlace(gitState, shimmed, head);
540
- gitState.stagedFiles = shimmed;
541
- return shimmed;
542
- }
543
-
544
- const migrated = attachSetCompatShim(new Map<string, string | null>(), gitState, resolveContent);
545
-
546
- if (gitState.staged instanceof Set) {
547
- for (const rawPath of gitState.staged.values()) {
548
- const rel = normalizeScmRelPath(rawPath, repoRoot);
549
- if (!rel || isIgnoredScmPath(rel)) continue;
550
- applyStagedEntry(gitState, migrated, rel, resolveContent(rel), head);
551
- }
552
- }
553
-
554
- gitState.staged = migrated;
555
- gitState.stagedFiles = migrated;
556
- return migrated;
557
- }
558
-
559
- /**
560
- * Initializes an in-memory Git repository state from initial VFS files,
561
- * keeping `headFiles` / `headSnapshot` and `staged` / `stagedFiles` synchronized.
562
- */
563
- export function createGitState(
564
- initialFiles: Record<string, string> = {},
565
- branch = 'main',
566
- options?: CreateGitStateOptions
567
- ): GitState {
568
- const repoRoot = options?.repoRoot || '/workspace';
569
- const isInit = options?.initialized !== false;
570
- let _initialized = isInit;
571
- let _repoRoot = repoRoot;
572
- let _headFiles: Record<string, string> = isInit ? cleanFileMap(initialFiles, repoRoot) : {};
573
- let _headCommit = isInit ? computeShortCommitHash(JSON.stringify(_headFiles) + ':init') : '';
574
- const now = Date.now();
575
- let _commits: GitCommitRecord[] = isInit
576
- ? [
577
- {
578
- hash: _headCommit,
579
- message: 'Initial commit',
580
- timestamp: now,
581
- author: 'CodeLab Developer <dev@codelab.internal>',
582
- date: new Date(now).toUTCString(),
583
- files: { ..._headFiles }
584
- }
585
- ]
586
- : [];
587
-
588
- const stateObj = {
589
- branch,
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[],
602
- remoteUrl: null as string | null,
603
- remotes: {} as Record<string, string>
604
- } as unknown as GitState;
605
-
606
- const resolveFromHead = (rel: string): string | null =>
607
- Object.prototype.hasOwnProperty.call(_headFiles, rel) ? _headFiles[rel] : null;
608
-
609
- let _stagedMap = attachSetCompatShim(new Map<string, string | null>(), stateObj, resolveFromHead);
610
-
611
- Object.defineProperties(stateObj, {
612
- initialized: {
613
- enumerable: true,
614
- configurable: true,
615
- get(): boolean {
616
- return _initialized;
617
- },
618
- set(v: boolean) {
619
- _initialized = Boolean(v);
620
- }
621
- },
622
- repoRoot: {
623
- enumerable: true,
624
- configurable: true,
625
- get(): string {
626
- return _repoRoot;
627
- },
628
- set(v: string) {
629
- _repoRoot = String(v || '/workspace');
630
- }
631
- },
632
- headCommit: {
633
- enumerable: true,
634
- configurable: true,
635
- get(): string {
636
- return _headCommit;
637
- },
638
- set(v: string) {
639
- _headCommit = String(v || '');
640
- }
641
- },
642
- headFiles: {
643
- enumerable: true,
644
- configurable: true,
645
- get(): Record<string, string> {
646
- return _headFiles;
647
- },
648
- set(v: Record<string, string>) {
649
- _headFiles = v && typeof v === 'object' ? v : {};
650
- }
651
- },
652
- headSnapshot: {
653
- enumerable: true,
654
- configurable: true,
655
- get(): Record<string, string> {
656
- return _headFiles;
657
- },
658
- set(v: Record<string, string>) {
659
- _headFiles = v && typeof v === 'object' ? v : {};
660
- }
661
- },
662
- staged: {
663
- enumerable: true,
664
- configurable: true,
665
- get(): Map<string, string | null> {
666
- return _stagedMap;
667
- },
668
- set(v: Map<string, string | null> | Set<string>) {
669
- if (v instanceof Map) {
670
- _stagedMap = attachSetCompatShim(v, stateObj, resolveFromHead);
671
- pruneStagedMapInPlace(stateObj, _stagedMap);
672
- } else {
673
- const next = attachSetCompatShim(
674
- new Map<string, string | null>(),
675
- stateObj,
676
- resolveFromHead
677
- );
678
- if (v instanceof Set) {
679
- for (const raw of v.values()) {
680
- const rel = normalizeScmRelPath(raw, _repoRoot);
681
- if (!rel || isIgnoredScmPath(rel)) continue;
682
- applyStagedEntry(stateObj, next, rel, resolveFromHead(rel));
683
- }
684
- }
685
- _stagedMap = next;
686
- }
687
- }
688
- },
689
- stagedFiles: {
690
- enumerable: true,
691
- configurable: true,
692
- get(): Map<string, string | null> {
693
- return _stagedMap;
694
- },
695
- set(v: Map<string, string | null>) {
696
- if (v instanceof Map) {
697
- _stagedMap = attachSetCompatShim(v, stateObj, resolveFromHead);
698
- pruneStagedMapInPlace(stateObj, _stagedMap);
699
- }
700
- }
701
- },
702
- commits: {
703
- enumerable: true,
704
- configurable: true,
705
- get(): GitCommitRecord[] {
706
- return _commits;
707
- },
708
- set(v: GitCommitRecord[]) {
709
- _commits = Array.isArray(v) ? v : [];
710
- if (_commits.length > 0 && _commits[0]?.hash) {
711
- _headCommit = _commits[0].hash;
712
- } else if (_commits.length === 0) {
713
- _headCommit = '';
714
- }
715
- }
716
- }
717
- });
718
-
719
- return stateObj;
720
- }
721
-
722
- export function readVfsTree(vfs: GitVfsLike, rootDir: string): Record<string, string> {
723
- const out: Record<string, string> = {};
724
- if (
725
- !vfs ||
726
- typeof vfs.existsSync !== 'function' ||
727
- typeof vfs.readdirSync !== 'function' ||
728
- typeof vfs.statSync !== 'function' ||
729
- typeof vfs.readFileSync !== 'function'
730
- ) {
731
- return out;
732
- }
733
- const cleanRoot = rootDir.replace(/\/+$/, '') || '/';
734
- if (!vfs.existsSync(cleanRoot)) return out;
735
-
736
- const walk = (dir: string): void => {
737
- let entries: string[] = [];
738
- try {
739
- entries = vfs.readdirSync ? vfs.readdirSync(dir) : [];
740
- } catch (err) {
741
- const _ignored = err;
742
- void _ignored;
743
- return;
744
- }
745
- for (const name of entries) {
746
- if (name === '.git' || name === 'node_modules') continue;
747
- const full = dir === '/' ? `/${name}` : `${dir}/${name}`;
748
- try {
749
- const st = vfs.statSync ? vfs.statSync(full) : null;
750
- if (st && st.isDirectory()) {
751
- walk(full);
752
- } else {
753
- const rel = normalizeScmRelPath(full, cleanRoot);
754
- if (!rel || isIgnoredScmPath(rel)) continue;
755
- const raw = vfs.readFileSync ? vfs.readFileSync(full, 'utf8') : '';
756
- out[rel] = typeof raw === 'string' ? raw : new TextDecoder().decode(raw);
757
- }
758
- } catch (err) {
759
- const _ignored = err;
760
- void _ignored;
761
- }
762
- }
763
- };
764
-
765
- walk(cleanRoot);
766
- return out;
767
- }
768
-
769
- function isGitShellLike(target: GitShellLike | GitState): target is GitShellLike {
770
- return (
771
- Boolean(target && typeof target === 'object') &&
772
- ('vfs' in target || 'gitState' in target || ('cwd' in target && !('headFiles' in target)))
773
- );
774
- }
775
-
776
- /**
777
- * Initializes a Git repository on a `PosixShell` (writing `.git/HEAD` & `.git/config`)
778
- * or directly on a `GitState` object. Defaults `snapshotExisting` to `false` so
779
- * existing workspace files appear as untracked until staged and committed.
780
- */
781
- export function initRepository(
782
- target: GitShellLike | GitState,
783
- options?: InitRepositoryOptions
784
- ): GitState {
785
- if (isGitShellLike(target)) {
786
- const repoRoot =
787
- (options?.repoRoot || target.gitState?.repoRoot || target.cwd || '/workspace').replace(
788
- /\/+$/,
789
- ''
790
- ) || '/';
791
- const branch = options?.branch || target.gitState?.branch || 'main';
792
- const vfs = target.vfs ?? null;
793
-
794
- if (vfs) {
795
- const gitDir = repoRoot === '/' ? '/.git' : `${repoRoot}/.git`;
796
- const headPath = `${gitDir}/HEAD`;
797
- const configPath = `${gitDir}/config`;
798
- if (typeof vfs.mkdirSync === 'function' && (!vfs.existsSync || !vfs.existsSync(gitDir))) {
799
- vfs.mkdirSync(gitDir, { recursive: true });
800
- }
801
- vfs.writeFileSync?.(headPath, `ref: refs/heads/${branch}\n`);
802
- vfs.writeFileSync?.(
803
- configPath,
804
- `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
805
- );
806
- target._emitVfsMutation?.('create', headPath);
807
- }
808
-
809
- const snap = options?.snapshotExisting
810
- ? options.initialFiles
811
- ? cleanFileMap(options.initialFiles, repoRoot)
812
- : vfs
813
- ? readVfsTree(vfs, repoRoot)
814
- : {}
815
- : {};
816
-
817
- let gs = target.gitState;
818
- if (!gs) {
819
- gs = createGitState(snap, branch, { initialized: true, repoRoot });
820
- if (!options?.snapshotExisting) {
821
- gs.commits = [];
822
- gs.headCommit = '';
823
- }
824
- saveBranchTip(gs, branch);
825
- target.gitState = gs;
826
- if (vfs) void syncToIsoGitRepo(vfs, gs);
827
- return gs;
828
- }
829
-
830
- gs.initialized = true;
831
- gs.repoRoot = repoRoot;
832
- gs.branch = branch;
833
- ensureBranchList(gs, branch);
834
- ensureStagedMap(gs).clear();
835
- syncGitHead(gs, snap);
836
- if (!options?.snapshotExisting && gs.commits.length === 0) {
837
- gs.headCommit = '';
838
- }
839
- saveBranchTip(gs, branch);
840
- if (vfs) void syncToIsoGitRepo(vfs, gs);
841
- return gs;
842
- }
843
-
844
- const gs = target;
845
- const repoRoot = options?.repoRoot || gs.repoRoot || '/workspace';
846
- const branch = options?.branch || gs.branch || 'main';
847
- gs.initialized = true;
848
- gs.repoRoot = repoRoot;
849
- gs.branch = branch;
850
- ensureBranchList(gs, branch);
851
- ensureStagedMap(gs).clear();
852
- syncGitHead(gs, options?.snapshotExisting ? options.initialFiles || {} : {});
853
- saveBranchTip(gs, branch);
854
- return gs;
855
- }
856
-
857
- /**
858
- * Computes working-tree and staging-area Git status against `gitState`,
859
- * honoring `.gitignore` rules for untracked files while keeping tracked files visible.
860
- */
861
- export function computeGitStatus(
862
- arg1: Record<string, string> | GitState,
863
- arg2: string | Record<string, string> = '/workspace',
864
- gitState?: GitState
865
- ): GitStatusResult {
866
- let rawVfsFiles: Record<string, string>;
867
- let repoRoot = '/workspace';
868
- let state: GitState;
869
-
870
- if (
871
- arg1 &&
872
- typeof arg1 === 'object' &&
873
- ('headFiles' in arg1 || 'headSnapshot' in arg1 || 'staged' in arg1 || 'commits' in arg1)
874
- ) {
875
- state = arg1 as GitState;
876
- rawVfsFiles = (arg2 && typeof arg2 === 'object' ? arg2 : {}) as Record<string, string>;
877
- repoRoot = state.repoRoot || '/workspace';
878
- } else {
879
- rawVfsFiles = (arg1 && typeof arg1 === 'object' ? arg1 : {}) as Record<string, string>;
880
- repoRoot = typeof arg2 === 'string' && arg2 ? arg2 : gitState?.repoRoot || '/workspace';
881
- state = gitState || createGitState({});
882
- }
883
-
884
- const headFiles = cleanFileMap(state.headFiles || state.headSnapshot || {}, repoRoot);
885
- const ignoreRules = extractGitignoreRules(rawVfsFiles, headFiles, repoRoot);
886
- const vfsFiles = cleanFileMap(rawVfsFiles, repoRoot, ignoreRules, headFiles);
887
- const unbornHead = isUnbornGitHead(state);
888
-
889
- const currentStaged = new Map<string, string | null>();
890
- if (state.staged instanceof Map) {
891
- for (const [rawK, v] of state.staged.entries()) {
892
- const k = normalizeScmRelPath(rawK, repoRoot);
893
- if (!k || isIgnoredScmPath(k)) continue;
894
- const normalizedV = v === undefined || v === null ? null : String(v);
895
- if (!isEffectiveStagedChange(state, k, normalizedV, headFiles)) continue;
896
- currentStaged.set(k, normalizedV);
897
- }
898
- } else if (state.staged instanceof Set) {
899
- for (const rawK of state.staged.values()) {
900
- const k = normalizeScmRelPath(rawK, repoRoot);
901
- if (!k || isIgnoredScmPath(k)) continue;
902
- const existsInVfs = Object.prototype.hasOwnProperty.call(vfsFiles, k);
903
- const normalizedV = existsInVfs ? vfsFiles[k] : null;
904
- if (!isEffectiveStagedChange(state, k, normalizedV, headFiles)) continue;
905
- currentStaged.set(k, normalizedV);
906
- }
907
- }
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
-
921
- const untracked: GitFileStatus[] = [];
922
- const modified: GitFileStatus[] = [];
923
- const deleted: GitFileStatus[] = [];
924
- const staged: GitFileStatus[] = [];
925
-
926
- for (const [filePath, stagedContent] of currentStaged.entries()) {
927
- const inHead = Object.prototype.hasOwnProperty.call(headFiles, filePath);
928
- const effectiveInHead = inHead && !unbornHead;
929
- if (stagedContent === null) {
930
- if (inHead) {
931
- staged.push({
932
- path: filePath,
933
- status: 'deleted',
934
- staged: true,
935
- oldContent: headFiles[filePath]
936
- });
937
- }
938
- } else {
939
- staged.push({
940
- path: filePath,
941
- status: effectiveInHead ? 'modified' : 'added',
942
- staged: true,
943
- oldContent: effectiveInHead ? headFiles[filePath] : undefined,
944
- newContent: stagedContent
945
- });
946
- if (!Object.prototype.hasOwnProperty.call(vfsFiles, filePath)) {
947
- deleted.push({
948
- path: filePath,
949
- status: 'deleted',
950
- staged: false,
951
- oldContent: stagedContent
952
- });
953
- }
954
- }
955
- }
956
-
957
- for (const [filePath, content] of Object.entries(vfsFiles)) {
958
- if (currentStaged.has(filePath)) {
959
- const stagedVal = currentStaged.get(filePath);
960
- if (stagedVal === null) {
961
- untracked.push({
962
- path: filePath,
963
- status: 'untracked',
964
- staged: false,
965
- newContent: content
966
- });
967
- } else if (stagedVal !== content) {
968
- modified.push({
969
- path: filePath,
970
- status: 'modified',
971
- staged: false,
972
- oldContent: stagedVal ?? undefined,
973
- newContent: content
974
- });
975
- }
976
- } else if (Object.prototype.hasOwnProperty.call(headFiles, filePath)) {
977
- if (headFiles[filePath] !== content) {
978
- modified.push({
979
- path: filePath,
980
- status: 'modified',
981
- staged: false,
982
- oldContent: headFiles[filePath],
983
- newContent: content
984
- });
985
- }
986
- } else {
987
- untracked.push({
988
- path: filePath,
989
- status: 'untracked',
990
- staged: false,
991
- newContent: content
992
- });
993
- }
994
- }
995
-
996
- for (const filePath of Object.keys(headFiles)) {
997
- if (
998
- !Object.prototype.hasOwnProperty.call(vfsFiles, filePath) &&
999
- !currentStaged.has(filePath)
1000
- ) {
1001
- deleted.push({
1002
- path: filePath,
1003
- status: 'deleted',
1004
- staged: false,
1005
- oldContent: headFiles[filePath]
1006
- });
1007
- }
1008
- }
1009
-
1010
- const modifiedPaths = new Set(modified.map((m) => m.path));
1011
- const deletedPaths = new Set(deleted.map((d) => d.path));
1012
- const stagedIndexByPath = new Map<string, string>();
1013
- for (const s of staged) {
1014
- stagedIndexByPath.set(
1015
- s.path,
1016
- s.status === 'added' ? 'A' : s.status === 'deleted' ? 'D' : 'M'
1017
- );
1018
- }
1019
-
1020
- const unstaged: GitFileStatus[] = [...modified, ...deleted];
1021
- const entries: GitStatusEntry[] = [
1022
- ...staged.map((s) => ({
1023
- path: s.path,
1024
- status: s.status,
1025
- staged: true,
1026
- index: stagedIndexByPath.get(s.path) || 'M',
1027
- worktree: modifiedPaths.has(s.path) ? 'M' : deletedPaths.has(s.path) ? 'D' : ' '
1028
- })),
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
- })),
1047
- ...untracked.map((u) => ({
1048
- path: u.path,
1049
- status: u.status,
1050
- staged: false,
1051
- index: '?',
1052
- worktree: '?'
1053
- }))
1054
- ];
1055
-
1056
- const isClean =
1057
- untracked.length === 0 &&
1058
- modified.length === 0 &&
1059
- deleted.length === 0 &&
1060
- staged.length === 0;
1061
-
1062
- return {
1063
- branch: state.branch || 'main',
1064
- headCommit: state.headCommit || '',
1065
- untracked,
1066
- modified,
1067
- deleted,
1068
- staged,
1069
- unstaged,
1070
- entries,
1071
- hasChanges: !isClean,
1072
- isClean
1073
- };
1074
- }
1075
-
1076
- /**
1077
- * Stages a file addition, modification, or deletion (`currentContent === null`).
1078
- */
1079
- export function stageFile(
1080
- gitState: GitState,
1081
- relativePath: string,
1082
- currentContent: string | null
1083
- ): void {
1084
- if (!gitState) return;
1085
- const repoRoot = gitState.repoRoot || '/workspace';
1086
- const rel = normalizeScmRelPath(relativePath, repoRoot);
1087
- if (!rel || isIgnoredScmPath(rel)) return;
1088
-
1089
- const headFiles = cleanFileMap(gitState.headFiles || gitState.headSnapshot || {}, repoRoot);
1090
- const stagedMap = ensureStagedMap(gitState);
1091
- const normalizedContent =
1092
- currentContent === undefined || currentContent === null ? null : String(currentContent);
1093
- applyStagedEntry(gitState, stagedMap, rel, normalizedContent, headFiles);
1094
- }
1095
-
1096
- /**
1097
- * Stages all modified, untracked (non-gitignored), and deleted tracked files.
1098
- */
1099
- export function stageAll(
1100
- gitState: GitState,
1101
- vfsFiles: Record<string, string>,
1102
- repoRoot = '/workspace'
1103
- ): void {
1104
- if (!gitState) return;
1105
- const resolvedRoot = gitState.repoRoot || repoRoot || '/workspace';
1106
- const headFiles = cleanFileMap(gitState.headFiles || gitState.headSnapshot || {}, resolvedRoot);
1107
- const ignoreRules = extractGitignoreRules(vfsFiles, headFiles, resolvedRoot);
1108
- const cleanVfs = cleanFileMap(vfsFiles, resolvedRoot, ignoreRules, headFiles);
1109
- const stagedMap = ensureStagedMap(gitState, cleanVfs);
1110
-
1111
- for (const [rel, content] of Object.entries(cleanVfs)) {
1112
- applyStagedEntry(gitState, stagedMap, rel, content, headFiles);
1113
- }
1114
-
1115
- for (const rel of Object.keys(headFiles)) {
1116
- if (!Object.prototype.hasOwnProperty.call(cleanVfs, rel)) {
1117
- applyStagedEntry(gitState, stagedMap, rel, null, headFiles);
1118
- }
1119
- }
1120
-
1121
- for (const stagedKey of Array.from(stagedMap.keys())) {
1122
- const normKey = normalizeScmRelPath(stagedKey, resolvedRoot);
1123
- if (
1124
- !normKey ||
1125
- isIgnoredScmPath(normKey) ||
1126
- (!Object.prototype.hasOwnProperty.call(cleanVfs, normKey) &&
1127
- !Object.prototype.hasOwnProperty.call(headFiles, normKey))
1128
- ) {
1129
- stagedMap.delete(stagedKey);
1130
- }
1131
- }
1132
- }
1133
-
1134
- /**
1135
- * Removes a file from the staging index.
1136
- */
1137
- export function unstageFile(gitState: GitState, relativePath: string): void {
1138
- if (!gitState) return;
1139
- const repoRoot = gitState.repoRoot || '/workspace';
1140
- const rel = normalizeScmRelPath(relativePath, repoRoot);
1141
- if (gitState.staged instanceof Map) {
1142
- gitState.staged.delete(rel);
1143
- gitState.staged.delete(relativePath);
1144
- } else if (gitState.staged instanceof Set) {
1145
- gitState.staged.delete(rel);
1146
- gitState.staged.delete(relativePath);
1147
- }
1148
- }
1149
-
1150
- /**
1151
- * Clears all staged entries from `gitState`.
1152
- */
1153
- export function unstageAll(gitState: GitState): void {
1154
- if (!gitState || !gitState.staged) return;
1155
- gitState.staged.clear();
1156
- }
1157
-
1158
- /**
1159
- * Commits all staged changes to `gitState`, advancing `headCommit`, updating
1160
- * `branchHeads[branch]`, synchronizing `headFiles` & `headSnapshot`, and clearing staging.
1161
- */
1162
- export function commitChanges(
1163
- gitState: GitState,
1164
- message: string,
1165
- author = 'CodeLab Developer <dev@codelab.internal>'
1166
- ): string {
1167
- const trimmed = typeof message === 'string' ? message.trim() : '';
1168
- if (!trimmed) {
1169
- throw new Error('Commit message cannot be empty');
1170
- }
1171
- if (!gitState) {
1172
- throw new Error('Nothing to commit (staging area is empty)');
1173
- }
1174
-
1175
- const repoRoot = gitState.repoRoot || '/workspace';
1176
- const newHeadFiles: Record<string, string> = cleanFileMap(
1177
- gitState.headFiles || gitState.headSnapshot || {},
1178
- repoRoot
1179
- );
1180
- const stagedMap = ensureStagedMap(gitState);
1181
- pruneStagedMapInPlace(gitState, stagedMap, newHeadFiles);
1182
-
1183
- if (stagedMap.size === 0) {
1184
- throw new Error('Nothing to commit (staging area is empty)');
1185
- }
1186
- const diffSummaryParts: string[] = [];
1187
- for (const [rawPath, content] of stagedMap.entries()) {
1188
- const filePath = normalizeScmRelPath(rawPath, repoRoot);
1189
- if (!filePath || isIgnoredScmPath(filePath)) continue;
1190
- diffSummaryParts.push(`${filePath}:${content === null ? '<DEL>' : content}`);
1191
- if (content === null) {
1192
- delete newHeadFiles[filePath];
1193
- } else {
1194
- newHeadFiles[filePath] = content;
1195
- }
1196
- }
1197
-
1198
- const timestamp = Date.now();
1199
- const commitSeq = Array.isArray(gitState.commits) ? gitState.commits.length : 0;
1200
- const parentHashes = gitState.headCommit ? [gitState.headCommit] : [];
1201
- const hash = computeShortCommitHash(
1202
- `${gitState.headCommit}:${trimmed}:${timestamp}:${commitSeq}:${diffSummaryParts.join('|')}`
1203
- );
1204
- const syncedHead = syncGitHead(gitState, newHeadFiles);
1205
- const commit: GitCommitRecord = {
1206
- hash,
1207
- message: trimmed,
1208
- timestamp,
1209
- author,
1210
- date: new Date(timestamp).toUTCString(),
1211
- files: { ...syncedHead },
1212
- parents: parentHashes
1213
- };
1214
-
1215
- if (!Array.isArray(gitState.commits)) {
1216
- gitState.commits = [];
1217
- }
1218
- gitState.commits.unshift(commit);
1219
- gitState.initialized = true;
1220
- gitState.headCommit = hash;
1221
- stagedMap.clear();
1222
- ensureBranchList(gitState, gitState.branch || 'main');
1223
- saveBranchTip(gitState, gitState.branch || 'main');
1224
-
1225
- return hash;
1226
- }
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
-
1266
- /**
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`.
1272
- */
1273
- export function discardChanges(
1274
- shell: GitShellLike,
1275
- filePath: string,
1276
- workspaceFiles?: Record<string, string>,
1277
- options?: DiscardChangesOptions
1278
- ): boolean {
1279
- if (!shell || typeof filePath !== 'string' || !filePath.trim()) {
1280
- return false;
1281
- }
1282
-
1283
- const gs = shell.gitState ?? null;
1284
- const repoRoot = ((gs && gs.repoRoot) || shell.cwd || '/workspace').replace(/\/+$/, '') || '/';
1285
- const relPath = normalizeScmRelPath(filePath, repoRoot);
1286
- if (!relPath || isIgnoredScmPath(relPath)) {
1287
- return false;
1288
- }
1289
-
1290
- const absPath = repoRoot === '/' ? `/${relPath}` : `${repoRoot}/${relPath}`;
1291
- const headFiles = gs ? cleanFileMap(gs.headFiles || gs.headSnapshot || {}, repoRoot) : {};
1292
- const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
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
- }
1311
-
1312
- if (inHead) {
1313
- const headContent = headFiles[relPath];
1314
- writeVfsFileSafe(vfs, absPath, headContent, shell);
1315
- if (workspaceFiles && typeof workspaceFiles === 'object') {
1316
- workspaceFiles[relPath] = headContent;
1317
- }
1318
- if (gs) {
1319
- unstageFile(gs, relPath);
1320
- }
1321
- return true;
1322
- }
1323
-
1324
- const existsInVfs = Boolean(vfs && typeof vfs.existsSync === 'function' && vfs.existsSync(absPath));
1325
- const existsInMapVfs = Boolean(vfs && vfs.files instanceof Map && vfs.files.has(absPath));
1326
- const existsInWs = Boolean(
1327
- workspaceFiles && Object.prototype.hasOwnProperty.call(workspaceFiles, relPath)
1328
- );
1329
- const existsInStaged = Boolean(stagedMap && stagedMap.has(relPath));
1330
-
1331
- if (!existsInVfs && !existsInMapVfs && !existsInWs && !existsInStaged) {
1332
- return false;
1333
- }
1334
-
1335
- deleteVfsFileSafe(vfs, absPath, shell);
1336
-
1337
- if (workspaceFiles && typeof workspaceFiles === 'object') {
1338
- delete workspaceFiles[relPath];
1339
- }
1340
- if (gs) {
1341
- unstageFile(gs, relPath);
1342
- }
1343
- return true;
1344
- }
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
-
2418
- export default {
2419
- computeShortCommitHash,
2420
- parseGitignoreRules,
2421
- isIgnoredByRules,
2422
- isIgnoredScmPath,
2423
- normalizeScmRelPath,
2424
- isUnbornGitHead,
2425
- isEffectiveStagedChange,
2426
- syncGitHead,
2427
- saveBranchTip,
2428
- createGitState,
2429
- readVfsTree,
2430
- initRepository,
2431
- computeGitStatus,
2432
- stageFile,
2433
- stageAll,
2434
- unstageFile,
2435
- unstageAll,
2436
- commitChanges,
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
2453
- };