@innovatorved/code-lab 0.4.0 → 0.5.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 (64) hide show
  1. package/ARCHITECTURE.md +2 -2
  2. package/CHANGELOG.md +21 -0
  3. package/README.md +4 -28
  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 +1553 -98
  7. package/dist/code-lab.d.ts +1 -1
  8. package/dist/code-lab.esm.js +11883 -1619
  9. package/dist/code-lab.js +11882 -1618
  10. package/dist/code-lab.umd.js +11882 -1618
  11. package/dist/diagnostics.d.ts +3 -0
  12. package/dist/extensions/cpp.esm.js +27 -29
  13. package/dist/extensions/cpp.js +27 -29
  14. package/dist/extensions/python.esm.js +27 -28
  15. package/dist/extensions/python.js +27 -28
  16. package/dist/index.d.ts +1 -1
  17. package/dist/packages/settings/src/configuration-service.d.ts +7 -0
  18. package/dist/packages/settings/src/index.d.ts +1 -1
  19. package/dist/packages/ui/src/index.d.ts +2 -2
  20. package/dist/packages/ui/src/plugin-registry.d.ts +1 -0
  21. package/dist/packages/ui/src/settings-dialog.d.ts +31 -3
  22. package/dist/packages/ui/src/themes.d.ts +5 -0
  23. package/dist/preview-sw.js +1 -1
  24. package/dist/runtime.esm.js +1 -1
  25. package/dist/runtime.js +1 -1
  26. package/dist/schemas.d.ts +1 -1
  27. package/dist/scm.d.ts +92 -11
  28. package/dist/shell.esm.js +937 -113
  29. package/dist/shell.js +937 -113
  30. package/dist/storage.d.ts +47 -0
  31. package/dist/terminal.esm.js +1 -1
  32. package/dist/terminal.js +1 -1
  33. package/dist/workbench/index.d.ts +1 -1
  34. package/dist/workbench/styles.d.ts +1 -1
  35. package/package.json +2 -2
  36. package/packages/commands/package.json +1 -1
  37. package/packages/core/package.json +1 -1
  38. package/packages/editor/package.json +1 -1
  39. package/packages/fs/package.json +1 -1
  40. package/packages/preview/package.json +1 -1
  41. package/packages/runtime/package.json +1 -1
  42. package/packages/settings/package.json +1 -1
  43. package/packages/settings/src/builtin-schemas.ts +17 -6
  44. package/packages/settings/src/configuration-service.ts +72 -6
  45. package/packages/settings/src/index.ts +1 -0
  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/index.ts +4 -0
  50. package/packages/ui/src/plugin-registry.ts +17 -2
  51. package/packages/ui/src/settings-dialog.ts +374 -92
  52. package/packages/ui/src/themes.ts +105 -12
  53. package/src/code-lab.css +1553 -98
  54. package/src/diagnostics.ts +139 -7
  55. package/src/extensions/cpp.ts +33 -33
  56. package/src/extensions/python.ts +33 -32
  57. package/src/index.ts +1 -1
  58. package/src/schemas.ts +1 -1
  59. package/src/scm.ts +781 -58
  60. package/src/shell.ts +936 -112
  61. package/src/storage.ts +336 -3
  62. package/src/workbench/icons.ts +8 -1
  63. package/src/workbench/styles.ts +25 -19
  64. package/src/workbench.ts +12010 -3814
package/dist/shell.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
2
  * ============================================================
3
- * @innovatorved/code-lab v0.4.0 — Standalone Browser Code IDE & Virtual Runtime
3
+ * @innovatorved/code-lab v0.5.0 — Standalone Browser Code IDE & Virtual Runtime
4
4
  * ============================================================
5
5
  * Features:
6
6
  * - Sandboxed Web Worker Execution Engine with Multi-Instance Isolation & Watchdog Timer
