@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/src/shell.ts CHANGED
@@ -2006,6 +2006,415 @@
2006
2006
  return snap;
2007
2007
  }
2008
2008
 
2009
+ function computeGitShortHash(input) {
2010
+ const str = String(input || '');
2011
+ let h1 = 0xdeadbeef ^ str.length;
2012
+ let h2 = 0x41c6ce57 ^ str.length;
2013
+ for (let i = 0; i < str.length; i++) {
2014
+ const ch = str.charCodeAt(i);
2015
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2016
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2017
+ }
2018
+ h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909);
2019
+ h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909);
2020
+ const combined = 4294967296 * (2097151 & h2) + (h1 >>> 0);
2021
+ return combined.toString(16).padStart(7, '0').slice(0, 7);
2022
+ }
2023
+
2024
+ function normalizeGitRelPath(rawPath, repoRoot) {
2025
+ if (!rawPath || typeof rawPath !== 'string') return '';
2026
+ let p = rawPath.trim().replace(/\\/g, '/');
2027
+ if (!p) return '';
2028
+ const cleanRoot = PosixPath.normalize(repoRoot || '/workspace');
2029
+ const prefix = cleanRoot === '/' ? '/' : cleanRoot + '/';
2030
+ if (p === cleanRoot) return '';
2031
+ if (p.startsWith(prefix)) {
2032
+ p = p.slice(prefix.length);
2033
+ } else if (p.startsWith('/workspace/')) {
2034
+ p = p.slice('/workspace/'.length);
2035
+ }
2036
+ while (p.startsWith('./')) p = p.slice(2);
2037
+ if (p.startsWith('/')) p = p.replace(/^\/+/, '');
2038
+
2039
+ const out = [];
2040
+ for (const seg of p.split('/')) {
2041
+ if (!seg || seg === '.') continue;
2042
+ if (seg === '..') {
2043
+ if (out.length === 0) return '';
2044
+ out.pop();
2045
+ continue;
2046
+ }
2047
+ out.push(seg);
2048
+ }
2049
+ const normalized = out.join('/');
2050
+ if (
2051
+ !normalized ||
2052
+ normalized === '.git' ||
2053
+ normalized.startsWith('.git/') ||
2054
+ normalized.includes('/.git/') ||
2055
+ normalized.endsWith('/.git') ||
2056
+ normalized === 'node_modules' ||
2057
+ normalized.startsWith('node_modules/') ||
2058
+ normalized.includes('/node_modules/') ||
2059
+ normalized.endsWith('/node_modules')
2060
+ ) {
2061
+ return '';
2062
+ }
2063
+ return normalized;
2064
+ }
2065
+
2066
+ function isUnbornShellHead(gitState) {
2067
+ return (
2068
+ (!Array.isArray(gitState && gitState.commits) || gitState.commits.length === 0) &&
2069
+ !(gitState && gitState.headCommit)
2070
+ );
2071
+ }
2072
+
2073
+ function isEffectiveShellStagedChange(gitState, relPath, stagedVal, resolvedHeadFiles) {
2074
+ if (!relPath) return false;
2075
+ const headFiles =
2076
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2077
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
2078
+ const normalizedVal = stagedVal === undefined || stagedVal === null ? null : String(stagedVal);
2079
+
2080
+ if (normalizedVal === null) {
2081
+ return inHead;
2082
+ }
2083
+ if (!inHead || isUnbornShellHead(gitState)) {
2084
+ return true;
2085
+ }
2086
+ return normalizedVal !== headFiles[relPath];
2087
+ }
2088
+
2089
+ function applyShellStagedEntry(gitState, map, rawPath, rawVal, resolvedHeadFiles) {
2090
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2091
+ const rel = normalizeGitRelPath(rawPath, root);
2092
+ if (!rel) return;
2093
+ const normalizedVal = rawVal === undefined || rawVal === null ? null : String(rawVal);
2094
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, resolvedHeadFiles)) {
2095
+ map.set(rel, normalizedVal);
2096
+ } else {
2097
+ map.delete(rel);
2098
+ }
2099
+ }
2100
+
2101
+ function pruneShellStagedMap(gitState, map, resolvedHeadFiles) {
2102
+ if (!(map instanceof Map)) return;
2103
+ const root = (gitState && gitState.repoRoot) || '/workspace';
2104
+ const headFiles =
2105
+ resolvedHeadFiles || (gitState && (gitState.headSnapshot || gitState.headFiles)) || {};
2106
+ for (const [rawK, rawV] of Array.from(map.entries())) {
2107
+ const rel = normalizeGitRelPath(rawK, root);
2108
+ if (rel !== rawK) {
2109
+ map.delete(rawK);
2110
+ }
2111
+ if (!rel) {
2112
+ map.delete(rawK);
2113
+ continue;
2114
+ }
2115
+ const normalizedVal = rawV === undefined || rawV === null ? null : String(rawV);
2116
+ if (isEffectiveShellStagedChange(gitState, rel, normalizedVal, headFiles)) {
2117
+ map.set(rel, normalizedVal);
2118
+ } else {
2119
+ map.delete(rel);
2120
+ }
2121
+ }
2122
+ }
2123
+
2124
+ function getBootSnapshotForDir(shell, initDir) {
2125
+ if (!shell || !shell._initialBootSnapshot || !shell._initialBootRoot) return {};
2126
+ const normInit = PosixPath.normalize(initDir);
2127
+ const normBoot = shell._initialBootRoot;
2128
+ if (normInit === normBoot) {
2129
+ return shell._initialBootSnapshot;
2130
+ }
2131
+ const prefix = normBoot === '/' ? '/' : normBoot + '/';
2132
+ if (normInit.startsWith(prefix)) {
2133
+ const subRel = normInit.slice(prefix.length) + '/';
2134
+ const subSnap = {};
2135
+ for (const [k, v] of Object.entries(shell._initialBootSnapshot)) {
2136
+ if (k.startsWith(subRel)) {
2137
+ subSnap[k.slice(subRel.length)] = v;
2138
+ }
2139
+ }
2140
+ return subSnap;
2141
+ }
2142
+ return {};
2143
+ }
2144
+
2145
+ function attachShellStagedMapShim(map, vfsRef, getRepoRoot, getGitState) {
2146
+ if (!(map instanceof Map)) return map;
2147
+ if (!map._hasShellStagedShim) {
2148
+ Object.defineProperty(map, '_hasShellStagedShim', {
2149
+ value: true,
2150
+ enumerable: false,
2151
+ configurable: true,
2152
+ writable: true
2153
+ });
2154
+ Object.defineProperty(map, 'add', {
2155
+ value(rawPath) {
2156
+ const gs = typeof getGitState === 'function' ? getGitState() : null;
2157
+ const root =
2158
+ typeof getRepoRoot === 'function'
2159
+ ? getRepoRoot()
2160
+ : ((gs && gs.repoRoot) || '/workspace');
2161
+ const rel = normalizeGitRelPath(rawPath, root);
2162
+ if (!rel) return map;
2163
+ let content = null;
2164
+ if (vfsRef && typeof vfsRef.existsSync === 'function') {
2165
+ const abs = PosixPath.join(root, rel);
2166
+ if (vfsRef.existsSync(abs)) {
2167
+ if (typeof vfsRef.statSync === 'function') {
2168
+ try {
2169
+ if (vfsRef.statSync(abs).isDirectory()) return map;
2170
+ } catch (err) {
2171
+ _shellLogger.debug('Failed statting staged path in VFS.', abs, err);
2172
+ }
2173
+ }
2174
+ if (typeof vfsRef.readFileSync === 'function') {
2175
+ try {
2176
+ content = String(vfsRef.readFileSync(abs, 'utf8'));
2177
+ } catch (err) {
2178
+ _shellLogger.debug('Failed reading staged file from VFS.', abs, err);
2179
+ return map;
2180
+ }
2181
+ }
2182
+ }
2183
+ }
2184
+ if (gs) {
2185
+ applyShellStagedEntry(gs, map, rel, content);
2186
+ } else {
2187
+ map.set(rel, content);
2188
+ }
2189
+ return map;
2190
+ },
2191
+ enumerable: false,
2192
+ configurable: true,
2193
+ writable: true
2194
+ });
2195
+ }
2196
+ return map;
2197
+ }
2198
+
2199
+ function ensureShellStagedMap(gitState, vfsRef, repoRoot) {
2200
+ const getRoot = () => (gitState && gitState.repoRoot) || repoRoot || '/workspace';
2201
+ const getGs = () => gitState;
2202
+ if (gitState.staged instanceof Map) {
2203
+ attachShellStagedMapShim(gitState.staged, vfsRef, getRoot, getGs);
2204
+ pruneShellStagedMap(gitState, gitState.staged);
2205
+ gitState.stagedFiles = gitState.staged;
2206
+ return gitState.staged;
2207
+ }
2208
+ const nextMap = attachShellStagedMapShim(new Map(), vfsRef, getRoot, getGs);
2209
+ if (gitState.staged && typeof gitState.staged[Symbol.iterator] === 'function') {
2210
+ for (const item of gitState.staged) {
2211
+ if (Array.isArray(item) && item.length >= 2) {
2212
+ applyShellStagedEntry(
2213
+ gitState,
2214
+ nextMap,
2215
+ item[0],
2216
+ item[1] === null ? null : String(item[1])
2217
+ );
2218
+ } else if (typeof item === 'string') {
2219
+ nextMap.add(item);
2220
+ }
2221
+ }
2222
+ }
2223
+ gitState.staged = nextMap;
2224
+ gitState.stagedFiles = nextMap;
2225
+ return nextMap;
2226
+ }
2227
+
2228
+ function parseGitHeadBranch(vfs, repoRoot) {
2229
+ if (!vfs || typeof vfs.existsSync !== 'function' || typeof vfs.readFileSync !== 'function') {
2230
+ return null;
2231
+ }
2232
+ const candidates = [
2233
+ PosixPath.join(repoRoot, '.git/HEAD'),
2234
+ '/workspace/.git/HEAD'
2235
+ ];
2236
+ for (const headFile of candidates) {
2237
+ if (vfs.existsSync(headFile)) {
2238
+ try {
2239
+ const raw = String(vfs.readFileSync(headFile, 'utf8')).trim();
2240
+ const m = /^ref:\s*refs\/heads\/([^\s]+)$/.exec(raw);
2241
+ if (m && m[1]) return m[1];
2242
+ } catch (err) {
2243
+ _shellLogger.debug('Could not parse .git/HEAD branch.', headFile, err);
2244
+ }
2245
+ }
2246
+ }
2247
+ return null;
2248
+ }
2249
+
2250
+ function createUnifiedShellGitState(vfs, cwd, options = {}) {
2251
+ const cleanCwd = PosixPath.normalize(cwd || '/workspace');
2252
+ const hasDotGit = Boolean(
2253
+ vfs &&
2254
+ typeof vfs.existsSync === 'function' &&
2255
+ (vfs.existsSync(PosixPath.join(cleanCwd, '.git')) ||
2256
+ vfs.existsSync(PosixPath.join(cleanCwd, '.git/HEAD')) ||
2257
+ vfs.existsSync('/workspace/.git') ||
2258
+ vfs.existsSync('/workspace/.git/HEAD'))
2259
+ );
2260
+
2261
+ let _initialized = Boolean(options.gitInitialized === true || hasDotGit);
2262
+ let _repoRoot = cleanCwd;
2263
+ const detectedBranch = hasDotGit ? parseGitHeadBranch(vfs, cleanCwd) : null;
2264
+ const initialBranch = detectedBranch || 'main';
2265
+
2266
+ let _headFiles = _initialized ? snapshotWorktree(vfs, cleanCwd) : {};
2267
+ let _headCommit = _initialized
2268
+ ? computeGitShortHash(JSON.stringify(_headFiles) + ':init')
2269
+ : '';
2270
+ const initTs = Date.now();
2271
+ let _commits = _initialized
2272
+ ? [
2273
+ {
2274
+ hash: _headCommit,
2275
+ author: 'CodeLab Developer <dev@codelab.internal>',
2276
+ date: new Date(initTs).toUTCString(),
2277
+ timestamp: initTs,
2278
+ message: 'Initial commit',
2279
+ files: Object.assign({}, _headFiles)
2280
+ }
2281
+ ]
2282
+ : [];
2283
+
2284
+ const gs = {
2285
+ branch: initialBranch,
2286
+ branches: new Set([initialBranch]),
2287
+ remoteUrl: null,
2288
+ remotes: {}
2289
+ };
2290
+
2291
+ let _stagedMap = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2292
+
2293
+ Object.defineProperties(gs, {
2294
+ initialized: {
2295
+ enumerable: true,
2296
+ configurable: true,
2297
+ get() {
2298
+ if (_initialized) return true;
2299
+ const root = _repoRoot || cleanCwd;
2300
+ if (
2301
+ vfs &&
2302
+ typeof vfs.existsSync === 'function' &&
2303
+ (vfs.existsSync(PosixPath.join(root, '.git')) ||
2304
+ vfs.existsSync(PosixPath.join(root, '.git/HEAD')))
2305
+ ) {
2306
+ _initialized = true;
2307
+ return true;
2308
+ }
2309
+ return false;
2310
+ },
2311
+ set(v) {
2312
+ _initialized = Boolean(v);
2313
+ }
2314
+ },
2315
+ repoRoot: {
2316
+ enumerable: true,
2317
+ configurable: true,
2318
+ get() {
2319
+ return _repoRoot;
2320
+ },
2321
+ set(v) {
2322
+ _repoRoot = PosixPath.normalize(String(v || cleanCwd));
2323
+ }
2324
+ },
2325
+ headCommit: {
2326
+ enumerable: true,
2327
+ configurable: true,
2328
+ get() {
2329
+ return _headCommit;
2330
+ },
2331
+ set(v) {
2332
+ _headCommit = String(v || '');
2333
+ }
2334
+ },
2335
+ headSnapshot: {
2336
+ enumerable: true,
2337
+ configurable: true,
2338
+ get() {
2339
+ return _headFiles;
2340
+ },
2341
+ set(v) {
2342
+ _headFiles = v && typeof v === 'object' ? v : {};
2343
+ }
2344
+ },
2345
+ headFiles: {
2346
+ enumerable: true,
2347
+ configurable: true,
2348
+ get() {
2349
+ return _headFiles;
2350
+ },
2351
+ set(v) {
2352
+ _headFiles = v && typeof v === 'object' ? v : {};
2353
+ }
2354
+ },
2355
+ staged: {
2356
+ enumerable: true,
2357
+ configurable: true,
2358
+ get() {
2359
+ return _stagedMap;
2360
+ },
2361
+ set(v) {
2362
+ if (v instanceof Map) {
2363
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2364
+ pruneShellStagedMap(gs, _stagedMap);
2365
+ } else {
2366
+ const converted = attachShellStagedMapShim(new Map(), vfs, () => _repoRoot, () => gs);
2367
+ if (v && typeof v[Symbol.iterator] === 'function') {
2368
+ for (const item of v) {
2369
+ if (typeof item === 'string') {
2370
+ converted.add(item);
2371
+ } else if (Array.isArray(item) && item.length >= 2) {
2372
+ applyShellStagedEntry(
2373
+ gs,
2374
+ converted,
2375
+ item[0],
2376
+ item[1] === null ? null : String(item[1])
2377
+ );
2378
+ }
2379
+ }
2380
+ }
2381
+ _stagedMap = converted;
2382
+ }
2383
+ }
2384
+ },
2385
+ stagedFiles: {
2386
+ enumerable: true,
2387
+ configurable: true,
2388
+ get() {
2389
+ return _stagedMap;
2390
+ },
2391
+ set(v) {
2392
+ if (v instanceof Map) {
2393
+ _stagedMap = attachShellStagedMapShim(v, vfs, () => _repoRoot, () => gs);
2394
+ pruneShellStagedMap(gs, _stagedMap);
2395
+ }
2396
+ }
2397
+ },
2398
+ commits: {
2399
+ enumerable: true,
2400
+ configurable: true,
2401
+ get() {
2402
+ return _commits;
2403
+ },
2404
+ set(v) {
2405
+ _commits = Array.isArray(v) ? v : [];
2406
+ if (_commits.length > 0 && _commits[0] && _commits[0].hash) {
2407
+ _headCommit = String(_commits[0].hash);
2408
+ } else if (_commits.length === 0) {
2409
+ _headCommit = '';
2410
+ }
2411
+ }
2412
+ }
2413
+ });
2414
+
2415
+ return gs;
2416
+ }
2417
+
2009
2418
  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;
