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