@@ -2127,6 +2127,415 @@ var CodeLabLogger = (() => {
2127
2127
  return snap;
2128
2128
  }
2129
2129
 
2130
+ function computeGitShortHash(input) {
2131
+ const str = String(input || '');
2132
+ let h1 = 0xdeadbeef ^ str.length;
2133
+ let h2 = 0x41c6ce57 ^ str.length;
2134
+ for (let i = 0; i < str.length; i++) {
2135
+ const ch = str.charCodeAt(i);
2136
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2137
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2138
+ }
2139
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2140
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2141
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
2142
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
2143
+ }
2144
+
2145
+ function normalizeGitRelPath(rawPath, repoRoot) {
2146
+ if (!rawPath || typeof rawPath !== 'string') return '';
2147
+ let p = rawPath.trim().replace(/\\/g, '/');
2148
+ if (!p) return '';
2149
+ const cleanRoot = PosixPath.normalize(repoRoot || '/workspace');
2150
+ const prefix = cleanRoot === '/' ? '/' : cleanRoot + '/';
2151
+ if (p === cleanRoot) return '';
2152
+ if (p.startsWith(prefix)) {
2153
+ p = p.slice(prefix.length);
2154
+ } else if (p.startsWith('/workspace/')) {
2155
+ p = p.slice('/workspace/'.length);
2156
+ }
2157
+ while (p.startsWith('./')) p = p.slice(2);
2158
+ if (p.startsWith('/')) p = p.replace(/^\/+/, '');
2159
+
2160
+ const out = [];
2161
+ for (const seg of p.split('/')) {
2162
+ if (!seg || seg === '.') continue;
2163
+ if (seg === '..') {
2164
+ if (out.length === 0) return '';
2165
+ out.pop();
2166
+ continue;
2167
+ }
2168
+ out.push(seg);
2169
+ }
2170
+ const normalized = out.join('/');
2171
+ if (
2172
+ !normalized ||
2173
+ normalized === '.git' ||
2174
+ normalized.startsWith('.git/') ||
2175
+ normalized.includes('/.git/') ||
2176
+ normalized.endsWith('/.git') ||
2177
+ normalized === 'node_modules' ||
2178
+ normalized.startsWith('node_modules/') ||
2179
+ normalized.includes('/node_modules/') ||
2180
+ normalized.endsWith('/node_modules')
2181
+ ) {
2182
+ return '';
2183
+ }
2184
+ return normalized;
2185
+ }
2186
+
2187
+ function isUnbornShellHead(gitState) {
2188
+ return (
2189
+ (!Array.isArray(gitState && gitState.commits) || gitState.commits.length === 0) &&
2190
+ !(gitState && gitState.headCommit)
2191
+ );
2192
+ }
2193
+
2194
+ function isEffectiveShellStagedChange(gitState, relPath, stagedVal, resolvedHeadFiles) {
2195
+ if (!relPath) return false;
2196
+ const headFiles =
2197
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2198
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
2199
+ const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
2200
+
2201
+ if (normalizedVal === null) {
2202
+ return inHead;
2203
+ }
2204
+ if (!inHead || isUnbornShellHead(gitState)) {
2205
+ return true;
2206
+ }
2207
+ return normalizedVal !== headFiles[relPath];
2208
+ }
2209
+
2210
+ function applyShellStagedEntry(gitState, map, rawPath, rawVal, resolvedHeadFiles) {
2211
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2212
+ const rel = normalizeGitRelPath(rawPath, root);
2213
+ if (!rel) return;
2214
+ const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
2215
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
2216
+ map.set(rel, normalizedVal);
2217
+ } else {
2218
+ map.delete(rel);
2219
+ }
2220
+ }
2221
+
2222
+ function pruneShellStagedMap(gitState, map, resolvedHeadFiles) {
2223
+ if (!(map instanceof Map)) return;
2224
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2225
+ const headFiles =
2226
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2227
+ for (const [rawK, rawV] of Array.from(map.entries())) {
2228
+ const rel = normalizeGitRelPath(rawK, root);
2229
+ if (rel !== rawK) {
2230
+ map.delete(rawK);
2231
+ }
2232
+ if (!rel) {
2233
+ map.delete(rawK);
2234
+ continue;
2235
+ }
2236
+ const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
2237
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, headFiles)) {
2238
+ map.set(rel, normalizedVal);
2239
+ } else {
2240
+ map.delete(rel);
2241
+ }
2242
+ }
2243
+ }
2244
+
2245
+ function getBootSnapshotForDir(shell, initDir) {
2246
+ if (!shell || !shell._initialBootSnapshot || !shell._initialBootRoot) return {};
2247
+ const normInit = PosixPath.normalize(initDir);
2248
+ const normBoot = shell._initialBootRoot;
2249
+ if (normInit === normBoot) {
2250
+ return shell._initialBootSnapshot;
2251
+ }
2252
+ const prefix = normBoot === '/' ? '/' : normBoot + '/';
2253
+ if (normInit.startsWith(prefix)) {
2254
+ const subRel = normInit.slice(prefix.length) + '/';
2255
+ const subSnap = {};
2256
+ for (const [k, v] of Object.entries(shell._initialBootSnapshot)) {
2257
+ if (k.startsWith(subRel)) {
2258
+ subSnap[k.slice(subRel.length)] = v;
2259
+ }
2260
+ }
2261
+ return subSnap;
2262
+ }
2263
+ return {};
2264
+ }
2265
+
2266
+ function attachShellStagedMapShim(map, vfsRef, getRepoRoot, getGitState) {
2267
+ if (!(map instanceof Map)) return map;
2268
+ if (!map._hasShellStagedShim) {
2269
+ Object.defineProperty(map, '_hasShellStagedShim', {
2270
+ value: true,
2271
+ enumerable: false,
2272
+ configurable: true,
2273
+ writable: true
2274
+ });
2275
+ Object.defineProperty(map, 'add', {
2276
+ value(rawPath) {
2277
+ const gs = typeof getGitState === 'function' ? getGitState() : null;
2278
+ const root =
2279
+ typeof getRepoRoot === 'function'
2280
+ ? getRepoRoot()
2281
+ : ((gs && gs.repoRoot) || '/workspace');
2282
+ const rel = normalizeGitRelPath(rawPath, root);
2283
+ if (!rel) return map;
2284
+ let content = null;
2285
+ if (vfsRef && typeof vfsRef.existsSync === 'function') {
2286
+ const abs = PosixPath.join(root, rel);
2287
+ if (vfsRef.existsSync(abs)) {
2288
+ if (typeof vfsRef.statSync === 'function') {
2289
+ try {
2290
+ if (vfsRef.statSync(abs).isDirectory()) return map;
2291
+ } catch (err) {
2292
+ _shellLogger.debug('Failed statting staged path in VFS.', abs, err);
2293
+ }
2294
+ }
2295
+ if (typeof vfsRef.readFileSync === 'function') {
2296
+ try {
2297
+ content = String(vfsRef.readFileSync(abs, 'utf8'));
2298
+ } catch (err) {
2299
+ _shellLogger.debug('Failed reading staged file from VFS.', abs, err);
2300
+ return map;
2301
+ }
2302
+ }
2303
+ }
2304
+ }
2305
+ if (gs) {
2306
+ applyShellStagedEntry(gs, map, rel, content);
2307
+ } else {
2308
+ map.set(rel, content);
2309
+ }
2310
+ return map;
2311
+ },
2312
+ enumerable: false,
2313
+ configurable: true,
2314
+ writable: true
2315
+ });
2316
+ }
2317
+ return map;
2318
+ }
2319
+
2320
+ function ensureShellStagedMap(gitState, vfsRef, repoRoot) {
2321
+ const getRoot = () => (gitState && gitState.repoRoot) || repoRoot || '/workspace';
2322
+ const getGs = () => gitState;
2323
+ if (gitState.staged instanceof Map) {
2324
+ attachShellStagedMapShim(gitState.staged, vfsRef, getRoot, getGs);
2325
+ pruneShellStagedMap(gitState, gitState.staged);
2326
+ gitState.stagedFiles = gitState.staged;
2327
+ return gitState.staged;
2328
+ }
2329
+ const nextMap = attachShellStagedMapShim(new Map(), vfsRef, getRoot, getGs);
2330
+ if (gitState.staged && typeof gitState.staged[Symbol.iterator] === 'function') {
2331
+ for (const item of gitState.staged) {
2332
+ if (Array.isArray(item) && item.length >= 2) {
2333
+ applyShellStagedEntry(
2334
+ gitState,
2335
+ nextMap,
2336
+ item[0],
2337
+ item[1] === null ? null : String(item[1])
2338
+ );
2339
+ } else if (typeof item === 'string') {
2340
+ nextMap.add(item);
2341
+ }
2342
+ }
2343
+ }
2344
+ gitState.staged = nextMap;
2345
+ gitState.stagedFiles = nextMap;
2346
+ return nextMap;
2347
+ }
2348
+
2349
+ function parseGitHeadBranch(vfs, repoRoot) {
2350
+ if (!vfs || typeof vfs.existsSync !== 'function' || typeof vfs.readFileSync !== 'function') {
2351
+ return null;
2352
+ }
2353
+ const candidates = [
2354
+ PosixPath.join(repoRoot, '.git/HEAD'),
2355
+ '/workspace/.git/HEAD'
2356
+ ];
2357
+ for (const headFile of candidates) {
2358
+ if (vfs.existsSync(headFile)) {
2359
+ try {
2360
+ const raw = String(vfs.readFileSync(headFile, 'utf8')).trim();
2361
+ const m = /^ref:\s*refs\/heads\/([^\s]+)$/.exec(raw);
2362
+ if (m && m[1]) return m[1];
2363
+ } catch (err) {
2364
+ _shellLogger.debug('Could not parse .git/HEAD branch.', headFile, err);
2365
+ }
2366
+ }
2367
+ }
2368
+ return null;
2369
+ }
2370
+
2371
+ function createUnifiedShellGitState(vfs, cwd, options = {}) {
2372
+ const cleanCwd = PosixPath.normalize(cwd || '/workspace');
2373
+ const hasDotGit = Boolean(
2374
+ vfs &&
2375
+ typeof vfs.existsSync === 'function' &&
2376
+ (vfs.existsSync(PosixPath.join(cleanCwd, '.git')) ||
2377
+ vfs.existsSync(PosixPath.join(cleanCwd, '.git/HEAD')) ||
2378
+ vfs.existsSync('/workspace/.git') ||
2379
+ vfs.existsSync('/workspace/.git/HEAD'))
2380
+ );
2381
+
2382
+ let _initialized = Boolean(options.gitInitialized === true || hasDotGit);
2383
+ let _repoRoot = cleanCwd;
2384
+ const detectedBranch = hasDotGit ? parseGitHeadBranch(vfs, cleanCwd) : null;
2385
+ const initialBranch = detectedBranch || 'main';
2386
+
2387
+ let _headFiles = _initialized ? snapshotWorktree(vfs, cleanCwd) : {};
2388
+ let _headCommit = _initialized
2389
+ ? computeGitShortHash(JSON.stringify(_headFiles) + ':init')
2390
+ : '';
2391
+ const initTs = Date.now();
2392
+ let _commits = _initialized
2393
+ ? [
2394
+ {
2395
+ hash: _headCommit,
2396
+ author: 'CodeLab Developer <dev@codelab.internal>',
2397
+ date: new Date(initTs).toUTCString(),
2398
+ timestamp: initTs,
2399
+ message: 'Initial commit',
2400
+ files: Object.assign({}, _headFiles)
2401
+ }
2402
+ ]
2403
+ : [];
2404
+
2405
+ const gs = {
2406
+ branch: initialBranch,
2407
+ branches: new Set([initialBranch]),
2408
+ remoteUrl: null,
2409
+ remotes: {}
2410
+ };
2411
+
2412
+ let _stagedMap = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2413
+
2414
+ Object.defineProperties(gs, {
2415
+ initialized: {
2416
+ enumerable: true,
2417
+ configurable: true,
2418
+ get() {
2419
+ if (_initialized) return true;
2420
+ const root = _repoRoot || cleanCwd;
2421
+ if (
2422
+ vfs &&
2423
+ typeof vfs.existsSync === 'function' &&
2424
+ (vfs.existsSync(PosixPath.join(root, '.git')) ||
2425
+ vfs.existsSync(PosixPath.join(root, '.git/HEAD')))
2426
+ ) {
2427
+ _initialized = true;
2428
+ return true;
2429
+ }
2430
+ return false;
2431
+ },
2432
+ set(v) {
2433
+ _initialized = Boolean(v);
2434
+ }
2435
+ },
2436
+ repoRoot: {
2437
+ enumerable: true,
2438
+ configurable: true,
2439
+ get() {
2440
+ return _repoRoot;
2441
+ },
2442
+ set(v) {
2443
+ _repoRoot = PosixPath.normalize(String(v || cleanCwd));
2444
+ }
2445
+ },
2446
+ headCommit: {
2447
+ enumerable: true,
2448
+ configurable: true,
2449
+ get() {
2450
+ return _headCommit;
2451
+ },
2452
+ set(v) {
2453
+ _headCommit = String(v || '');
2454
+ }
2455
+ },
2456
+ headSnapshot: {
2457
+ enumerable: true,
2458
+ configurable: true,
2459
+ get() {
2460
+ return _headFiles;
2461
+ },
2462
+ set(v) {
2463
+ _headFiles = v && typeof v === 'object' ? v : {};
2464
+ }
2465
+ },
2466
+ headFiles: {
2467
+ enumerable: true,
2468
+ configurable: true,
2469
+ get() {
2470
+ return _headFiles;
2471
+ },
2472
+ set(v) {
2473
+ _headFiles = v && typeof v === 'object' ? v : {};
2474
+ }
2475
+ },
2476
+ staged: {
2477
+ enumerable: true,
2478
+ configurable: true,
2479
+ get() {
2480
+ return _stagedMap;
2481
+ },
2482
+ set(v) {
2483
+ if (v instanceof Map) {
2484
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2485
+ pruneShellStagedMap(gs, _stagedMap);
2486
+ } else {
2487
+ const converted = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2488
+ if (v && typeof v[Symbol.iterator] === 'function') {
2489
+ for (const item of v) {
2490
+ if (typeof item === 'string') {
2491
+ converted.add(item);
2492
+ } else if (Array.isArray(item) && item.length >= 2) {
2493
+ applyShellStagedEntry(
2494
+ gs,
2495
+ converted,
2496
+ item[0],
2497
+ item[1] === null ? null : String(item[1])
2498
+ );
2499
+ }
2500
+ }
2501
+ }
2502
+ _stagedMap = converted;
2503
+ }
2504
+ }
2505
+ },
2506
+ stagedFiles: {
2507
+ enumerable: true,
2508
+ configurable: true,
2509
+ get() {
2510
+ return _stagedMap;
2511
+ },
2512
+ set(v) {
2513
+ if (v instanceof Map) {
2514
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2515
+ pruneShellStagedMap(gs, _stagedMap);
2516
+ }
2517
+ }
2518
+ },
2519
+ commits: {
2520
+ enumerable: true,
2521
+ configurable: true,
2522
+ get() {
2523
+ return _commits;
2524
+ },
2525
+ set(v) {
2526
+ _commits = Array.isArray(v) ? v : [];
2527
+ if (_commits.length > 0 && _commits[0] && _commits[0].hash) {
2528
+ _headCommit = String(_commits[0].hash);
2529
+ } else if (_commits.length === 0) {
2530
+ _headCommit = '';
2531
+ }
2532
+ }
2533
+ }
2534
+ });
2535
+
2536
+ return gs;
2537
+ }
2538
+
2130
2539
  const BINARY_OR_HEAVY_EXT_RE = /\.(png|jpg|jpeg|gif|webp|ico|bmp|tiff|woff|woff2|ttf|eot|otf|mp3|mp4|wav|ogg|webm|avi|mov|pdf|zip|tar|gz|tgz|bz2|7z|rar|exe|dll|so|dylib|wasm|pyc|pyo|class|jar|war|ear|bin|dat|iso|dmg|pkg|deb|rpm|o|a|lib|DS_Store)$/i;
