@nemus-cli/nemus 0.15.2 → 0.16.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.
@@ -0,0 +1,219 @@
1
+ import { Command } from 'commander';
2
+ import { execFile } from 'child_process';
3
+ import { promisify } from 'util';
4
+ import * as path from 'path';
5
+ import { getGlobalOpts } from '../utils/command-helpers';
6
+ import { readLockFile, parseLock, reconstructRepo, LOCK_FILENAME, type WorkspaceLock, type LockRepo } from '../utils/workspace-lock';
7
+ import { cloneRepositories, reportCloneResults } from '../utils/git-operations';
8
+ import { warnIfGhqMissing } from '../utils/ghq-integration';
9
+ import { createMetadata, saveMetadata } from '../utils/workspace-meta';
10
+ import { generateClaudeContext } from '../utils/claude-integration';
11
+ import { verifyGhAuth } from '../utils/github';
12
+ import { validateWorkspaceName, checkWorkspaceExists, sanitizeWorkspaceName, resolveWorkspaceNameConflict, safeWorkspacePath } from '../utils/validation';
13
+ import { logError, logInfo, logSuccess, logStep, logWarning } from '../utils/logger';
14
+ import { colorize } from '../utils/colors';
15
+ import { printBanner } from '../utils/banner';
16
+ import type { CloneResult } from '../types';
17
+
18
+ export interface RestoreResult {
19
+ workspaceName: string;
20
+ workspacePath: string;
21
+ results: CloneResult[];
22
+ }
23
+
24
+ const execFileAsync = promisify(execFile);
25
+ const GIT_TIMEOUT = 30000;
26
+
27
+ export function registerRestoreCommand(parent: Command) {
28
+ parent
29
+ .command('restore [lockfile]')
30
+ .description('Recreate a workspace from a nemus.lock (defaults to ./nemus.lock, "-" for stdin)')
31
+ .option('-w, --workspace <name>', 'Override the workspace name baked into the lockfile')
32
+ .option('--pin', 'Check out the exact recorded commit instead of the branch tip')
33
+ .action(async (lockfile, opts, cmd) => {
34
+ const globalOpts = getGlobalOpts(cmd);
35
+ await handleRestore({ lockfile, ...opts, ...globalOpts });
36
+ });
37
+ }
38
+
39
+ async function readStdin(): Promise<string> {
40
+ const chunks: Buffer[] = [];
41
+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer);
42
+ return Buffer.concat(chunks).toString('utf-8');
43
+ }
44
+
45
+ // `branch`/`commit` come from an untrusted lockfile (already ref-validated in
46
+ // parseLock); the `--end-of-options` guard is defense-in-depth so a ref can
47
+ // never be reparsed as a git option even if validation is bypassed.
48
+ /** Check out `branch` in a freshly-cloned repo, creating a tracking branch if needed. */
49
+ async function checkoutBranch(repoPath: string, branch: string): Promise<boolean> {
50
+ try {
51
+ await execFileAsync('git', ['checkout', '--end-of-options', branch], { cwd: repoPath, timeout: GIT_TIMEOUT });
52
+ return true;
53
+ } catch {
54
+ try {
55
+ await execFileAsync('git', ['checkout', '-b', branch, '--end-of-options', `origin/${branch}`], { cwd: repoPath, timeout: GIT_TIMEOUT });
56
+ return true;
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+ }
62
+
63
+ async function checkoutCommit(repoPath: string, commit: string): Promise<boolean> {
64
+ try {
65
+ await execFileAsync('git', ['checkout', '--end-of-options', commit], { cwd: repoPath, timeout: GIT_TIMEOUT });
66
+ return true;
67
+ } catch {
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Core restore: clone every repo in a (already-validated) lock and check out the
74
+ * recorded branch (or the exact commit with `pin`), then write metadata + agent
75
+ * context — exactly like `create`. Throws on fatal errors (no process.exit) and
76
+ * logs progress via the logger (stderr), so both the CLI and the MCP tool can
77
+ * call it. Callers own presentation (final message, shell-CD hook).
78
+ */
79
+ export async function restoreWorkspace(
80
+ lock: WorkspaceLock,
81
+ opts: { workspace?: string; pin?: boolean } = {}
82
+ ): Promise<RestoreResult> {
83
+ if (lock.repositories.length === 0) {
84
+ throw new Error('Lockfile has no repositories to restore');
85
+ }
86
+
87
+ // Resolve the target workspace name
88
+ let workspaceName = sanitizeWorkspaceName(opts.workspace || lock.workspace);
89
+ const nameError = validateWorkspaceName(workspaceName);
90
+ if (nameError !== true) {
91
+ throw new Error(typeof nameError === 'string' ? nameError : 'Invalid workspace name');
92
+ }
93
+ if (await checkWorkspaceExists(workspaceName)) {
94
+ const resolved = await resolveWorkspaceNameConflict(
95
+ workspaceName,
96
+ lock.repositories.map(r => r.directoryName)
97
+ );
98
+ logInfo(`Workspace "${workspaceName}" already exists — using "${colorize(resolved, 'cyan')}" instead.`);
99
+ workspaceName = resolved;
100
+ }
101
+
102
+ const workspacePath = safeWorkspacePath(workspaceName);
103
+ logInfo(`Restoring ${colorize(String(lock.repositories.length), 'cyan')} repos into workspace "${colorize(workspaceName, 'cyan')}"`);
104
+
105
+ // Clone every repo (reuses the create pipeline: ghq, concurrency, dedup)
106
+ logStep(1, 3, 'Cloning repositories...');
107
+ const { mkdir } = await import('fs/promises');
108
+ await mkdir(workspacePath, { recursive: true });
109
+ await warnIfGhqMissing();
110
+
111
+ const entries = lock.repositories.map(r => ({
112
+ repo: reconstructRepo(r),
113
+ directoryName: r.directoryName,
114
+ }));
115
+ const results = await cloneRepositories(entries, workspacePath);
116
+ reportCloneResults(results);
117
+
118
+ // Check out the recorded branch (or pinned commit) per repo
119
+ logStep(2, 3, opts.pin ? 'Checking out pinned commits...' : 'Checking out recorded branches...');
120
+ const byDir = new Map<string, LockRepo>(lock.repositories.map(r => [r.directoryName, r]));
121
+ for (const result of results) {
122
+ if (result.status !== 'success') continue;
123
+ const entry = byDir.get(result.directoryName);
124
+ if (!entry) continue;
125
+ const repoPath = path.join(workspacePath, result.directoryName);
126
+ const display = colorize(result.directoryName, 'cyan');
127
+
128
+ if (opts.pin && entry.commit) {
129
+ if (!(await checkoutCommit(repoPath, entry.commit))) {
130
+ logWarning(`${display}: could not check out pinned commit ${entry.commit} — left on the default branch`);
131
+ }
132
+ } else if (entry.branch) {
133
+ if (await checkoutBranch(repoPath, entry.branch)) {
134
+ logInfo(`${display} → ${entry.branch}`);
135
+ } else if (entry.commit && (await checkoutCommit(repoPath, entry.commit))) {
136
+ logWarning(`${display}: branch "${entry.branch}" not found — checked out commit ${entry.commit} instead`);
137
+ } else {
138
+ logWarning(`${display}: could not check out "${entry.branch}" — left on the default branch`);
139
+ }
140
+ } else if (entry.commit) {
141
+ // No branch was recorded (detached HEAD at lock time) — restore the commit
142
+ // so that state isn't silently lost even without --pin.
143
+ if (await checkoutCommit(repoPath, entry.commit)) {
144
+ logInfo(`${display} → ${entry.commit} (detached)`);
145
+ } else {
146
+ logWarning(`${display}: could not check out commit ${entry.commit} — left on the default branch`);
147
+ }
148
+ }
149
+ }
150
+
151
+ // Metadata + agent context (same as create)
152
+ logStep(3, 3, 'Saving workspace metadata...');
153
+ const metadata = createMetadata(workspaceName, results, { prompt: `Restored from ${LOCK_FILENAME}` });
154
+ await saveMetadata(workspacePath, metadata);
155
+
156
+ const successfulRepos = results.filter(r => r.status === 'success').map(r => r.repo);
157
+ if (successfulRepos.length > 0) {
158
+ await generateClaudeContext(workspacePath, workspaceName, successfulRepos, metadata);
159
+ }
160
+
161
+ return { workspaceName, workspacePath, results };
162
+ }
163
+
164
+ async function handleRestore(opts: {
165
+ lockfile?: string;
166
+ workspace?: string;
167
+ pin?: boolean;
168
+ yes: boolean;
169
+ }) {
170
+ printBanner();
171
+
172
+ try {
173
+ // Step 1: Load + validate the lockfile
174
+ let lock: WorkspaceLock;
175
+ if (opts.lockfile === '-') {
176
+ lock = parseLock(await readStdin());
177
+ } else {
178
+ const lockPath = path.resolve(opts.lockfile || LOCK_FILENAME);
179
+ try {
180
+ lock = await readLockFile(lockPath);
181
+ } catch (error) {
182
+ logError(`Could not read lockfile at ${lockPath}`);
183
+ if (error instanceof Error) logError(error.message);
184
+ logInfo('Pass a path (nemus restore path/to/nemus.lock) or pipe one with: nemus restore -');
185
+ process.exit(1);
186
+ }
187
+ }
188
+
189
+ if (lock.repositories.length === 0) {
190
+ logError('Lockfile has no repositories to restore');
191
+ process.exit(1);
192
+ }
193
+
194
+ // gh auth (soft — private repos need it, public/other creds may not)
195
+ if (!(await verifyGhAuth())) {
196
+ logWarning('GitHub CLI not authenticated — private repositories may fail to clone.');
197
+ }
198
+
199
+ const { workspaceName, workspacePath } = await restoreWorkspace(lock, {
200
+ workspace: opts.workspace,
201
+ pin: opts.pin,
202
+ });
203
+
204
+ logSuccess(`Workspace "${colorize(workspaceName, 'cyan')}" restored!`);
205
+
206
+ // Shell-integration auto-CD (same hook create uses)
207
+ try {
208
+ const { writeFile } = await import('fs/promises');
209
+ const os = await import('os');
210
+ await writeFile(path.join(os.homedir(), '.workspace-last-created'), workspacePath, 'utf-8');
211
+ } catch {
212
+ // non-critical
213
+ }
214
+ } catch (error) {
215
+ logError('Failed to restore workspace');
216
+ if (error instanceof Error) logError(error.message);
217
+ process.exit(1);
218
+ }
219
+ }
package/src/mcp/server.ts CHANGED
@@ -41,6 +41,8 @@ import {
41
41
  handleSuiteImport,
42
42
  handleSuiteUse,
43
43
  handleSaveContext,
44
+ handleLockWorkspace,
45
+ handleRestoreWorkspace,
44
46
  } from './tools';
45
47
 
46
48
  import { getPackageVersion } from '../utils/config';
@@ -567,6 +569,44 @@ server.tool(
567
569
  }
568
570
  );
569
571
 
572
+ server.tool(
573
+ 'lock-workspace',
574
+ 'Snapshot a workspace into a committable nemus.lock manifest (repos + owner + the branch each repo is on + its HEAD commit) so it can be shared and recreated elsewhere with restore-workspace. Writes nemus.lock to the workspace root by default and returns the manifest.',
575
+ {
576
+ workspace: wsName.describe('Name of the workspace to lock'),
577
+ output: z.string().optional().describe('Optional path to write the lockfile to instead of <workspace>/nemus.lock'),
578
+ },
579
+ async ({ workspace, output }) => {
580
+ try {
581
+ const result = await handleLockWorkspace(workspace, output);
582
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
583
+ } catch (error) {
584
+ const msg = error instanceof Error ? error.message : 'Unknown error';
585
+ return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
586
+ }
587
+ }
588
+ );
589
+
590
+ server.tool(
591
+ 'restore-workspace',
592
+ 'Recreate a workspace from a nemus.lock manifest: clone every repo and check out the recorded branch (or the exact commit with pin). Provide the manifest inline via lockContent, or a path via lockfile (defaults to ./nemus.lock).',
593
+ {
594
+ lockContent: z.string().optional().describe('The nemus.lock manifest JSON, inline (preferred for agents)'),
595
+ lockfile: z.string().optional().describe('Path to a nemus.lock file (used when lockContent is not given; defaults to ./nemus.lock)'),
596
+ workspace: wsName.optional().describe('Override the workspace name baked into the lockfile'),
597
+ pin: z.boolean().optional().describe('Check out the exact recorded commit instead of the branch tip'),
598
+ },
599
+ async ({ lockContent, lockfile, workspace, pin }) => {
600
+ try {
601
+ const result = await handleRestoreWorkspace({ lockContent, lockfile, workspace, pin });
602
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
603
+ } catch (error) {
604
+ const msg = error instanceof Error ? error.message : 'Unknown error';
605
+ return { content: [{ type: 'text', text: `Error: ${msg}` }], isError: true };
606
+ }
607
+ }
608
+ );
609
+
570
610
  async function main() {
571
611
  const transport = new StdioServerTransport();
572
612
  await server.connect(transport);
package/src/mcp/tools.ts CHANGED
@@ -21,6 +21,8 @@ import { removeNodeModules, removeBuildArtifacts } from '../utils/cleanup-operat
21
21
  import { runPostCloneHooks } from '../utils/hooks';
22
22
  import { SuiteEntry, WorkspaceSuite, SuitesStore } from '../types';
23
23
  import { resolveWorkspaceNameConflict, sanitizeWorkspaceName, safeWorkspacePath } from '../utils/validation';
24
+ import { buildLock, writeLock, readLockFile, parseLock, LOCK_FILENAME } from '../utils/workspace-lock';
25
+ import { restoreWorkspace } from '../commands/restore';
24
26
 
25
27
  /**
26
28
  * Redirects stdout to stderr for the duration of a function call.
@@ -1017,3 +1019,70 @@ export async function handleSaveContext(workspace: string, content: string, appe
1017
1019
  };
1018
1020
  });
1019
1021
  }
1022
+
1023
+ // ── Portable workspaces: lock / restore ─────────────────────────────────────
1024
+
1025
+ /**
1026
+ * Snapshot a workspace into a nemus.lock manifest (repos + branch + commit).
1027
+ * Writes it to the workspace root by default and also returns the manifest so
1028
+ * an agent can share/commit it.
1029
+ */
1030
+ export async function handleLockWorkspace(workspace: string, output?: string) {
1031
+ return withStdoutProtection(async () => {
1032
+ if (!workspace || workspace.trim().length === 0) {
1033
+ throw new Error('Workspace name is required');
1034
+ }
1035
+ const workspacePath = safeWorkspacePath(sanitizeWorkspaceName(workspace));
1036
+ const metadata = await loadMetadata(workspacePath);
1037
+ if (!metadata) {
1038
+ throw new Error(`Workspace not found: ${workspace}`);
1039
+ }
1040
+ const lock = await buildLock(workspacePath, metadata);
1041
+ const outPath = output ? path.resolve(output) : path.join(workspacePath, LOCK_FILENAME);
1042
+ await writeLock(outPath, lock);
1043
+ return {
1044
+ workspace: metadata.workspaceName,
1045
+ lockfilePath: outPath,
1046
+ repoCount: lock.repositories.length,
1047
+ lock,
1048
+ };
1049
+ });
1050
+ }
1051
+
1052
+ /**
1053
+ * Recreate a workspace from a nemus.lock. Accepts either inline `lockContent`
1054
+ * (the manifest JSON) or a `lockfile` path (defaults to ./nemus.lock). Clones
1055
+ * every repo and checks out the recorded branch (or exact commit with `pin`).
1056
+ */
1057
+ export async function handleRestoreWorkspace(opts: {
1058
+ workspace?: string;
1059
+ lockfile?: string;
1060
+ lockContent?: string;
1061
+ pin?: boolean;
1062
+ }) {
1063
+ return withStdoutProtection(async () => {
1064
+ const lock = opts.lockContent
1065
+ ? parseLock(opts.lockContent)
1066
+ : await readLockFile(path.resolve(opts.lockfile || LOCK_FILENAME));
1067
+
1068
+ const { workspaceName, workspacePath, results } = await restoreWorkspace(lock, {
1069
+ workspace: opts.workspace,
1070
+ pin: opts.pin,
1071
+ });
1072
+
1073
+ const cloned = results.filter(r => r.status === 'success');
1074
+ const failed = results.filter(r => r.status === 'failed');
1075
+ return {
1076
+ workspace: workspaceName,
1077
+ path: workspacePath,
1078
+ cloned: cloned.length,
1079
+ failed: failed.length,
1080
+ repositories: results.map(r => ({
1081
+ name: r.repo.name,
1082
+ directoryName: r.directoryName,
1083
+ status: r.status,
1084
+ ...(r.error ? { error: r.error } : {}),
1085
+ })),
1086
+ };
1087
+ });
1088
+ }
package/src/program.ts CHANGED
@@ -64,6 +64,8 @@ import { registerMigrateCommand } from './commands/migrate';
64
64
  import { registerReportBugCommand } from './commands/report-bug';
65
65
  import { registerCompletionCommand } from './commands/completion';
66
66
  import { registerReflectCommand } from './commands/reflect';
67
+ import { registerLockCommand } from './commands/lock';
68
+ import { registerRestoreCommand } from './commands/restore';
67
69
 
68
70
  registerCreateCommand(program);
69
71
  registerListCommand(program);
@@ -92,6 +94,8 @@ registerMigrateCommand(program);
92
94
  registerReportBugCommand(program);
93
95
  registerCompletionCommand(program);
94
96
  registerReflectCommand(program);
97
+ registerLockCommand(program);
98
+ registerRestoreCommand(program);
95
99
 
96
100
  // Register TUI (delegates to existing Ink/React implementation)
97
101
  program
@@ -0,0 +1,200 @@
1
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
2
+ import { execFile } from 'child_process';
3
+ import { promisify } from 'util';
4
+ import * as fs from 'fs/promises';
5
+ import * as os from 'os';
6
+ import * as path from 'path';
7
+ import {
8
+ parseLock,
9
+ serializeLock,
10
+ parseGitHost,
11
+ reconstructRepo,
12
+ buildLock,
13
+ isSafeSegment,
14
+ isAllowedCloneUrl,
15
+ isSafeGitRef,
16
+ LOCK_VERSION,
17
+ type WorkspaceLock,
18
+ type LockRepo,
19
+ } from './workspace-lock';
20
+ import type { WorkspaceMetadata } from '../types';
21
+
22
+ const execFileAsync = promisify(execFile);
23
+
24
+ const validLock: WorkspaceLock = {
25
+ version: LOCK_VERSION,
26
+ workspace: 'checkout-flow',
27
+ generatedAt: '2026-09-09T10:00:00.000Z',
28
+ repositories: [
29
+ { name: 'web', owner: 'acme', directoryName: 'web', cloneUrl: 'git@github.com:acme/web.git', branch: 'feat/x', commit: 'abc1234' },
30
+ ],
31
+ };
32
+
33
+ describe('parseLock', () => {
34
+ it('round-trips a valid lock through serialize + parse', () => {
35
+ const parsed = parseLock(serializeLock(validLock));
36
+ expect(parsed).toEqual(validLock);
37
+ });
38
+
39
+ it('rejects non-JSON', () => {
40
+ expect(() => parseLock('not json')).toThrow(/valid JSON/i);
41
+ });
42
+
43
+ it('rejects an unsupported version', () => {
44
+ const bad = JSON.stringify({ ...validLock, version: 99 });
45
+ expect(() => parseLock(bad)).toThrow(/version 99/);
46
+ });
47
+
48
+ it('rejects a missing workspace name', () => {
49
+ const bad = JSON.stringify({ ...validLock, workspace: '' });
50
+ expect(() => parseLock(bad)).toThrow(/workspace/i);
51
+ });
52
+
53
+ it('rejects a non-array repositories field', () => {
54
+ const bad = JSON.stringify({ ...validLock, repositories: {} });
55
+ expect(() => parseLock(bad)).toThrow(/repositories/i);
56
+ });
57
+
58
+ it('rejects a repo entry missing a required field', () => {
59
+ const bad = JSON.stringify({ ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName: 'web' }] });
60
+ expect(() => parseLock(bad)).toThrow(/cloneUrl/);
61
+ });
62
+
63
+ it('accepts entries without optional branch/commit', () => {
64
+ const minimal = { ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName: 'web', cloneUrl: 'https://github.com/acme/web.git' }] };
65
+ expect(() => parseLock(JSON.stringify(minimal))).not.toThrow();
66
+ });
67
+
68
+ // Untrusted-input hardening: fields that reach git / path.join are validated.
69
+ it('rejects a directoryName that escapes the workspace', () => {
70
+ for (const directoryName of ['../evil', 'a/b', '..', 'a\\b']) {
71
+ const bad = { ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName, cloneUrl: 'https://h/o/r.git' }] };
72
+ expect(() => parseLock(JSON.stringify(bad)), directoryName).toThrow(/path segment/);
73
+ }
74
+ });
75
+
76
+ it('rejects an owner/name that is not a safe path segment (reconstructRepo builds URLs from them)', () => {
77
+ const badOwner = { ...validLock, repositories: [{ name: 'web', owner: '../x', directoryName: 'web', cloneUrl: 'https://h/o/r.git' }] };
78
+ expect(() => parseLock(JSON.stringify(badOwner))).toThrow(/owner/);
79
+ const badName = { ...validLock, repositories: [{ name: 'a/b', owner: 'acme', directoryName: 'web', cloneUrl: 'https://h/o/r.git' }] };
80
+ expect(() => parseLock(JSON.stringify(badName))).toThrow(/name/);
81
+ });
82
+
83
+ it('rejects a cloneUrl with no recognized transport (option-injection)', () => {
84
+ for (const cloneUrl of ['--upload-pack=/x', '-oProxyCommand=x', '/local/path.git', 'file:///x']) {
85
+ const bad = { ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName: 'web', cloneUrl }] };
86
+ expect(() => parseLock(JSON.stringify(bad)), cloneUrl).toThrow(/transport/);
87
+ }
88
+ });
89
+
90
+ it('rejects a branch/commit that could smuggle git flags', () => {
91
+ const badBranch = { ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName: 'web', cloneUrl: 'https://h/o/r.git', branch: '--upload-pack=x' }] };
92
+ expect(() => parseLock(JSON.stringify(badBranch))).toThrow(/branch/);
93
+ const badCommit = { ...validLock, repositories: [{ name: 'web', owner: 'acme', directoryName: 'web', cloneUrl: 'https://h/o/r.git', commit: '-x' }] };
94
+ expect(() => parseLock(JSON.stringify(badCommit))).toThrow(/commit/);
95
+ });
96
+ });
97
+
98
+ describe('field validators', () => {
99
+ it('isSafeSegment accepts plain names, rejects traversal/separators', () => {
100
+ for (const ok of ['web', 'my-repo', 'repo.git', 'a..b']) expect(isSafeSegment(ok), ok).toBe(true);
101
+ for (const no of ['', '.', '..', 'a/b', 'a\\b', '../x']) expect(isSafeSegment(no), no).toBe(false);
102
+ });
103
+ it('isAllowedCloneUrl accepts real remotes, rejects options/paths', () => {
104
+ for (const ok of ['https://github.com/a/b.git', 'ssh://git@h/a/b', 'git@github.com:a/b.git', 'git://h/a/b']) expect(isAllowedCloneUrl(ok), ok).toBe(true);
105
+ for (const no of ['--upload-pack=x', '/local/path', 'file:///x', 'ext::sh -c x']) expect(isAllowedCloneUrl(no), no).toBe(false);
106
+ });
107
+ it('isSafeGitRef accepts real refs, rejects flags/metachars', () => {
108
+ for (const ok of ['main', 'feat/x', 'release-1.2', 'abc1234']) expect(isSafeGitRef(ok), ok).toBe(true);
109
+ for (const no of ['-x', '--flag', 'a b', 'a..b', 'a~1', 'a^', 'a:b', '']) expect(isSafeGitRef(no), no).toBe(false);
110
+ });
111
+ });
112
+
113
+ describe('parseGitHost', () => {
114
+ it('parses scp-style URLs', () => {
115
+ expect(parseGitHost('git@github.com:acme/web.git')).toBe('github.com');
116
+ expect(parseGitHost('git@gitlab.example.com:team/app.git')).toBe('gitlab.example.com');
117
+ });
118
+ it('parses URL-style remotes', () => {
119
+ expect(parseGitHost('https://github.com/acme/web.git')).toBe('github.com');
120
+ expect(parseGitHost('ssh://git@code.corp/team/app')).toBe('code.corp');
121
+ });
122
+ it('returns undefined for garbage', () => {
123
+ expect(parseGitHost('not-a-url')).toBeUndefined();
124
+ });
125
+ });
126
+
127
+ describe('reconstructRepo', () => {
128
+ it('synthesizes https + ssh forms for a known host so getCloneUrl can pick', () => {
129
+ const repo = reconstructRepo({ name: 'web', owner: 'acme', directoryName: 'web', cloneUrl: 'git@github.com:acme/web.git' });
130
+ expect(repo.url).toBe('https://github.com/acme/web');
131
+ expect(repo.sshUrl).toBe('git@github.com:acme/web.git');
132
+ expect(repo.owner.login).toBe('acme');
133
+ });
134
+
135
+ it('preserves a non-default host from the locked URL', () => {
136
+ const repo = reconstructRepo({ name: 'app', owner: 'team', directoryName: 'app', cloneUrl: 'git@gitlab.corp:team/app.git' });
137
+ expect(repo.url).toBe('https://gitlab.corp/team/app');
138
+ expect(repo.sshUrl).toBe('git@gitlab.corp:team/app.git');
139
+ });
140
+
141
+ it('falls back to the stored URL when the host is unparseable', () => {
142
+ const url = './local/path.git';
143
+ const repo = reconstructRepo({ name: 'x', owner: 'y', directoryName: 'x', cloneUrl: url });
144
+ expect(repo.url).toBe(url);
145
+ expect(repo.sshUrl).toBe(url);
146
+ });
147
+ });
148
+
149
+ describe('buildLock', () => {
150
+ let tmp: string;
151
+ let repoDir: string;
152
+
153
+ beforeAll(async () => {
154
+ tmp = await fs.mkdtemp(path.join(os.tmpdir(), 'nemus-lock-'));
155
+ repoDir = path.join(tmp, 'web');
156
+ await fs.mkdir(repoDir, { recursive: true });
157
+ const git = (args: string[]) => execFileAsync('git', args, { cwd: repoDir });
158
+ await git(['init', '-q']);
159
+ await git(['config', 'user.email', 'test@example.com']);
160
+ await git(['config', 'user.name', 'Test']);
161
+ await git(['checkout', '-q', '-b', 'feat/x']);
162
+ await fs.writeFile(path.join(repoDir, 'f.txt'), 'hi');
163
+ await git(['add', '.']);
164
+ await git(['commit', '-q', '-m', 'init']);
165
+ });
166
+
167
+ afterAll(async () => {
168
+ await fs.rm(tmp, { recursive: true, force: true });
169
+ });
170
+
171
+ it('captures the live branch + commit for each repo', async () => {
172
+ const metadata: WorkspaceMetadata = {
173
+ workspaceName: 'demo',
174
+ createdAt: 'now',
175
+ repositories: [
176
+ { name: 'web', directoryName: 'web', owner: 'acme', clonedAt: 'now', cloneUrl: 'git@github.com:acme/web.git', status: 'success' },
177
+ ],
178
+ };
179
+ const lock = await buildLock(tmp, metadata);
180
+ expect(lock.version).toBe(LOCK_VERSION);
181
+ expect(lock.workspace).toBe('demo');
182
+ expect(lock.repositories).toHaveLength(1);
183
+ const [r] = lock.repositories;
184
+ expect(r.branch).toBe('feat/x');
185
+ expect(r.commit).toMatch(/^[0-9a-f]{7,}$/);
186
+ });
187
+
188
+ it('skips repos whose clone failed', async () => {
189
+ const metadata: WorkspaceMetadata = {
190
+ workspaceName: 'demo',
191
+ createdAt: 'now',
192
+ repositories: [
193
+ { name: 'web', directoryName: 'web', owner: 'acme', clonedAt: 'now', cloneUrl: 'x', status: 'success' },
194
+ { name: 'gone', directoryName: 'gone', owner: 'acme', clonedAt: 'now', cloneUrl: 'x', status: 'failed', error: 'nope' },
195
+ ],
196
+ };
197
+ const lock = await buildLock(tmp, metadata);
198
+ expect(lock.repositories.map((r: LockRepo) => r.name)).toEqual(['web']);
199
+ });
200
+ });