2010
2419
 
2011
2420
  function scoreRepoFilePriority(relPath) {
@@ -2266,18 +2675,23 @@
2266
2675
  if (commitsRes && commitsRes.ok) {
2267
2676
  const commitsJson = await commitsRes.json();
2268
2677
  if (Array.isArray(commitsJson) && commitsJson.length > 0) {
2269
- commits = commitsJson.map((c) => ({
2270
- hash: String(c.sha || 'a1b2c3d').slice(0, 7),
2271
- author:
2272
- c.commit && c.commit.author
2273
- ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2274
- : `${owner} <${owner}@users.noreply.github.com>`,
2275
- date:
2276
- c.commit && c.commit.author && c.commit.author.date
2277
- ? new Date(c.commit.author.date).toUTCString()
2278
- : new Date().toUTCString(),
2279
- message: c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit'
2280
- }));
2678
+ commits = commitsJson.map((c, idx) => {
2679
+ const msgText = c.commit && c.commit.message ? String(c.commit.message).split('\n')[0] : 'Commit';
2680
+ const fallbackHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${idx}:${msgText}`);
2681
+ const ts = c.commit && c.commit.author && c.commit.author.date
2682
+ ? Date.parse(c.commit.author.date) || Date.now()
2683
+ : Date.now();
2684
+ return {
2685
+ hash: String(c.sha || fallbackHash).slice(0, 7),
2686
+ author:
2687
+ c.commit && c.commit.author
2688
+ ? `${c.commit.author.name || owner} <${c.commit.author.email || `${owner}@users.noreply.github.com`}>`
2689
+ : `${owner} <${owner}@users.noreply.github.com>`,
2690
+ date: new Date(ts).toUTCString(),
2691
+ timestamp: ts,
2692
+ message: msgText
2693
+ };
2694
+ });
2281
2695
  }
2282
2696
  }
2283
2697
  } catch (err) {
@@ -2285,11 +2699,14 @@
2285
2699
  }
2286
2700
 
2287
2701
  if (commits.length === 0) {
2702
+ const cloneTs = Date.now();
2703
+ const cloneHash = computeGitShortHash(`${owner}/${repo}:${resolvedBranch}:${filesWritten}`);
2288
2704
  commits = [
2289
2705
  {
2290
- hash: 'a1b2c3d',
2706
+ hash: cloneHash,
2291
2707
  author: `${owner} <${owner}@users.noreply.github.com>`,
2292
- date: new Date().toUTCString(),
2708
+ date: new Date(cloneTs).toUTCString(),
2709
+ timestamp: cloneTs,
2293
2710
  message: `Clone ${owner}/${repo} (${resolvedBranch})`
2294
2711
  }
2295
2712
  ];
@@ -5478,26 +5895,56 @@
5478
5895
  // -----------------------------------------------------------------------
5479
5896
  async git(args, ctx) {
5480
5897
  const subcmd = args[0] || 'status';
5898
+ if (subcmd === 'version' || subcmd === '--version' || subcmd === '-v') {
5899
+ return { code: 0, stdout: 'git version 2.45.0 (CodeLab Virtual Git)\n', stderr: '' };
5900
+ }
5901
+ if (subcmd === 'help' || subcmd === '--help' || subcmd === '-h') {
5902
+ return {
5903
+ code: 0,
5904
+ stdout:
5905
+ 'usage: git <command> [<args>]\n\nCommon commands: init, clone, status, add, diff, commit, restore, reset, rm, branch, checkout, switch, remote, fetch, pull, log\n',
5906
+ stderr: ''
5907
+ };
5908
+ }
5909
+
5481
5910
  const gitState = ctx.shell.gitState;
5482
5911
  if (!(gitState.branches instanceof Set)) {
5483
5912
  gitState.branches = new Set(Array.isArray(gitState.branches) ? gitState.branches : [gitState.branch || 'main']);
5484
5913
  }
5485
- if (!gitState.headSnapshot) {
5486
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, gitState.repoRoot || ctx.cwd);
5487
- }
5488
5914
  if (!gitState.remotes) {
5489
5915
  gitState.remotes = gitState.remoteUrl ? { origin: gitState.remoteUrl } : {};
5490
5916
  }
5491
5917
 
5492
- const repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
5918
+ let repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
5919
+ const stagedMap = ensureShellStagedMap(gitState, ctx.vfs, repoRoot);
5920
+
5493
5921
  const toRepoRel = (p) => {
5494
5922
  const abs = ctx.resolvePath(p);
5495
5923
  const prefix = repoRoot === '/' ? '/' : repoRoot + '/';
5496
5924
  if (abs === repoRoot) return '.';
5497
- if (abs.startsWith(prefix)) return abs.slice(prefix.length);
5498
- return p.replace(/^\.\//, '');
5925
+ if (abs.startsWith(prefix)) return normalizeGitRelPath(abs.slice(prefix.length), repoRoot);
5926
+ return '';
5499
5927
  };
5500
5928
 
5929
+ if (subcmd !== 'init' && subcmd !== 'clone') {
5930
+ const hasDotGitInFs = Boolean(
5931
+ ctx.vfs &&
5932
+ typeof ctx.vfs.existsSync === 'function' &&
5933
+ (ctx.vfs.existsSync(PosixPath.join(repoRoot, '.git')) ||
5934
+ ctx.vfs.existsSync(PosixPath.join(ctx.cwd, '.git')))
5935
+ );
5936
+ if (!gitState.initialized && !hasDotGitInFs) {
5937
+ return {
5938
+ code: 128,
5939
+ stdout: '',
5940
+ stderr: 'fatal: not a git repository (or any of the parent directories): .git\n'
5941
+ };
5942
+ }
5943
+ if (hasDotGitInFs && !gitState.initialized) {
5944
+ gitState.initialized = true;
5945
+ }
5946
+ }
5947
+
5501
5948
  if (subcmd === 'clone') {
5502
5949
  let branchOpt = null;
5503
5950
  const positional = [];
@@ -5544,7 +5991,6 @@
5544
5991
  dirDisplayName = parsed.repo;
5545
5992
  }
5546
5993
 
5547
- // Stream clone progress to the terminal as it happens (no end-of-run buffering).
5548
5994
  const canStream = typeof ctx.onStdout === 'function';
5549
5995
  const streamLine = (text) => { if (canStream && text) ctx.onStdout(text); };
5550
5996
  streamLine(`Cloning into '${dirDisplayName}'...\n`);
@@ -5578,14 +6024,18 @@
5578
6024
  }
5579
6025
  });
5580
6026
 
6027
+ const clonedHead = Object.assign({}, result.headSnapshot);
6028
+ gitState.initialized = true;
5581
6029
  gitState.branch = result.branch;
5582
6030
  gitState.branches.add(result.branch);
5583
6031
  gitState.remoteUrl = result.url;
5584
6032
  gitState.remotes.origin = result.url;
5585
6033
  gitState.repoRoot = targetDir;
5586
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6034
+ gitState.headSnapshot = clonedHead;
6035
+ gitState.headFiles = clonedHead;
5587
6036
  gitState.commits = result.commits;
5588
- gitState.staged.clear();
6037
+ gitState.headCommit = (result.commits && result.commits[0] && result.commits[0].hash) || '';
6038
+ stagedMap.clear();
5589
6039
 
5590
6040
  const count = Math.max(1, result.filesWritten);
5591
6041
  const kb = Math.max(0.1, result.totalBytes / 1024).toFixed(1);
@@ -5611,62 +6061,149 @@
5611
6061
  }
5612
6062
 
5613
6063
  if (subcmd === 'init') {
5614
- const initDir = args[1] && !args[1].startsWith('-') ? ctx.resolvePath(args[1]) : ctx.cwd;
6064
+ let initBranch = gitState.branch || 'main';
6065
+ let emptyHead = false;
6066
+ let dirArg = null;
6067
+ for (let i = 1; i < args.length; i++) {
6068
+ const a = args[i];
6069
+ if ((a === '-b' || a === '--initial-branch') && i + 1 < args.length) {
6070
+ initBranch = args[++i];
6071
+ } else if (a.startsWith('--initial-branch=')) {
6072
+ initBranch = a.slice('--initial-branch='.length) || initBranch;
6073
+ } else if (a === '--empty-head') {
6074
+ emptyHead = true;
6075
+ } else if (!a.startsWith('-') && !dirArg) {
6076
+ dirArg = a;
6077
+ }
6078
+ }
6079
+ const initDir = PosixPath.normalize(dirArg ? ctx.resolvePath(dirArg) : ctx.cwd);
5615
6080
  const gitDir = PosixPath.join(initDir, '.git');
6081
+ const wasReinitSameDir =
6082
+ Boolean(gitState.initialized) &&
6083
+ PosixPath.normalize(gitState.repoRoot || ctx.cwd) === initDir &&
6084
+ !emptyHead;
5616
6085
  ensureDirSync(ctx.vfs, gitDir, ctx.emitMutation);
5617
- const branchName = gitState.branch || 'main';
5618
- ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${branchName}\n`);
6086
+ if (!wasReinitSameDir || !ctx.vfs.existsSync(PosixPath.join(gitDir, 'HEAD'))) {
6087
+ ctx.vfs.writeFileSync(PosixPath.join(gitDir, 'HEAD'), `ref: refs/heads/${initBranch}\n`);
6088
+ }
5619
6089
  ctx.vfs.writeFileSync(
5620
6090
  PosixPath.join(gitDir, 'config'),
5621
6091
  `[core]\n\trepositoryformatversion = 0\n\tfilemode = true\n\tbare = false\n`
5622
6092
  );
5623
6093
  ctx.emitMutation('create', PosixPath.join(gitDir, 'HEAD'));
6094
+
6095
+ if (wasReinitSameDir && !isUnbornShellHead(gitState)) {
6096
+ gitState.branches.add(gitState.branch || initBranch);
6097
+ return {
6098
+ code: 0,
6099
+ stdout: `Reinitialized existing Git repository in ${gitDir}/\n`,
6100
+ stderr: ''
6101
+ };
6102
+ }
6103
+
6104
+ const initSnap = {};
6105
+ if (!emptyHead) {
6106
+ const currentLive = snapshotWorktree(ctx.vfs, initDir);
6107
+ const bootSnap = getBootSnapshotForDir(ctx.shell, initDir);
6108
+ for (const [rel, content] of Object.entries(currentLive)) {
6109
+ if (Object.prototype.hasOwnProperty.call(bootSnap, rel) && bootSnap[rel] === content) {
6110
+ initSnap[rel] = content;
6111
+ }
6112
+ }
6113
+ }
6114
+ gitState.initialized = true;
6115
+ gitState.branch = initBranch;
6116
+ gitState.branches.add(initBranch);
5624
6117
  gitState.repoRoot = initDir;
5625
- gitState.headSnapshot = snapshotWorktree(ctx.vfs, initDir);
5626
- gitState.staged.clear();
5627
- return { code: 0, stdout: `Initialized empty Git repository in ${gitDir}/\n`, stderr: '' };
6118
+ gitState.headSnapshot = initSnap;
6119
+ gitState.headFiles = initSnap;
6120
+ gitState.commits = [];
6121
+ gitState.headCommit = '';
6122
+ stagedMap.clear();
6123
+ return {
6124
+ code: 0,
6125
+ stdout: `${wasReinitSameDir ? 'Reinitialized existing' : 'Initialized empty'} Git repository in ${gitDir}/\n`,
6126
+ stderr: ''
6127
+ };
5628
6128
  }
5629
6129
 
6130
+ repoRoot = PosixPath.normalize(gitState.repoRoot || ctx.cwd);
6131
+
5630
6132
  if (subcmd === 'status') {
5631
- const isShort = args.includes('-s') || args.includes('--short');
6133
+ const isShort = args.includes('-s') || args.includes('--short') || args.includes('--porcelain');
5632
6134
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5633
- const headFiles = gitState.headSnapshot || {};
6135
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6136
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6137
+ const unbornHead = isUnbornShellHead(gitState);
5634
6138
 
5635
6139
  const stagedList = [];
5636
- for (const relPath of gitState.staged) {
6140
+ const unstagedList = [];
6141
+ const untrackedList = [];
6142
+ const stagedKeysSorted = Array.from(stagedMap.keys()).sort();
6143
+
6144
+ for (const relPath of stagedKeysSorted) {
6145
+ const stagedVal = stagedMap.get(relPath);
5637
6146
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5638
6147
  const inLive = Object.prototype.hasOwnProperty.call(liveFiles, relPath);
5639
- if (!inHead && inLive) {
5640
- stagedList.push({ status: 'new file', short: 'A ', path: relPath });
5641
- } else if (inHead && !inLive) {
5642
- stagedList.push({ status: 'deleted', short: 'D ', path: relPath });
6148
+
6149
+ if (stagedVal === null) {
6150
+ if (inHead) {
6151
+ stagedList.push({ status: 'deleted', code: 'D', path: relPath });
6152
+ }
6153
+ if (inLive) {
6154
+ untrackedList.push(relPath);
6155
+ }
5643
6156
  } else {
5644
- stagedList.push({ status: 'modified', short: 'M ', path: relPath });
6157
+ if (!inHead || unbornHead) {
6158
+ stagedList.push({ status: 'new file', code: 'A', path: relPath });
6159
+ } else if (stagedVal !== headFiles[relPath]) {
6160
+ stagedList.push({ status: 'modified', code: 'M', path: relPath });
6161
+ }
6162
+
6163
+ if (!inLive) {
6164
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
6165
+ } else if (liveFiles[relPath] !== stagedVal) {
6166
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
6167
+ }
5645
6168
  }
5646
6169
  }
5647
6170
 
5648
- const unstagedList = [];
5649
6171
  for (const relPath of Object.keys(headFiles).sort()) {
5650
- if (gitState.staged.has(relPath)) continue;
6172
+ if (stagedMap.has(relPath)) continue;
5651
6173
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5652
- unstagedList.push({ status: 'deleted', short: ' D', path: relPath });
6174
+ unstagedList.push({ status: 'deleted', code: 'D', path: relPath });
5653
6175
  } else if (liveFiles[relPath] !== headFiles[relPath]) {
5654
- unstagedList.push({ status: 'modified', short: ' M', path: relPath });
6176
+ unstagedList.push({ status: 'modified', code: 'M', path: relPath });
5655
6177
  }
5656
6178
  }
5657
6179
 
5658
- const untrackedList = [];
5659
6180
  for (const relPath of Object.keys(liveFiles).sort()) {
5660
- if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
6181
+ if (!Object.prototype.hasOwnProperty.call(headFiles, relPath) && !stagedMap.has(relPath)) {
5661
6182
  untrackedList.push(relPath);
5662
6183
  }
5663
6184
  }
5664
6185
 
6186
+ unstagedList.sort((a, b) => a.path.localeCompare(b.path));
6187
+ untrackedList.sort();
6188
+
5665
6189
  if (isShort) {
6190
+ const shortByPath = new Map();
6191
+ for (const item of stagedList) {
6192
+ shortByPath.set(item.path, { idx: item.code, wt: ' ' });
6193
+ }
6194
+ for (const item of unstagedList) {
6195
+ const prev = shortByPath.get(item.path);
6196
+ if (prev) prev.wt = item.code;
6197
+ else shortByPath.set(item.path, { idx: ' ', wt: item.code });
6198
+ }
5666
6199
  let sOut = '';
5667
- for (const item of stagedList) sOut += `${item.short} ${item.path}\n`;
5668
- for (const item of unstagedList) sOut += `${item.short} ${item.path}\n`;
5669
- for (const p of untrackedList) sOut += `?? ${p}\n`;
6200
+ for (const p of Array.from(shortByPath.keys()).sort()) {
6201
+ const pair = shortByPath.get(p);
6202
+ sOut += `${pair.idx}${pair.wt} ${p}\n`;
6203
+ }
6204
+ for (const p of untrackedList) {
6205
+ sOut += `?? ${p}\n`;
6206
+ }
5670
6207
  return { code: 0, stdout: sOut, stderr: '' };
5671
6208
  }
5672
6209
 
@@ -5703,24 +6240,43 @@
5703
6240
 
5704
6241
  if (subcmd === 'diff') {
5705
6242
  const isStaged = args.includes('--staged') || args.includes('--cached');
5706
- const fileFilters = args.slice(1).filter((a) => !a.startsWith('-')).map(toRepoRel);
6243
+ const rawFilterArgs = args.slice(1).filter((a) => !a.startsWith('-'));
6244
+ const fileFilters = rawFilterArgs.map(toRepoRel);
6245
+ const matchAllInRepo = fileFilters.length === 0 || fileFilters.includes('.');
5707
6246
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5708
- const headFiles = gitState.headSnapshot || {};
5709
- const allKeys = Array.from(new Set([...Object.keys(headFiles), ...Object.keys(liveFiles)])).sort();
6247
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6248
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6249
+ const unbornHead = isUnbornShellHead(gitState);
6250
+ const allKeys = Array.from(
6251
+ new Set([...Object.keys(headFiles), ...Object.keys(liveFiles), ...Array.from(stagedMap.keys())])
6252
+ ).sort();
5710
6253
 
5711
6254
  let stdout = '';
5712
6255
  for (const relPath of allKeys) {
5713
- if (fileFilters.length > 0 && !fileFilters.includes(relPath)) continue;
5714
- if (isStaged && !gitState.staged.has(relPath)) continue;
5715
- if (!isStaged && !Object.prototype.hasOwnProperty.call(headFiles, relPath) && !gitState.staged.has(relPath)) {
5716
- continue;
5717
- }
5718
- const oldText = Object.prototype.hasOwnProperty.call(headFiles, relPath) ? headFiles[relPath] : '';
5719
- const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
5720
- if (oldText !== newText) {
5721
- const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
5722
- if (uDiff) {
5723
- stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6256
+ if (!matchAllInRepo && !fileFilters.includes(relPath)) continue;
6257
+ if (isStaged) {
6258
+ if (!stagedMap.has(relPath)) continue;
6259
+ const stagedVal = stagedMap.get(relPath);
6260
+ if (!isEffectiveShellStagedChange(gitState, relPath, stagedVal, headFiles)) continue;
6261
+ const oldText =
6262
+ !unbornHead && Object.prototype.hasOwnProperty.call(headFiles, relPath)
6263
+ ? headFiles[relPath]
6264
+ : '';
6265
+ const newText = stagedVal === null ? '' : String(stagedVal);
6266
+ if (oldText !== newText) {
6267
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6268
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
6269
+ }
6270
+ } else {
6271
+ const isTrackedOrStaged =
6272
+ Object.prototype.hasOwnProperty.call(headFiles, relPath) || stagedMap.has(relPath);
6273
+ if (!isTrackedOrStaged) continue;
6274
+ const baseVal = stagedMap.has(relPath) ? stagedMap.get(relPath) : headFiles[relPath];
6275
+ const oldText = baseVal === null || baseVal === undefined ? '' : String(baseVal);
6276
+ const newText = Object.prototype.hasOwnProperty.call(liveFiles, relPath) ? liveFiles[relPath] : '';
6277
+ if (oldText !== newText) {
6278
+ const uDiff = computeUnifiedDiff(`a/${relPath}`, `b/${relPath}`, oldText, newText);
6279
+ if (uDiff) stdout += `diff --git a/${relPath} b/${relPath}\n${uDiff}`;
5724
6280
  }
5725
6281
  }
5726
6282
  }
@@ -5730,38 +6286,76 @@
5730
6286
  if (subcmd === 'add') {
5731
6287
  const targets = args.slice(1);
5732
6288
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5733
- const headFiles = gitState.headSnapshot || {};
6289
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6290
+
6291
+ const stagePath = (relPath) => {
6292
+ const clean = normalizeGitRelPath(relPath, repoRoot);
6293
+ if (!clean) return;
6294
+ const inLive = Object.prototype.hasOwnProperty.call(liveFiles, clean);
6295
+ const inHead = Object.prototype.hasOwnProperty.call(headFiles, clean);
6296
+ if (inLive) {
6297
+ applyShellStagedEntry(gitState, stagedMap, clean, liveFiles[clean], headFiles);
6298
+ } else if (inHead) {
6299
+ applyShellStagedEntry(gitState, stagedMap, clean, null, headFiles);
6300
+ } else {
6301
+ stagedMap.delete(clean);
6302
+ }
6303
+ };
5734
6304
 
5735
6305
  if (targets.includes('.') || targets.includes('-A') || targets.includes('--all') || targets.includes('-u')) {
5736
6306
  const includeUntracked = !targets.includes('-u');
5737
6307
  for (const relPath of Object.keys(liveFiles)) {
5738
6308
  const inHead = Object.prototype.hasOwnProperty.call(headFiles, relPath);
5739
6309
  if (!inHead && includeUntracked) {
5740
- gitState.staged.add(relPath);
5741
- } else if (inHead && liveFiles[relPath] !== headFiles[relPath]) {
5742
- gitState.staged.add(relPath);
6310
+ stagePath(relPath);
6311
+ } else if (inHead) {
6312
+ stagePath(relPath);
5743
6313
  }
5744
6314
  }
5745
6315
  for (const relPath of Object.keys(headFiles)) {
5746
6316
  if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5747
- gitState.staged.add(relPath);
6317
+ stagePath(relPath);
6318
+ }
6319
+ }
6320
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6321
+ if (
6322
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6323
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6324
+ ) {
6325
+ stagedMap.delete(stagedKey);
5748
6326
  }
5749
6327
  }
5750
6328
  } else {
5751
6329
  for (const f of targets) {
5752
6330
  if (f.startsWith('-')) continue;
5753
6331
  const rel = toRepoRel(f);
6332
+ if (!rel) continue;
5754
6333
  if (rel === '.') {
5755
- for (const k of Object.keys(liveFiles)) {
5756
- if (liveFiles[k] !== headFiles[k]) gitState.staged.add(k);
6334
+ for (const k of Object.keys(liveFiles)) stagePath(k);
6335
+ for (const k of Object.keys(headFiles)) {
6336
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, k)) stagePath(k);
6337
+ }
6338
+ for (const stagedKey of Array.from(stagedMap.keys())) {
6339
+ if (
6340
+ !Object.prototype.hasOwnProperty.call(liveFiles, stagedKey) &&
6341
+ !Object.prototype.hasOwnProperty.call(headFiles, stagedKey)
6342
+ ) {
6343
+ stagedMap.delete(stagedKey);
6344
+ }
5757
6345
  }
5758
6346
  } else {
5759
6347
  const dirPrefix = rel.replace(/\/+$/, '') + '/';
5760
- const matchedSubfiles = Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix));
6348
+ const matchedSubfiles = Array.from(
6349
+ new Set([
6350
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6351
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6352
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6353
+ ])
6354
+ );
5761
6355
  if (matchedSubfiles.length > 0) {
5762
- for (const k of matchedSubfiles) gitState.staged.add(k);
6356
+ for (const k of matchedSubfiles) stagePath(k);
5763
6357
  } else {
5764
- gitState.staged.add(rel);
6358
+ stagePath(rel);
5765
6359
  }
5766
6360
  }
5767
6361
  }
@@ -5771,37 +6365,72 @@
5771
6365
 
5772
6366
  if (subcmd === 'commit') {
5773
6367
  const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
5774
- const headFiles = gitState.headSnapshot || {};
5775
- if (args.includes('-a') || args.includes('-am')) {
6368
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6369
+ const autoStageTracked = args.some(
6370
+ (a) =>
6371
+ a === '-a' ||
6372
+ a === '--all' ||
6373
+ (a.startsWith('-') && !a.startsWith('--') && a !== '-m' && a.includes('a'))
6374
+ );
6375
+ if (autoStageTracked) {
5776
6376
  for (const relPath of Object.keys(headFiles)) {
5777
- if (liveFiles[relPath] !== headFiles[relPath]) {
5778
- gitState.staged.add(relPath);
6377
+ if (!Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
6378
+ applyShellStagedEntry(gitState, stagedMap, relPath, null, headFiles);
6379
+ } else {
6380
+ applyShellStagedEntry(gitState, stagedMap, relPath, liveFiles[relPath], headFiles);
5779
6381
  }
5780
6382
  }
5781
6383
  }
5782
6384
 
6385
+ pruneShellStagedMap(gitState, stagedMap, headFiles);
6386
+
6387
+ if (stagedMap.size === 0) {
6388
+ return {
6389
+ code: 1,
6390
+ stdout: `On branch ${gitState.branch}\nnothing to commit, working tree clean\n`,
6391
+ stderr: ''
6392
+ };
6393
+ }
6394
+
5783
6395
  let msg = 'Commit changes';
5784
- const mIdx = args.findIndex((a) => a === '-m' || a === '-am');
6396
+ const mIdx = args.findIndex(
6397
+ (a) => a === '-m' || a === '-am' || a === '-ma'
6398
+ );
5785
6399
  if (mIdx !== -1 && mIdx + 1 < args.length) msg = args[mIdx + 1];
5786
6400
 
5787
- for (const relPath of gitState.staged) {
5788
- if (Object.prototype.hasOwnProperty.call(liveFiles, relPath)) {
5789
- gitState.headSnapshot[relPath] = liveFiles[relPath];
6401
+ const nextHead = Object.assign({}, headFiles);
6402
+ const summaryParts = [];
6403
+ for (const [relPath, stagedVal] of stagedMap.entries()) {
6404
+ summaryParts.push(`${relPath}:${stagedVal === null ? '<DEL>' : stagedVal}`);
6405
+ if (stagedVal === null) {
6406
+ delete nextHead[relPath];
5790
6407
  } else {
5791
- delete gitState.headSnapshot[relPath];
6408
+ nextHead[relPath] = String(stagedVal);
5792
6409
  }
5793
6410
  }
5794
6411
 
5795
- const hash = Math.random().toString(16).slice(2, 9);
6412
+ const commitTs = Date.now();
6413
+ const hash = computeGitShortHash(
6414
+ `${gitState.headCommit || ''}:${msg}:${commitTs}:${gitState.commits.length}:${summaryParts.join('|')}`
6415
+ );
6416
+ const count = stagedMap.size;
6417
+ gitState.headSnapshot = nextHead;
6418
+ gitState.headFiles = nextHead;
5796
6419
  gitState.commits.unshift({
5797
6420
  hash,
5798
- author: `${ctx.env.USER || 'codelab'} <dev@codelab.internal>`,
5799
- date: new Date().toUTCString(),
5800
- message: msg
6421
+ author: `${ctx.env.USER || 'CodeLab Developer'} <dev@codelab.internal>`,
6422
+ date: new Date(commitTs).toUTCString(),
6423
+ timestamp: commitTs,
6424
+ message: msg,
6425
+ files: Object.assign({}, nextHead)
5801
6426
  });
5802
- const count = gitState.staged.size || 1;
5803
- gitState.staged.clear();
5804
- return { code: 0, stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file changed\n`, stderr: '' };
6427
+ gitState.headCommit = hash;
6428
+ stagedMap.clear();
6429
+ return {
6430
+ code: 0,
6431
+ stdout: `[${gitState.branch} ${hash}] ${msg}\n ${count} file${count === 1 ? '' : 's'} changed\n`,
6432
+ stderr: ''
6433
+ };
5805
6434
  }
5806
6435
 
5807
6436
  if (subcmd === 'branch') {
@@ -5861,9 +6490,11 @@
5861
6490
  }
5862
6491
 
5863
6492
  const rel = toRepoRel(target);
5864
- if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6493
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6494
+ if (rel && Object.prototype.hasOwnProperty.call(headFiles, rel)) {
5865
6495
  const abs = PosixPath.join(repoRoot, rel);
5866
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6496
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6497
+ ctx.vfs.writeFileSync(abs, headFiles[rel]);
5867
6498
  ctx.emitMutation('change', abs);
5868
6499
  return { code: 0, stdout: `Updated 1 path from the index\n`, stderr: '' };
5869
6500
  }
@@ -5873,20 +6504,199 @@
5873
6504
 
5874
6505
  if (subcmd === 'restore') {
5875
6506
  const isStaged = args.includes('--staged') || args.includes('-S');
5876
- const targets = args.slice(1).filter((a) => !a.startsWith('-'));
6507
+ const isWorktree = args.includes('--worktree') || args.includes('-W') || !isStaged;
6508
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6509
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
5877
6510
  for (const t of targets) {
5878
6511
  const rel = toRepoRel(t);
6512
+ if (!rel) continue;
5879
6513
  if (isStaged) {
5880
- gitState.staged.delete(rel);
5881
- } else if (gitState.headSnapshot && Object.prototype.hasOwnProperty.call(gitState.headSnapshot, rel)) {
6514
+ if (rel === '.') {
6515
+ stagedMap.clear();
6516
+ } else {
6517
+ const cleanRel = rel.replace(/\/+$/, '');
6518
+ const dirPrefix = cleanRel + '/';
6519
+ stagedMap.delete(cleanRel);
6520
+ for (const k of Array.from(stagedMap.keys())) {
6521
+ if (k.startsWith(dirPrefix)) {
6522
+ stagedMap.delete(k);
6523
+ }
6524
+ }
6525
+ }
6526
+ }
6527
+ if (isWorktree) {
6528
+ if (rel === '.') {
6529
+ for (const [k, v] of Object.entries(headFiles)) {
6530
+ const abs = PosixPath.join(repoRoot, k);
6531
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6532
+ ctx.vfs.writeFileSync(abs, v);
6533
+ ctx.emitMutation('change', abs);
6534
+ }
6535
+ } else {
6536
+ const cleanRel = rel.replace(/\/+$/, '');
6537
+ const dirPrefix = cleanRel + '/';
6538
+ const subHeadKeys = Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix));
6539
+ if (subHeadKeys.length > 0 && !Object.prototype.hasOwnProperty.call(headFiles, cleanRel)) {
6540
+ for (const k of subHeadKeys) {
6541
+ const sourceText =
6542
+ !isStaged && stagedMap.has(k) && stagedMap.get(k) !== null
6543
+ ? stagedMap.get(k)
6544
+ : headFiles[k];
6545
+ const abs = PosixPath.join(repoRoot, k);
6546
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6547
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6548
+ ctx.emitMutation('change', abs);
6549
+ }
6550
+ } else {
6551
+ const sourceText =
6552
+ !isStaged && stagedMap.has(cleanRel) && stagedMap.get(cleanRel) !== null
6553
+ ? stagedMap.get(cleanRel)
6554
+ : (Object.prototype.hasOwnProperty.call(headFiles, cleanRel) ? headFiles[cleanRel] : undefined);
6555
+ if (sourceText !== undefined) {
6556
+ const abs = PosixPath.join(repoRoot, cleanRel);
6557
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6558
+ ctx.vfs.writeFileSync(abs, String(sourceText));
6559
+ ctx.emitMutation('change', abs);
6560
+ }
6561
+ }
6562
+ }
6563
+ }
6564
+ }
6565
+ return { code: 0, stdout: '', stderr: '' };
6566
+ }
6567
+
6568
+ if (subcmd === 'reset') {
6569
+ const isHard = args.includes('--hard');
6570
+ const fileArgs = args.slice(1).filter((a) => !a.startsWith('-') && a !== 'HEAD' && a !== '--');
6571
+ if (fileArgs.length > 0) {
6572
+ for (const f of fileArgs) {
6573
+ const rel = toRepoRel(f);
6574
+ if (!rel) continue;
6575
+ if (rel === '.') {
6576
+ stagedMap.clear();
6577
+ } else {
6578
+ const cleanRel = rel.replace(/\/+$/, '');
6579
+ const dirPrefix = cleanRel + '/';
6580
+ stagedMap.delete(cleanRel);
6581
+ for (const k of Array.from(stagedMap.keys())) {
6582
+ if (k.startsWith(dirPrefix)) {
6583
+ stagedMap.delete(k);
6584
+ }
6585
+ }
6586
+ }
6587
+ }
6588
+ return { code: 0, stdout: '', stderr: '' };
6589
+ }
6590
+ stagedMap.clear();
6591
+ if (isHard) {
6592
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6593
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6594
+ for (const rel of Object.keys(liveFiles)) {
6595
+ if (!Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6596
+ const abs = PosixPath.join(repoRoot, rel);
6597
+ if (typeof ctx.vfs.rmSync === 'function') {
6598
+ ctx.vfs.rmSync(abs, { force: true });
6599
+ } else if (typeof ctx.vfs.unlinkSync === 'function' && ctx.vfs.existsSync(abs)) {
6600
+ ctx.vfs.unlinkSync(abs);
6601
+ }
6602
+ ctx.emitMutation('delete', abs);
6603
+ }
6604
+ }
6605
+ for (const [rel, text] of Object.entries(headFiles)) {
5882
6606
  const abs = PosixPath.join(repoRoot, rel);
5883
- ctx.vfs.writeFileSync(abs, gitState.headSnapshot[rel]);
6607
+ ensureDirSync(ctx.vfs, PosixPath.dirname(abs), ctx.emitMutation);
6608
+ ctx.vfs.writeFileSync(abs, text);
5884
6609
  ctx.emitMutation('change', abs);
5885
6610
  }
5886
6611
  }
5887
6612
  return { code: 0, stdout: '', stderr: '' };
5888
6613
  }
5889
6614
 
6615
+ if (subcmd === 'rm') {
6616
+ const cachedOnly = args.includes('--cached');
6617
+ const isRecursive = args.some((a) => a === '-r' || a === '-rf' || a === '-fr');
6618
+ const targets = args.slice(1).filter((a) => !a.startsWith('-') && a !== '--');
6619
+ const headFiles = gitState.headSnapshot || gitState.headFiles || {};
6620
+ const liveFiles = snapshotWorktree(ctx.vfs, repoRoot);
6621
+
6622
+ if (targets.length === 0) {
6623
+ return { code: 128, stdout: '', stderr: 'usage: git rm [--cached] [-r] [-f] <file>...\n' };
6624
+ }
6625
+
6626
+ const removeSingleRel = (rel) => {
6627
+ if (!rel) return;
6628
+ const abs = PosixPath.join(repoRoot, rel);
6629
+ if (!cachedOnly && ctx.vfs.existsSync(abs)) {
6630
+ if (typeof ctx.vfs.rmSync === 'function') {
6631
+ ctx.vfs.rmSync(abs, { force: true, recursive: isRecursive });
6632
+ } else if (typeof ctx.vfs.unlinkSync === 'function') {
6633
+ ctx.vfs.unlinkSync(abs);
6634
+ }
6635
+ ctx.emitMutation('delete', abs);
6636
+ }
6637
+ if (Object.prototype.hasOwnProperty.call(headFiles, rel)) {
6638
+ stagedMap.set(rel, null);
6639
+ } else {
6640
+ stagedMap.delete(rel);
6641
+ }
6642
+ };
6643
+
6644
+ for (const t of targets) {
6645
+ const rel = toRepoRel(t);
6646
+ if (!rel) continue;
6647
+ if (rel === '.') {
6648
+ if (isRecursive) {
6649
+ const allRel = Array.from(
6650
+ new Set([
6651
+ ...Object.keys(headFiles),
6652
+ ...Object.keys(liveFiles),
6653
+ ...Array.from(stagedMap.keys())
6654
+ ])
6655
+ );
6656
+ for (const sub of allRel) removeSingleRel(sub);
6657
+ }
6658
+ continue;
6659
+ }
6660
+ const dirPrefix = rel.replace(/\/+$/, '') + '/';
6661
+ const subMatches = isRecursive
6662
+ ? Array.from(
6663
+ new Set([
6664
+ ...Object.keys(headFiles).filter((k) => k.startsWith(dirPrefix)),
6665
+ ...Object.keys(liveFiles).filter((k) => k.startsWith(dirPrefix)),
6666
+ ...Array.from(stagedMap.keys()).filter((k) => k.startsWith(dirPrefix))
6667
+ ])
6668
+ )
6669
+ : [];
6670
+ if (subMatches.length > 0) {
6671
+ for (const sub of subMatches) removeSingleRel(sub);
6672
+ if (!cachedOnly) removeDirRecursive(ctx.vfs, PosixPath.join(repoRoot, rel), ctx.emitMutation);
6673
+ } else {
6674
+ const abs = PosixPath.join(repoRoot, rel);
6675
+ if (
6676
+ !isRecursive &&
6677
+ ctx.vfs &&
6678
+ typeof ctx.vfs.existsSync === 'function' &&
6679
+ ctx.vfs.existsSync(abs) &&
6680
+ typeof ctx.vfs.statSync === 'function'
6681
+ ) {
6682
+ try {
6683
+ if (ctx.vfs.statSync(abs).isDirectory()) {
6684
+ return {
6685
+ code: 128,
6686
+ stdout: '',
6687
+ stderr: `fatal: not removing '${t}' recursively without -r\n`
6688
+ };
6689
+ }
6690
+ } catch (err) {
6691
+ _shellLogger.debug('Failed statting path in git rm.', abs, err);
6692
+ }
6693
+ }
6694
+ removeSingleRel(rel);
6695
+ }
6696
+ }
6697
+ return { code: 0, stdout: '', stderr: '' };
6698
+ }
6699
+
5890
6700
  if (subcmd === 'remote') {
5891
6701
  const sub = args[1];
5892
6702
  if (!sub) {
@@ -5934,7 +6744,9 @@
5934
6744
  signal: ctx.signal,
5935
6745
  onFile: (absPath) => ctx.emitMutation('change', absPath)
5936
6746
  });
5937
- gitState.headSnapshot = Object.assign({}, result.headSnapshot);
6747
+ const pulledHead = Object.assign({}, result.headSnapshot);
6748
+ gitState.headSnapshot = pulledHead;
6749
+ gitState.headFiles = pulledHead;
5938
6750
  return {
5939
6751
  code: 0,
5940
6752
  stdout: `From ${remoteUrl.replace(/\.git$/, '')}\n * branch ${result.branch} -> FETCH_HEAD\nAlready up to date.\n`,
@@ -5961,9 +6773,11 @@
5961
6773
  if (oneline) {
5962
6774
  stdout += `${c.hash} ${c.message}\n`;
5963
6775
  } else {
6776
+ const authorStr = c.author || 'CodeLab Developer <dev@codelab.internal>';
6777
+ const dateStr = c.date || (c.timestamp ? new Date(c.timestamp).toUTCString() : new Date(0).toUTCString());
5964
6778
  stdout += `commit ${c.hash}\n`;
5965
- stdout += `Author: ${c.author}\n`;
5966
- stdout += `Date: ${c.date}\n\n`;
6779
+ stdout += `Author: ${authorStr}\n`;
6780
+ stdout += `Date: ${dateStr}\n\n`;
5967
6781
  stdout += ` ${c.message}\n\n`;
5968
6782
  }
5969
6783
  }
@@ -7780,6 +8594,16 @@
7780
8594
  if (options.files && typeof options.files === 'object') {
7781
8595
  for (const [k, v] of Object.entries(options.files)) {
7782
8596
  const abs = PosixPath.resolve(this.cwd, k);
8597
+ if (typeof this.vfs.mkdirSync === 'function') {
8598
+ const parentDir = PosixPath.dirname(abs);
8599
+ if (
8600
+ parentDir &&
8601
+ parentDir !== '/' &&
8602
+ (typeof this.vfs.existsSync !== 'function' || !this.vfs.existsSync(parentDir))
8603
+ ) {
8604
+ this.vfs.mkdirSync(parentDir, { recursive: true });
8605
+ }
8606
+ }
7783
8607
  if (typeof this.vfs.writeFileSync === 'function') {
7784
8608
  this.vfs.writeFileSync(abs, String(v ?? ''));
7785
8609
  }
@@ -7791,23 +8615,19 @@
7791
8615
  this.nextPid = 100;
7792
8616
  this.commands = Object.assign({}, COREUTILS, options.commands || {});
7793
8617
 
7794
- this.gitState = {
7795
- branch: 'main',
7796
- branches: new Set(['main']),
7797
- remoteUrl: null,
7798
- remotes: {},
7799
- repoRoot: this.cwd,
7800
- headSnapshot: snapshotWorktree(this.vfs, this.cwd),
7801
- staged: new Set(),
7802
- commits: [
7803
- {
7804
- hash: 'a1b2c3d',
7805
- author: 'CodeLab Developer <dev@codelab.internal>',
7806
- date: new Date().toUTCString(),
7807
- message: 'Initial project commit'
7808
- }
7809
- ]
7810
- };
8618
+ this._initialBootRoot = options._initialBootRoot
8619
+ ? PosixPath.normalize(options._initialBootRoot)
8620
+ : PosixPath.normalize(this.cwd || '/workspace');
8621
+ this._initialBootSnapshot =
8622
+ options._initialBootSnapshot && typeof options._initialBootSnapshot === 'object'
8623
+ ? options._initialBootSnapshot
8624
+ : snapshotWorktree(this.vfs, this._initialBootRoot);
8625
+
8626
+ if (options.gitState && typeof options.gitState === 'object') {
8627
+ this.gitState = options.gitState;
8628
+ } else {
8629
+ this.gitState = createUnifiedShellGitState(this.vfs, this.cwd, options);
8630
+ }
7811
8631
  }
7812
8632
 
7813
8633
  resolvePath(p) {
@@ -7936,6 +8756,9 @@
7936
8756
  ...this.options,
7937
8757
  vfs: this.vfs,
7938
8758
  portTable: this.portTable,
8759
+ gitState: this.gitState,
8760
+ _initialBootRoot: this._initialBootRoot,
8761
+ _initialBootSnapshot: this._initialBootSnapshot,
7939
8762
  env: { ...env, PWD: this.cwd }
7940
8763
  });
7941
8764
  subShell.cwd = this.cwd;
@@ -8657,6 +9480,7 @@
8657
9480
  ...this.options,
8658
9481
  vfs: this.vfs,
8659
9482
  portTable: this.portTable,
9483
+ gitState: this.gitState,
8660
9484
  env: Object.assign({}, this.env, innerCtx.env || {})
8661
9485
  });
8662
9486
  subShell.cwd = innerCtx.cwd || this.cwd;