2131
2540
 
2132
2541
  function scoreRepoFilePriority(relPath) {
@@ -2387,18 +2796,23 @@ var CodeLabLogger = (() => {
2387
2796
  if (commitsRes && commitsRes.ok) {
2388
2797
  const commitsJson = await commitsRes.json();
2389
2798
  if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2390
- commits = commitsJson.map((c) => ({
2391
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2392
- author:
2393
- c.commit && c.commit.author
2394
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2395
- : `${owner} <${owner}@users.noreply.github.com>`,
2396
- date:
2397
- c.commit && c.commit.author && c.commit.author.date
2398
- ? new Date(c.commit.author.date).toUTCString()
2399
- : new Date().toUTCString(),
2400
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2401
- }));
2799
+ commits = commitsJson.map((c, idx) => {
2800
+ const msgText = c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit';
2801
+ const fallbackHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${idx}:${msgText}`);
2802
+ const ts = c.commit && c.commit.author && c.commit.author.date
2803
+ ? Date.parse(c.commit.author.date) || Date.now()
2804
+ : Date.now();
2805
+ return {
2806
+ hash: String(c.sha || fallbackHash).slice(0, 7),
2807
+ author:
2808
+ c.commit && c.commit.author
2809
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2810
+ : `${owner} <${owner}@users.noreply.github.com>`,
2811
+ date: new Date(ts).toUTCString(),
2812
+ timestamp: ts,
2813
+ message: msgText
2814
+ };
2815
+ });
2402
2816
  }
2403
2817
  }
2404
2818
  } catch (err) {
@@ -2406,11 +2820,14 @@ var CodeLabLogger = (() => {
2406
2820
  }
2407
2821
 
2408
2822
  if (commits.length === 0) {
2823
+ const cloneTs = Date.now();
2824
+ const cloneHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${filesWritten}`);
2409
2825
  commits = [
2410
2826
  {
2411
- hash: 'a1b2c3d',
2827
+ hash: cloneHash,
2412
2828
  author: `${owner} <${owner}@users.noreply.github.com>`,
2413
- date: new Date().toUTCString(),
2829
+ date: new Date(cloneTs).toUTCString(),
2830
+ timestamp: cloneTs,
2414
2831
  message: `Clone ${owner}/${repo} (${resolvedBranch})`
2415
2832
  }
2416
2833
  ];
@@ -5599,26 +6016,56 @@ var CodeLabLogger = (() => {
5599
6016
  // -----------------------------------------------------------------------
5600
6017
  async git(args, ctx) {
5601
6018
  const subcmd = args[0] || 'status';
6019
+ if (subcmd === 'version' || subcmd === '--version' || subcmd === '-v') {
6020
+ return { code: 0, stdout: 'git version 2.45.0 (CodeLab Virtual Git)\n', stderr: '' };
6021
+ }
6022
+ if (subcmd === 'help' || subcmd === '--help' || subcmd === '-h') {
6023
+ return {
6024
+ code: 0,
6025
+ stdout:
6026
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, remote, fetch, pull, log\n',
6027
+ stderr: ''
6028
+ };
6029
+ }
6030
+
5602
6031
  const gitState = ctx.shell.gitState;
5603
6032
  if (!(gitState.branches instanceof Set)) {
5604
6033
  gitState.branches = new Set(Array.isArray(gitState.branches) ? gitState.branches : [gitState.branch || 'main']);
5605
6034
  }
5606
- if (!gitState.headSnapshot) {
5607
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, gitState.repoRoot || ctx.cwd);
5608
- }
5609
6035
  if (!gitState.remotes) {
5610
6036
  gitState.remotes = gitState.remoteUrl ? { origin: gitState.remoteUrl } : {};
5611
6037
  }
5612
6038
 
5613
- const repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6039
+ let repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6040
+ const stagedMap = ensureShellStagedMap(gitState, ctx.vfs, repoRoot);
6041
+
5614
6042
  const toRepoRel = (p) => {
5615
6043
  const abs = ctx.resolvePath(p);
5616
6044
  const prefix = repoRoot === '/' ? '/' : repoRoot + '/';
5617
6045
  if (abs === repoRoot) return '.';
5618
- if (abs.startsWith(prefix)) return abs.slice(prefix.length);
5619
- return p.replace(/^\.\//, '');
6046
+ if (abs.startsWith(prefix)) return normalizeGitRelPath(abs.slice(prefix.length), repoRoot);
6047
+ return '';
5620
6048
  };
5621
6049
 
6050
+ if (subcmd !== 'init' && subcmd !== 'clone') {
6051
+ const hasDotGitInFs = Boolean(
6052
+ ctx.vfs &&
6053
+ typeof ctx.vfs.existsSync === 'function' &&
6054
+ (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git')) ||
6055
+ ctx.vfs.existsSync(PosixPath.join(ctx.cwd, '.git')))
6056
+ );
6057
+ if (!gitState.initialized && !hasDotGitInFs) {
6058
+ return {
6059
+ code: 128,
6060
+ stdout: '',
6061
+ stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
6062
+ };
6063
+ }
6064
+ if (hasDotGitInFs && !gitState.initialized) {
6065
+ gitState.initialized = true;
6066
+ }
6067
+ }
6068
+
5622
6069
  if (subcmd === 'clone') {
5623
6070
  let branchOpt = null;
5624
6071
  const positional = [];
@@ -5665,7 +6112,6 @@ var CodeLabLogger = (() => {
5665
6112
  dirDisplayName = parsed.repo;
5666
6113
  }
5667
6114
 
5668
- // Stream clone progress to the terminal as it happens (no end-of-run buffering).
5669
6115
  const canStream = typeof ctx.onStdout === 'function';
5670
6116
  const streamLine = (text) => { if (canStream && text) ctx.onStdout(text); };
5671
6117
  streamLine(`Cloning into '${dirDisplayName}'...\n`);
@@ -5699,14 +6145,18 @@ var CodeLabLogger = (() => {
5699
6145
  }
5700
6146
  });
5701
6147
 
6148
+ const clonedHead = Object.assign({}, result.headSnapshot);
6149
+ gitState.initialized = true;
5702
6150
  gitState.branch = result.branch;
5703
6151
  gitState.branches.add(result.branch);
5704
6152
  gitState.remoteUrl = result.url;
5705
6153
  gitState.remotes.origin = result.url;
5706
6154
  gitState.repoRoot = targetDir;
5707
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6155
+ gitState.headSnapshot = clonedHead;
6156
+ gitState.headFiles = clonedHead;
5708
6157
  gitState.commits = result.commits;
5709
- gitState.staged.clear();
6158
+ gitState.headCommit = (result.commits && result.commits[0] && result.commits[0].hash) || '';
6159
+ stagedMap.clear();
5710
6160
 
5711
6161
  const count = Math.max(1, result.filesWritten);
5712
6162
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
@@ -5732,62 +6182,149 @@ var CodeLabLogger = (() => {
5732
6182
  }
5733
6183
 
5734
6184
  if (subcmd === 'init') {
5735
- const initDir = args[1] && !args[1].startsWith('-') ? ctx.resolvePath(args[1]) : ctx.cwd;
6185
+ let initBranch = gitState.branch || 'main';
6186
+ let emptyHead = false;
6187
+ let dirArg = null;
6188
+ for (let i = 1; i < args.length; i++) {
6189
+ const a = args[i];
6190
+ if ((a === '-b' || a === '--initial-branch') && i + 1 < args.length) {
6191
+ initBranch = args[++i];
6192
+ } else if (a.startsWith('--initial-branch=')) {
6193
+ initBranch = a.slice('--initial-branch='.length) || initBranch;
6194
+ } else if (a === '--empty-head') {
6195
+ emptyHead = true;
6196
+ } else if (!a.startsWith('-') && !dirArg) {
6197
+ dirArg = a;
6198
+ }
6199
+ }
6200
+ const initDir = PosixPath.normalize(dirArg ? ctx.resolvePath(dirArg) : ctx.cwd);
5736
6201
  const gitDir = PosixPath.join(initDir, '.git');
6202
+ const wasReinitSameDir =
6203
+ Boolean(gitState.initialized) &&
6204
+ PosixPath.normalize(gitState.repoRoot || ctx.cwd) === initDir &&
6205
+ !emptyHead;
5737
6206
  ensureDirSync(ctx.vfs, gitDir, ctx.emitMutation);
5738
- const branchName = gitState.branch || 'main';
5739
- ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${branchName}\n`);
6207
+ if (!wasReinitSameDir || !ctx.vfs.existsSync(PosixPath.join(gitDir, 'HEAD'))) {
6208
+ ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${initBranch}\n`);
6209
+ }
5740
6210
  ctx.vfs.writeFileSync(
5741
6211
  PosixPath.join(gitDir, 'config'),
5742
6212
  `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
5743
6213
  );
5744
6214
  ctx.emitMutation('create', PosixPath.join(gitDir, 'HEAD'));
6215
+
6216
+ if (wasReinitSameDir && !isUnbornShellHead(gitState)) {
6217
+ gitState.branches.add(gitState.branch || initBranch);
6218
+ return {
6219
+ code: 0,
6220
+ stdout: `Reinitialized existing Git repository in ${gitDir}/\n`,
6221
+ stderr: ''
6222
+ };
6223
+ }
6224
+
6225
+ const initSnap = {};
6226
+ if (!emptyHead) {
6227
+ const currentLive = snapshotWorktree(ctx.vfs, initDir);
6228
+ const bootSnap = getBootSnapshotForDir(ctx.shell, initDir);
6229
+ for (const [rel, content] of Object.entries(currentLive)) {
6230
+ if (Object.prototype.hasOwnProperty.call(bootSnap, rel) && bootSnap[rel] === content) {
6231
+ initSnap[rel] = content;
6232
+ }
6233
+ }
6234
+ }
6235
+ gitState.initialized = true;
6236
+ gitState.branch = initBranch;
6237
+ gitState.branches.add(initBranch);
5745
6238
  gitState.repoRoot = initDir;
5746
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, initDir);
5747
- gitState.staged.clear();
5748
- return { code: 0, stdout: `Initialized empty Git repository in ${gitDir}/\n`, stderr: '' };
6239
+ gitState.headSnapshot = initSnap;
6240
+ gitState.headFiles = initSnap;
6241
+ gitState.commits = [];
6242
+ gitState.headCommit = '';
6243
+ stagedMap.clear();
6244
+ return {
6245
+ code: 0,
6246
+ stdout: `${wasReinitSameDir ? 'Reinitialized existing' : 'Initialized empty'} Git repository in ${gitDir}/\n`,
6247
+ stderr: ''
6248
+ };
5749
6249
  }
5750
6250
 
6251
+ repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6252
+
5751
6253
  if (subcmd === 'status') {
5752
- const isShort = args.includes('-s') || args.includes('--short');
6254
+ const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
5753
6255
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5754
- const headFiles = gitState.headSnapshot || {};
6256
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6257
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6258
+ const unbornHead = isUnbornShellHead(gitState);
5755
6259
 
5756
6260
  const stagedList = [];
5757
- for (const relPath of gitState.staged) {
6261
+ const unstagedList = [];
6262
+ const untrackedList = [];
6263
+ const stagedKeysSorted = Array.from(stagedMap.keys()).sort();
6264
+
6265
+ for (const relPath of stagedKeysSorted) {
6266
+ const stagedVal = stagedMap.get(relPath);
5758
6267
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5759
6268
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, relPath);
5760
- if (!inHead && inLive) {
5761
- stagedList.push({ status: 'new file', short: 'A ', path: relPath });
5762
- } else if (inHead && !inLive) {
5763
- stagedList.push({ status: 'deleted', short: 'D ', path: relPath });
6269
+
6270
+ if (stagedVal === null) {
6271
+ if (inHead) {
6272
+ stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6273
+ }
6274
+ if (inLive) {
6275
+ untrackedList.push(relPath);
6276
+ }
5764
6277
  } else {
5765
- stagedList.push({ status: 'modified', short: 'M ', path: relPath });
6278
+ if (!inHead || unbornHead) {
6279
+ stagedList.push({ status: 'new file', code: 'A', path: relPath });
6280
+ } else if (stagedVal !== headFiles[relPath]) {
6281
+ stagedList.push({ status: 'modified', code: 'M', path: relPath });
6282
+ }
6283
+
6284
+ if (!inLive) {
6285
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
6286
+ } else if (liveFiles[relPath] !== stagedVal) {
6287
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
6288
+ }
5766
6289
  }
5767
6290
  }
5768
6291
 
5769
- const unstagedList = [];
5770
6292
  for (const relPath of Object.keys(headFiles).sort()) {
5771
- if (gitState.staged.has(relPath)) continue;
6293
+ if (stagedMap.has(relPath)) continue;
5772
6294
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5773
- unstagedList.push({ status: 'deleted', short: ' D', path: relPath });
6295
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
5774
6296
  } else if (liveFiles[relPath] !== headFiles[relPath]) {
5775
- unstagedList.push({ status: 'modified', short: ' M', path: relPath });
6297
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
5776
6298
  }
5777
6299
  }
5778
6300
 
5779
- const untrackedList = [];
5780
6301
  for (const relPath of Object.keys(liveFiles).sort()) {
5781
- if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
6302
+ if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
5782
6303
  untrackedList.push(relPath);
5783
6304
  }
5784
6305
  }
5785
6306
 
6307
+ unstagedList.sort((a, b) => a.path.localeCompare(b.path));
6308
+ untrackedList.sort();
6309
+
5786
6310
  if (isShort) {
6311
+ const shortByPath = new Map();
6312
+ for (const item of stagedList) {
6313
+ shortByPath.set(item.path, { idx: item.code, wt: ' ' });
6314
+ }
6315
+ for (const item of unstagedList) {
6316
+ const prev = shortByPath.get(item.path);
6317
+ if (prev) prev.wt = item.code;
6318
+ else shortByPath.set(item.path, { idx: ' ', wt: item.code });
6319
+ }
5787
6320
  let sOut = '';
5788
- for (const item of stagedList) sOut += `${item.short} ${item.path}\n`;
5789
- for (const item of unstagedList) sOut += `${item.short} ${item.path}\n`;
5790
- for (const p of untrackedList) sOut += `?? ${p}\n`;
6321
+ for (const p of Array.from(shortByPath.keys()).sort()) {
6322
+ const pair = shortByPath.get(p);
6323
+ sOut += `${pair.idx}${pair.wt} ${p}\n`;
6324
+ }
6325
+ for (const p of untrackedList) {
6326
+ sOut += `?? ${p}\n`;
6327
+ }
5791
6328
  return { code: 0, stdout: sOut, stderr: '' };
5792
6329
  }
5793
6330
 
@@ -5824,24 +6361,43 @@ var CodeLabLogger = (() => {
5824
6361
 
5825
6362
  if (subcmd === 'diff') {
5826
6363
  const isStaged = args.includes('--staged') || args.includes('--cached');
5827
- const fileFilters = args.slice(1).filter((a) => !a.startsWith('-')).map(toRepoRel);
6364
+ const rawFilterArgs = args.slice(1).filter((a) => !a.startsWith('-'));
6365
+ const fileFilters = rawFilterArgs.map(toRepoRel);
6366
+ const matchAllInRepo = fileFilters.length === 0 || fileFilters.includes('.');
5828
6367
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5829
- const headFiles = gitState.headSnapshot || {};
5830
- const allKeys = Array.from(new Set([...Object.keys(headFiles), ...Object.keys(liveFiles)])).sort();
6368
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6369
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6370
+ const unbornHead = isUnbornShellHead(gitState);
6371
+ const allKeys = Array.from(
6372
+ new Set([...Object.keys(headFiles), ...Object.keys(liveFiles), ...Array.from(stagedMap.keys())])
6373
+ ).sort();
5831
6374
 
5832
6375
  let stdout = '';
5833
6376
  for (const relPath of allKeys) {
5834
- if (fileFilters.length > 0 && !fileFilters.includes(relPath)) continue;
5835
- if (isStaged && !gitState.staged.has(relPath)) continue;
5836
- if (!isStaged && !Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5837
- continue;
5838
- }
5839
- const oldText = Object.prototype.hasOwnProperty.call(headFiles, relPath) ? headFiles[relPath] : '';
5840
- const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
5841
- if (oldText !== newText) {
5842
- const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
5843
- if (uDiff) {
5844
- stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6377
+ if (!matchAllInRepo && !fileFilters.includes(relPath)) continue;
6378
+ if (isStaged) {
6379
+ if (!stagedMap.has(relPath)) continue;
6380
+ const stagedVal = stagedMap.get(relPath);
6381
+ if (!isEffectiveShellStagedChange(gitState, relPath, stagedVal, headFiles)) continue;
6382
+ const oldText =
6383
+ !unbornHead && Object.prototype.hasOwnProperty.call(headFiles, relPath)
6384
+ ? headFiles[relPath]
6385
+ : '';
6386
+ const newText = stagedVal === null ? '' : String(stagedVal);
6387
+ if (oldText !== newText) {
6388
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6389
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6390
+ }
6391
+ } else {
6392
+ const isTrackedOrStaged =
6393
+ Object.prototype.hasOwnProperty.call(headFiles, relPath) || stagedMap.has(relPath);
6394
+ if (!isTrackedOrStaged) continue;
6395
+ const baseVal = stagedMap.has(relPath) ? stagedMap.get(relPath) : headFiles[relPath];
6396
+ const oldText = baseVal === null || baseVal === undefined ? '' : String(baseVal);
6397
+ const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
6398
+ if (oldText !== newText) {
6399
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6400
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
5845
6401
  }
5846
6402
  }
5847
6403
  }
@@ -5851,38 +6407,76 @@ var CodeLabLogger = (() => {
5851
6407
  if (subcmd === 'add') {
5852
6408
  const targets = args.slice(1);
5853
6409
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5854
- const headFiles = gitState.headSnapshot || {};
6410
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6411
+
6412
+ const stagePath = (relPath) => {
6413
+ const clean = normalizeGitRelPath(relPath, repoRoot);
6414
+ if (!clean) return;
6415
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6416
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6417
+ if (inLive) {
6418
+ applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6419
+ } else if (inHead) {
6420
+ applyShellStagedEntry(gitState, stagedMap, clean, null, headFiles);
6421
+ } else {
6422
+ stagedMap.delete(clean);
6423
+ }
6424
+ };
5855
6425
 
5856
6426
  if (targets.includes('.') || targets.includes('-A') || targets.includes('--all') || targets.includes('-u')) {
5857
6427
  const includeUntracked = !targets.includes('-u');
5858
6428
  for (const relPath of Object.keys(liveFiles)) {
5859
6429
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5860
6430
  if (!inHead && includeUntracked) {
5861
- gitState.staged.add(relPath);
5862
- } else if (inHead && liveFiles[relPath] !== headFiles[relPath]) {
5863
- gitState.staged.add(relPath);
6431
+ stagePath(relPath);
6432
+ } else if (inHead) {
6433
+ stagePath(relPath);
5864
6434
  }
5865
6435
  }
5866
6436
  for (const relPath of Object.keys(headFiles)) {
5867
6437
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5868
- gitState.staged.add(relPath);
6438
+ stagePath(relPath);
6439
+ }
6440
+ }
6441
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6442
+ if (
6443
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6444
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6445
+ ) {
6446
+ stagedMap.delete(stagedKey);
5869
6447
  }
5870
6448
  }
5871
6449
  } else {
5872
6450
  for (const f of targets) {
5873
6451
  if (f.startsWith('-')) continue;
5874
6452
  const rel = toRepoRel(f);
6453
+ if (!rel) continue;
5875
6454
  if (rel === '.') {
5876
- for (const k of Object.keys(liveFiles)) {
5877
- if (liveFiles[k] !== headFiles[k]) gitState.staged.add(k);
6455
+ for (const k of Object.keys(liveFiles)) stagePath(k);
6456
+ for (const k of Object.keys(headFiles)) {
6457
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k);
6458
+ }
6459
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6460
+ if (
6461
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6462
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6463
+ ) {
6464
+ stagedMap.delete(stagedKey);
6465
+ }
5878
6466
  }
5879
6467
  } else {
5880
6468
  const dirPrefix = rel.replace(/\/+$/, '') + '/';
5881
- const matchedSubfiles = Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix));
6469
+ const matchedSubfiles = Array.from(
6470
+ new Set([
6471
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6472
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6473
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6474
+ ])
6475
+ );
5882
6476
  if (matchedSubfiles.length > 0) {
5883
- for (const k of matchedSubfiles) gitState.staged.add(k);
6477
+ for (const k of matchedSubfiles) stagePath(k);
5884
6478
  } else {
5885
- gitState.staged.add(rel);
6479
+ stagePath(rel);
5886
6480
  }
5887
6481
  }
5888
6482
  }
@@ -5892,37 +6486,72 @@ var CodeLabLogger = (() => {
5892
6486
 
5893
6487
  if (subcmd === 'commit') {
5894
6488
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5895
- const headFiles = gitState.headSnapshot || {};
5896
- if (args.includes('-a') || args.includes('-am')) {
6489
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6490
+ const autoStageTracked = args.some(
6491
+ (a) =>
6492
+ a === '-a' ||
6493
+ a === '--all' ||
6494
+ (a.startsWith('-') && !a.startsWith('--') && a !== '-m' && a.includes('a'))
6495
+ );
6496
+ if (autoStageTracked) {
5897
6497
  for (const relPath of Object.keys(headFiles)) {
5898
- if (liveFiles[relPath] !== headFiles[relPath]) {
5899
- gitState.staged.add(relPath);
6498
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6499
+ applyShellStagedEntry(gitState, stagedMap, relPath, null, headFiles);
6500
+ } else {
6501
+ applyShellStagedEntry(gitState, stagedMap, relPath, liveFiles[relPath], headFiles);
5900
6502
  }
5901
6503
  }
5902
6504
  }
5903
6505
 
6506
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6507
+
6508
+ if (stagedMap.size === 0) {
6509
+ return {
6510
+ code: 1,
6511
+ stdout: `On branch ${gitState.branch}\nnothing to commit, working tree clean\n`,
6512
+ stderr: ''
6513
+ };
6514
+ }
6515
+
5904
6516
  let msg = 'Commit changes';
5905
- const mIdx = args.findIndex((a) => a === '-m' || a === '-am');
6517
+ const mIdx = args.findIndex(
6518
+ (a) => a === '-m' || a === '-am' || a === '-ma'
6519
+ );
5906
6520
  if (mIdx !== -1 && mIdx + 1 < args.length) msg = args[mIdx + 1];
5907
6521
 
5908
- for (const relPath of gitState.staged) {
5909
- if (Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5910
- gitState.headSnapshot[relPath] = liveFiles[relPath];
6522
+ const nextHead = Object.assign({}, headFiles);
6523
+ const summaryParts = [];
6524
+ for (const [relPath, stagedVal] of stagedMap.entries()) {
6525
+ summaryParts.push(`${relPath}:${stagedVal === null ? '<DEL>' : stagedVal}`);
6526
+ if (stagedVal === null) {
6527
+ delete nextHead[relPath];
5911
6528
  } else {
5912
- delete gitState.headSnapshot[relPath];
6529
+ nextHead[relPath] = String(stagedVal);
5913
6530
  }
5914
6531
  }
5915
6532
 
5916
- const hash = Math.random().toString(16).slice(2, 9);
6533
+ const commitTs = Date.now();
6534
+ const hash = computeGitShortHash(
6535
+ `${gitState.headCommit || ''}:${msg}:${commitTs}:${gitState.commits.length}:${summaryParts.join('|')}`
6536
+ );
6537
+ const count = stagedMap.size;
6538
+ gitState.headSnapshot = nextHead;
6539
+ gitState.headFiles = nextHead;
5917
6540
  gitState.commits.unshift({
5918
6541
  hash,
5919
- author: `${ctx.env.USER || 'codelab'} <dev@codelab.internal>`,
5920
- date: new Date().toUTCString(),
5921
- message: msg
6542
+ author: `${ctx.env.USER || 'CodeLab Developer'} <dev@codelab.internal>`,
6543
+ date: new Date(commitTs).toUTCString(),
6544
+ timestamp: commitTs,
6545
+ message: msg,
6546
+ files: Object.assign({}, nextHead)
5922
6547
  });
5923
- const count = gitState.staged.size || 1;
5924
- gitState.staged.clear();
5925
- return { code: 0, stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file changed\n`, stderr: '' };
6548
+ gitState.headCommit = hash;
6549
+ stagedMap.clear();
6550
+ return {
6551
+ code: 0,
6552
+ stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
6553
+ stderr: ''
6554
+ };
5926
6555
  }
5927
6556
 
5928
6557
  if (subcmd === 'branch') {
@@ -5982,9 +6611,11 @@ var CodeLabLogger = (() => {
5982
6611
  }
5983
6612
 
5984
6613
  const rel = toRepoRel(target);
5985
- if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6614
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6615
+ if (rel && Object.prototype.hasOwnProperty.call(headFiles, rel)) {
5986
6616
  const abs = PosixPath.join(repoRoot, rel);
5987
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6617
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6618
+ ctx.vfs.writeFileSync(abs, headFiles[rel]);
5988
6619
  ctx.emitMutation('change', abs);
5989
6620
  return { code: 0, stdout: `Updated 1 path from the index\n`, stderr: '' };
5990
6621
  }
@@ -5994,20 +6625,199 @@ var CodeLabLogger = (() => {
5994
6625
 
5995
6626
  if (subcmd === 'restore') {
5996
6627
  const isStaged = args.includes('--staged') || args.includes('-S');
5997
- const targets = args.slice(1).filter((a) => !a.startsWith('-'));
6628
+ const isWorktree = args.includes('--worktree') || args.includes('-W') || !isStaged;
6629
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6630
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
5998
6631
  for (const t of targets) {
5999
6632
  const rel = toRepoRel(t);
6633
+ if (!rel) continue;
6000
6634
  if (isStaged) {
6001
- gitState.staged.delete(rel);
6002
- } else if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6635
+ if (rel === '.') {
6636
+ stagedMap.clear();
6637
+ } else {
6638
+ const cleanRel = rel.replace(/\/+$/, '');
6639
+ const dirPrefix = cleanRel + '/';
6640
+ stagedMap.delete(cleanRel);
6641
+ for (const k of Array.from(stagedMap.keys())) {
6642
+ if (k.startsWith(dirPrefix)) {
6643
+ stagedMap.delete(k);
6644
+ }
6645
+ }
6646
+ }
6647
+ }
6648
+ if (isWorktree) {
6649
+ if (rel === '.') {
6650
+ for (const [k, v] of Object.entries(headFiles)) {
6651
+ const abs = PosixPath.join(repoRoot, k);
6652
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6653
+ ctx.vfs.writeFileSync(abs, v);
6654
+ ctx.emitMutation('change', abs);
6655
+ }
6656
+ } else {
6657
+ const cleanRel = rel.replace(/\/+$/, '');
6658
+ const dirPrefix = cleanRel + '/';
6659
+ const subHeadKeys = Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix));
6660
+ if (subHeadKeys.length > 0 && !Object.prototype.hasOwnProperty.call(headFiles, cleanRel)) {
6661
+ for (const k of subHeadKeys) {
6662
+ const sourceText =
6663
+ !isStaged && stagedMap.has(k) && stagedMap.get(k) !== null
6664
+ ? stagedMap.get(k)
6665
+ : headFiles[k];
6666
+ const abs = PosixPath.join(repoRoot, k);
6667
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6668
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6669
+ ctx.emitMutation('change', abs);
6670
+ }
6671
+ } else {
6672
+ const sourceText =
6673
+ !isStaged && stagedMap.has(cleanRel) && stagedMap.get(cleanRel) !== null
6674
+ ? stagedMap.get(cleanRel)
6675
+ : (Object.prototype.hasOwnProperty.call(headFiles, cleanRel) ? headFiles[cleanRel] : undefined);
6676
+ if (sourceText !== undefined) {
6677
+ const abs = PosixPath.join(repoRoot, cleanRel);
6678
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6679
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6680
+ ctx.emitMutation('change', abs);
6681
+ }
6682
+ }
6683
+ }
6684
+ }
6685
+ }
6686
+ return { code: 0, stdout: '', stderr: '' };
6687
+ }
6688
+
6689
+ if (subcmd === 'reset') {
6690
+ const isHard = args.includes('--hard');
6691
+ const fileArgs = args.slice(1).filter((a) => !a.startsWith('-') && a !== 'HEAD' && a !== '--');
6692
+ if (fileArgs.length > 0) {
6693
+ for (const f of fileArgs) {
6694
+ const rel = toRepoRel(f);
6695
+ if (!rel) continue;
6696
+ if (rel === '.') {
6697
+ stagedMap.clear();
6698
+ } else {
6699
+ const cleanRel = rel.replace(/\/+$/, '');
6700
+ const dirPrefix = cleanRel + '/';
6701
+ stagedMap.delete(cleanRel);
6702
+ for (const k of Array.from(stagedMap.keys())) {
6703
+ if (k.startsWith(dirPrefix)) {
6704
+ stagedMap.delete(k);
6705
+ }
6706
+ }
6707
+ }
6708
+ }
6709
+ return { code: 0, stdout: '', stderr: '' };
6710
+ }
6711
+ stagedMap.clear();
6712
+ if (isHard) {
6713
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6714
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6715
+ for (const rel of Object.keys(liveFiles)) {
6716
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6717
+ const abs = PosixPath.join(repoRoot, rel);
6718
+ if (typeof ctx.vfs.rmSync === 'function') {
6719
+ ctx.vfs.rmSync(abs, { force: true });
6720
+ } else if (typeof ctx.vfs.unlinkSync === 'function' && ctx.vfs.existsSync(abs)) {
6721
+ ctx.vfs.unlinkSync(abs);
6722
+ }
6723
+ ctx.emitMutation('delete', abs);
6724
+ }
6725
+ }
6726
+ for (const [rel, text] of Object.entries(headFiles)) {
6003
6727
  const abs = PosixPath.join(repoRoot, rel);
6004
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6728
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6729
+ ctx.vfs.writeFileSync(abs, text);
6005
6730
  ctx.emitMutation('change', abs);
6006
6731
  }
6007
6732
  }
6008
6733
  return { code: 0, stdout: '', stderr: '' };
6009
6734
  }
6010
6735
 
6736
+ if (subcmd === 'rm') {
6737
+ const cachedOnly = args.includes('--cached');
6738
+ const isRecursive = args.some((a) => a === '-r' || a === '-rf' || a === '-fr');
6739
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6740
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6741
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6742
+
6743
+ if (targets.length === 0) {
6744
+ return { code: 128, stdout: '', stderr: 'usage: git rm [--cached] [-r] [-f] <file>...\n' };
6745
+ }
6746
+
6747
+ const removeSingleRel = (rel) => {
6748
+ if (!rel) return;
6749
+ const abs = PosixPath.join(repoRoot, rel);
6750
+ if (!cachedOnly && ctx.vfs.existsSync(abs)) {
6751
+ if (typeof ctx.vfs.rmSync === 'function') {
6752
+ ctx.vfs.rmSync(abs, { force: true, recursive: isRecursive });
6753
+ } else if (typeof ctx.vfs.unlinkSync === 'function') {
6754
+ ctx.vfs.unlinkSync(abs);
6755
+ }
6756
+ ctx.emitMutation('delete', abs);
6757
+ }
6758
+ if (Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6759
+ stagedMap.set(rel, null);
6760
+ } else {
6761
+ stagedMap.delete(rel);
6762
+ }
6763
+ };
6764
+
6765
+ for (const t of targets) {
6766
+ const rel = toRepoRel(t);
6767
+ if (!rel) continue;
6768
+ if (rel === '.') {
6769
+ if (isRecursive) {
6770
+ const allRel = Array.from(
6771
+ new Set([
6772
+ ...Object.keys(headFiles),
6773
+ ...Object.keys(liveFiles),
6774
+ ...Array.from(stagedMap.keys())
6775
+ ])
6776
+ );
6777
+ for (const sub of allRel) removeSingleRel(sub);
6778
+ }
6779
+ continue;
6780
+ }
6781
+ const dirPrefix = rel.replace(/\/+$/, '') + '/';
6782
+ const subMatches = isRecursive
6783
+ ? Array.from(
6784
+ new Set([
6785
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6786
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6787
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6788
+ ])
6789
+ )
6790
+ : [];
6791
+ if (subMatches.length > 0) {
6792
+ for (const sub of subMatches) removeSingleRel(sub);
6793
+ if (!cachedOnly) removeDirRecursive(ctx.vfs, PosixPath.join(repoRoot, rel), ctx.emitMutation);
6794
+ } else {
6795
+ const abs = PosixPath.join(repoRoot, rel);
6796
+ if (
6797
+ !isRecursive &&
6798
+ ctx.vfs &&
6799
+ typeof ctx.vfs.existsSync === 'function' &&
6800
+ ctx.vfs.existsSync(abs) &&
6801
+ typeof ctx.vfs.statSync === 'function'
6802
+ ) {
6803
+ try {
6804
+ if (ctx.vfs.statSync(abs).isDirectory()) {
6805
+ return {
6806
+ code: 128,
6807
+ stdout: '',
6808
+ stderr: `fatal: not removing '${t}' recursively without -r\n`
6809
+ };
6810
+ }
6811
+ } catch (err) {
6812
+ _shellLogger.debug('Failed statting path in git rm.', abs, err);
6813
+ }
6814
+ }
6815
+ removeSingleRel(rel);
6816
+ }
6817
+ }
6818
+ return { code: 0, stdout: '', stderr: '' };
6819
+ }
6820
+
6011
6821
  if (subcmd === 'remote') {
6012
6822
  const sub = args[1];
6013
6823
  if (!sub) {
@@ -6055,7 +6865,9 @@ var CodeLabLogger = (() => {
6055
6865
  signal: ctx.signal,
6056
6866
  onFile: (absPath) => ctx.emitMutation('change', absPath)
6057
6867
  });
6058
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6868
+ const pulledHead = Object.assign({}, result.headSnapshot);
6869
+ gitState.headSnapshot = pulledHead;
6870
+ gitState.headFiles = pulledHead;
6059
6871
  return {
6060
6872
  code: 0,
6061
6873
  stdout: `From ${remoteUrl.replace(/\.git$/, '')}\n * branch ${result.branch} -> FETCH_HEAD\nAlready up to date.\n`,
@@ -6082,9 +6894,11 @@ var CodeLabLogger = (() => {
6082
6894
  if (oneline) {
6083
6895
  stdout += `${c.hash} ${c.message}\n`;
6084
6896
  } else {
6897
+ const authorStr = c.author || 'CodeLab Developer <dev@codelab.internal>';
6898
+ const dateStr = c.date || (c.timestamp ? new Date(c.timestamp).toUTCString() : new Date(0).toUTCString());
6085
6899
  stdout += `commit ${c.hash}\n`;
6086
- stdout += `Author: ${c.author}\n`;
6087
- stdout += `Date: ${c.date}\n\n`;
6900
+ stdout += `Author: ${authorStr}\n`;
6901
+ stdout += `Date: ${dateStr}\n\n`;
6088
6902
  stdout += ` ${c.message}\n\n`;
6089
6903
  }
6090
6904
  }
@@ -7901,6 +8715,16 @@ var CodeLabLogger = (() => {
7901
8715
  if (options.files && typeof options.files === 'object') {
7902
8716
  for (const [k, v] of Object.entries(options.files)) {
7903
8717
  const abs = PosixPath.resolve(this.cwd, k);
8718
+ if (typeof this.vfs.mkdirSync === 'function') {
8719
+ const parentDir = PosixPath.dirname(abs);
8720
+ if (
8721
+ parentDir &&
8722
+ parentDir !== '/' &&
8723
+ (typeof this.vfs.existsSync !== 'function' || !this.vfs.existsSync(parentDir))
8724
+ ) {
8725
+ this.vfs.mkdirSync(parentDir, { recursive: true });
8726
+ }
8727
+ }
7904
8728
  if (typeof this.vfs.writeFileSync === 'function') {
7905
8729
  this.vfs.writeFileSync(abs, String(v ?? ''));
7906
8730
  }
@@ -7912,23 +8736,19 @@ var CodeLabLogger = (() => {
7912
8736
  this.nextPid = 100;
7913
8737
  this.commands = Object.assign({}, COREUTILS, options.commands || {});
7914
8738
 
7915
- this.gitState = {
7916
- branch: 'main',
7917
- branches: new Set(['main']),
7918
- remoteUrl: null,
7919
- remotes: {},
7920
- repoRoot: this.cwd,
7921
- headSnapshot: snapshotWorktree(this.vfs, this.cwd),
7922
- staged: new Set(),
7923
- commits: [
7924
- {
7925
- hash: 'a1b2c3d',
7926
- author: 'CodeLab Developer <dev@codelab.internal>',
7927
- date: new Date().toUTCString(),
7928
- message: 'Initial project commit'
7929
- }
7930
- ]
7931
- };
8739
+ this._initialBootRoot = options._initialBootRoot
8740
+ ? PosixPath.normalize(options._initialBootRoot)
8741
+ : PosixPath.normalize(this.cwd || '/workspace');
8742
+ this._initialBootSnapshot =
8743
+ options._initialBootSnapshot && typeof options._initialBootSnapshot === 'object'
8744
+ ? options._initialBootSnapshot
8745
+ : snapshotWorktree(this.vfs, this._initialBootRoot);
8746
+
8747
+ if (options.gitState && typeof options.gitState === 'object') {
8748
+ this.gitState = options.gitState;
8749
+ } else {
8750
+ this.gitState = createUnifiedShellGitState(this.vfs, this.cwd, options);
8751
+ }
7932
8752
  }
7933
8753
 
7934
8754
  resolvePath(p) {
@@ -8057,6 +8877,9 @@ var CodeLabLogger = (() => {
8057
8877
  ...this.options,
8058
8878
  vfs: this.vfs,
8059
8879
  portTable: this.portTable,
8880
+ gitState: this.gitState,
8881
+ _initialBootRoot: this._initialBootRoot,
8882
+ _initialBootSnapshot: this._initialBootSnapshot,
8060
8883
  env: { ...env, PWD: this.cwd }
8061
8884
  });
8062
8885
  subShell.cwd = this.cwd;
@@ -8778,6 +9601,7 @@ var CodeLabLogger = (() => {
8778
9601
  ...this.options,
8779
9602
  vfs: this.vfs,
8780
9603
  portTable: this.portTable,
9604
+ gitState: this.gitState,
8781
9605
  env: Object.assign({}, this.env, innerCtx.env || {})
8782
9606
  });
8783
9607
  subShell.cwd = innerCtx.cwd || this.cwd;