@zookanalytics/agent-env 0.1.1 → 0.1.3

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.
package/dist/cli.js CHANGED
@@ -34,12 +34,15 @@ var execute = createExecutor();
34
34
  // src/cli.ts
35
35
  import { program } from "commander";
36
36
  import { render as render2 } from "ink";
37
- import React2 from "react";
37
+ import { existsSync } from "fs";
38
+ import { dirname as dirname3, resolve } from "path";
39
+ import { fileURLToPath as fileURLToPath2 } from "url";
40
+ import React3 from "react";
38
41
 
39
42
  // package.json
40
43
  var package_default = {
41
44
  name: "@zookanalytics/agent-env",
42
- version: "0.1.1",
45
+ version: "0.1.3",
43
46
  description: "CLI for creating isolated, AI-ready development environments",
44
47
  type: "module",
45
48
  bin: {
@@ -51,6 +54,11 @@ var package_default = {
51
54
  import: "./dist/cli.js"
52
55
  }
53
56
  },
57
+ repository: {
58
+ type: "git",
59
+ url: "https://github.com/zookanalytics/bmad-orchestrator",
60
+ directory: "packages/agent-env"
61
+ },
54
62
  engines: {
55
63
  node: ">=20"
56
64
  },
@@ -73,6 +81,7 @@ var package_default = {
73
81
  },
74
82
  dependencies: {
75
83
  "@inkjs/ui": "^2.0.0",
84
+ chalk: "^5.3.0",
76
85
  commander: "^14.0.2",
77
86
  execa: "^9.6.1",
78
87
  ink: "^6.6.0",
@@ -100,6 +109,8 @@ import { homedir as homedir3 } from "os";
100
109
  var DEVCONTAINER_UP_TIMEOUT = 12e4;
101
110
  var DOCKER_INSPECT_TIMEOUT = 1e4;
102
111
  var DOCKER_INFO_TIMEOUT = 5e3;
112
+ var DOCKER_STOP_TIMEOUT = 3e4;
113
+ var DOCKER_RM_TIMEOUT = 1e4;
103
114
  function createContainerLifecycle(executor = createExecutor()) {
104
115
  async function isDockerAvailable() {
105
116
  const result = await executor("docker", ["info"], { timeout: DOCKER_INFO_TIMEOUT });
@@ -168,6 +179,26 @@ function createContainerLifecycle(executor = createExecutor()) {
168
179
  const name = result.stdout.trim().replace(/^\//, "");
169
180
  return name || null;
170
181
  }
182
+ async function findContainerByWorkspaceLabel(workspacePath) {
183
+ const result = await executor(
184
+ "docker",
185
+ [
186
+ "ps",
187
+ "-a",
188
+ "--filter",
189
+ // Quote the label value to prevent parsing issues with special characters like commas
190
+ `label=devcontainer.local_folder="${workspacePath}"`,
191
+ "--format",
192
+ "{{.Names}}"
193
+ ],
194
+ { timeout: DOCKER_INSPECT_TIMEOUT }
195
+ );
196
+ if (!result.ok) {
197
+ return null;
198
+ }
199
+ const name = result.stdout.trim().split("\n")[0]?.trim();
200
+ return name || null;
201
+ }
171
202
  async function devcontainerUp(workspacePath, containerName) {
172
203
  const dockerOk = await isDockerAvailable();
173
204
  if (!dockerOk) {
@@ -199,7 +230,14 @@ function createContainerLifecycle(executor = createExecutor()) {
199
230
  }
200
231
  }
201
232
  if (!result.ok) {
202
- const details = parsedOutput?.message || parsedOutput?.description || result.stderr || result.stdout.slice(0, 500) || "No error details available";
233
+ const parts = [];
234
+ if (parsedOutput?.message) parts.push(parsedOutput.message);
235
+ if (parsedOutput?.description) parts.push(parsedOutput.description);
236
+ if (result.stderr) parts.push(result.stderr);
237
+ if (parts.length === 0 && result.stdout) parts.push(result.stdout.slice(0, 1e3));
238
+ const details = parts.join("\n ") || "No error details available";
239
+ const combined = `${result.stderr} ${result.stdout}`;
240
+ const isNameConflict = combined.includes("is already in use") || combined.includes("name is already in use") || combined.includes("Conflict.") || combined.includes("conflict");
203
241
  return {
204
242
  ok: false,
205
243
  status: "not-found",
@@ -208,7 +246,7 @@ function createContainerLifecycle(executor = createExecutor()) {
208
246
  code: "CONTAINER_ERROR",
209
247
  message: `devcontainer up failed for '${containerName}':
210
248
  ${details}`,
211
- suggestion: "Check the devcontainer.json configuration and Docker logs."
249
+ suggestion: isNameConflict ? "A container with this name already exists. Use `docker ps -a` to find it, then `docker rm -f <name>` to remove it and retry." : "Check the devcontainer.json configuration and Docker logs."
212
250
  }
213
251
  };
214
252
  }
@@ -219,11 +257,51 @@ function createContainerLifecycle(executor = createExecutor()) {
219
257
  containerId
220
258
  };
221
259
  }
260
+ async function containerStop(containerName) {
261
+ const result = await executor("docker", ["stop", containerName], {
262
+ timeout: DOCKER_STOP_TIMEOUT
263
+ });
264
+ if (result.ok) {
265
+ return { ok: true };
266
+ }
267
+ if (result.stderr.includes("No such") || result.stderr.includes("not found") || result.stderr.includes("is not running")) {
268
+ return { ok: true };
269
+ }
270
+ return {
271
+ ok: false,
272
+ error: {
273
+ code: "CONTAINER_STOP_TIMEOUT",
274
+ message: `Failed to stop container '${containerName}': ${result.stderr}`,
275
+ suggestion: `Try manually: docker rm -f ${containerName}`
276
+ }
277
+ };
278
+ }
279
+ async function containerRemove(containerName) {
280
+ const result = await executor("docker", ["rm", containerName], {
281
+ timeout: DOCKER_RM_TIMEOUT
282
+ });
283
+ if (result.ok) {
284
+ return { ok: true };
285
+ }
286
+ if (result.stderr.includes("No such") || result.stderr.includes("not found")) {
287
+ return { ok: true };
288
+ }
289
+ return {
290
+ ok: false,
291
+ error: {
292
+ code: "CONTAINER_ERROR",
293
+ message: `Failed to remove container '${containerName}': ${result.stderr}`
294
+ }
295
+ };
296
+ }
222
297
  return {
223
298
  isDockerAvailable,
224
299
  containerStatus,
225
300
  getContainerNameById,
226
- devcontainerUp
301
+ findContainerByWorkspaceLabel,
302
+ devcontainerUp,
303
+ containerStop,
304
+ containerRemove
227
305
  };
228
306
  }
229
307
 
@@ -235,12 +313,12 @@ import {
235
313
  readdir as readdir3,
236
314
  readFile as readFile3,
237
315
  rename as rename2,
238
- rm,
316
+ rm as rm2,
239
317
  stat as stat3,
240
318
  writeFile as writeFile3
241
319
  } from "fs/promises";
242
320
  import { homedir as homedir2 } from "os";
243
- import { dirname as dirname3 } from "path";
321
+ import { dirname as dirname2 } from "path";
244
322
 
245
323
  // src/lib/devcontainer.ts
246
324
  import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
@@ -290,8 +368,8 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
290
368
  await deps.mkdir(targetDir, { recursive: true });
291
369
  await deps.cp(baselinePath, targetDir, { recursive: true });
292
370
  }
293
- async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps) {
294
- const configPath = join(workspacePath, DEVCONTAINER_DIR, DEVCONTAINER_JSON);
371
+ async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
372
+ const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
295
373
  const content = await deps.readFile(configPath, "utf-8");
296
374
  const config = JSON.parse(content);
297
375
  const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
@@ -299,10 +377,15 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
299
377
  config.runArgs = [...filtered, `--name=${containerName}`];
300
378
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
301
379
  }
380
+ async function listBaselineFiles(deps = defaultFsDeps) {
381
+ const baselinePath = getBaselineConfigPath();
382
+ const entries = await deps.readdir(baselinePath);
383
+ return entries.sort();
384
+ }
302
385
 
303
386
  // src/lib/state.ts
304
387
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
305
- import { dirname as dirname2, join as join2 } from "path";
388
+ import { join as join2 } from "path";
306
389
 
307
390
  // src/lib/types.ts
308
391
  var AGENT_ENV_DIR = ".agent-env";
@@ -339,13 +422,14 @@ async function readState(wsPath, deps = defaultStateFsDeps) {
339
422
  }
340
423
  }
341
424
  async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
342
- const tmpPath = join2(dirname2(wsPath.stateFile), STATE_FILE_TMP);
343
- await deps.mkdir(dirname2(wsPath.stateFile), { recursive: true });
425
+ const tmpPath = join2(wsPath.agentEnvDir, STATE_FILE_TMP);
426
+ await deps.mkdir(wsPath.agentEnvDir, { recursive: true });
344
427
  const content = JSON.stringify(state, null, 2) + "\n";
345
428
  await deps.writeFile(tmpPath, content, "utf-8");
346
429
  await deps.rename(tmpPath, wsPath.stateFile);
347
430
  }
348
- function createInitialState(name, repo, containerName) {
431
+ function createInitialState(name, repo, options) {
432
+ const { containerName, configSource } = options ?? {};
349
433
  const now = (/* @__PURE__ */ new Date()).toISOString();
350
434
  return {
351
435
  name,
@@ -353,7 +437,8 @@ function createInitialState(name, repo, containerName) {
353
437
  createdAt: now,
354
438
  lastAttached: now,
355
439
  purpose: null,
356
- containerName: containerName ?? `${CONTAINER_PREFIX}${name}`
440
+ containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
441
+ configSource: configSource ?? "baseline"
357
442
  };
358
443
  }
359
444
  function isValidState(value) {
@@ -382,7 +467,7 @@ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
382
467
  }
383
468
 
384
469
  // src/lib/workspace.ts
385
- import { mkdir as mkdir3, readdir as readdir2, stat as stat2 } from "fs/promises";
470
+ import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2 } from "fs/promises";
386
471
  import { homedir } from "os";
387
472
  import { join as join3 } from "path";
388
473
  var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
@@ -445,6 +530,10 @@ async function scanWorkspaces(deps = defaultFsDeps2) {
445
530
  throw err;
446
531
  }
447
532
  }
533
+ var defaultDeleteFsDeps = { rm };
534
+ async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
535
+ await deps.rm(wsPath.root, { recursive: true, force: true });
536
+ }
448
537
 
449
538
  // src/lib/create-instance.ts
450
539
  var GIT_CLONE_TIMEOUT = 12e4;
@@ -518,7 +607,11 @@ function createDefaultDeps() {
518
607
  workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
519
608
  stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
520
609
  devcontainerFsDeps: { cp: cp2, mkdir: mkdir4, readFile: readFile3, stat: stat3, writeFile: writeFile3 },
521
- rm
610
+ rm: rm2,
611
+ logger: {
612
+ warn: (msg) => console.warn(msg),
613
+ info: (msg) => console.info(msg)
614
+ }
522
615
  };
523
616
  }
524
617
  async function createInstance(instanceName, repoUrl, deps) {
@@ -548,12 +641,23 @@ async function createInstance(instanceName, repoUrl, deps) {
548
641
  }
549
642
  };
550
643
  }
551
- await deps.workspaceFsDeps.mkdir(dirname3(wsPath.root), { recursive: true });
644
+ try {
645
+ await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
646
+ } catch (err) {
647
+ return {
648
+ ok: false,
649
+ error: {
650
+ code: "WORKSPACE_ERROR",
651
+ message: `Failed to create workspace directory: ${err instanceof Error ? err.message : String(err)}`,
652
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
653
+ }
654
+ };
655
+ }
552
656
  const cloneResult = await deps.executor("git", ["clone", repoUrl, wsPath.root], {
553
657
  timeout: GIT_CLONE_TIMEOUT
554
658
  });
555
659
  if (!cloneResult.ok) {
556
- await safeRollback(wsPath.root, deps.rm);
660
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
557
661
  return {
558
662
  ok: false,
559
663
  error: {
@@ -563,13 +667,26 @@ async function createInstance(instanceName, repoUrl, deps) {
563
667
  }
564
668
  };
565
669
  }
566
- await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
670
+ try {
671
+ await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
672
+ } catch (err) {
673
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
674
+ return {
675
+ ok: false,
676
+ error: {
677
+ code: "WORKSPACE_ERROR",
678
+ message: `Failed to create .agent-env directory: ${err instanceof Error ? err.message : String(err)}`,
679
+ suggestion: "Check filesystem permissions in the cloned workspace directory."
680
+ }
681
+ };
682
+ }
567
683
  const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
684
+ let configSource = "baseline";
568
685
  if (!hasConfig) {
569
686
  try {
570
687
  await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
571
688
  } catch (err) {
572
- await safeRollback(wsPath.root, deps.rm);
689
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
573
690
  return {
574
691
  ok: false,
575
692
  error: {
@@ -581,7 +698,7 @@ async function createInstance(instanceName, repoUrl, deps) {
581
698
  try {
582
699
  await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
583
700
  } catch (err) {
584
- await safeRollback(wsPath.root, deps.rm);
701
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
585
702
  return {
586
703
  ok: false,
587
704
  error: {
@@ -590,10 +707,25 @@ async function createInstance(instanceName, repoUrl, deps) {
590
707
  }
591
708
  };
592
709
  }
710
+ } else {
711
+ configSource = "repo";
712
+ }
713
+ const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
714
+ if (existingContainer) {
715
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
716
+ return {
717
+ ok: false,
718
+ error: {
719
+ code: "CONTAINER_EXISTS",
720
+ message: `A container '${existingContainer}' already exists for this workspace path.`,
721
+ suggestion: `Remove it first with: docker rm -f ${existingContainer}`
722
+ }
723
+ };
593
724
  }
594
725
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
595
726
  if (!containerResult.ok) {
596
- await safeRollback(wsPath.root, deps.rm);
727
+ deps.logger?.warn(`Rolling back workspace at ${wsPath.root} due to container startup failure.`);
728
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
597
729
  return {
598
730
  ok: false,
599
731
  error: containerResult.error ?? {
@@ -609,11 +741,14 @@ async function createInstance(instanceName, repoUrl, deps) {
609
741
  actualContainerName = discovered;
610
742
  }
611
743
  } else {
612
- console.warn(
744
+ deps.logger?.warn(
613
745
  `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
614
746
  );
615
747
  }
616
- const state = createInitialState(wsPath.name, repoUrl, actualContainerName);
748
+ const state = createInitialState(wsPath.name, repoUrl, {
749
+ containerName: actualContainerName,
750
+ configSource
751
+ });
617
752
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
618
753
  await ensureGitExclude(wsPath.root, deps.stateFsDeps);
619
754
  return {
@@ -622,11 +757,11 @@ async function createInstance(instanceName, repoUrl, deps) {
622
757
  containerName: actualContainerName
623
758
  };
624
759
  }
625
- async function safeRollback(workspacePath, rmFn) {
760
+ async function safeRollback(workspacePath, rmFn, logger) {
626
761
  try {
627
762
  await rmFn(workspacePath, { recursive: true, force: true });
628
763
  } catch {
629
- console.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
764
+ logger?.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
630
765
  }
631
766
  }
632
767
 
@@ -654,7 +789,7 @@ async function findWorkspaceByName(instanceName, deps) {
654
789
  }
655
790
  return { found: false, reason: "not-found" };
656
791
  }
657
- async function attachInstance(instanceName, deps, onContainerStarting) {
792
+ async function attachInstance(instanceName, deps, onContainerStarting, onAttaching) {
658
793
  const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
659
794
  if (!lookup.found) {
660
795
  if (lookup.reason === "ambiguous") {
@@ -714,6 +849,7 @@ async function attachInstance(instanceName, deps, onContainerStarting) {
714
849
  };
715
850
  }
716
851
  }
852
+ onAttaching?.();
717
853
  const attachResult = await attachToInstance(containerName, deps.executor);
718
854
  if (!attachResult.ok) {
719
855
  return attachResult;
@@ -729,9 +865,17 @@ async function attachInstance(instanceName, deps, onContainerStarting) {
729
865
  // src/commands/attach.ts
730
866
  var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").action(async (name) => {
731
867
  const deps = createAttachDefaultDeps();
732
- const result = await attachInstance(name, deps, () => {
733
- console.log("Starting container...");
734
- });
868
+ const result = await attachInstance(
869
+ name,
870
+ deps,
871
+ () => {
872
+ console.log("Starting container...");
873
+ },
874
+ () => {
875
+ console.log();
876
+ console.log("Attaching to tmux session...");
877
+ }
878
+ );
735
879
  if (!result.ok) {
736
880
  const { code, message, suggestion } = result.error;
737
881
  console.error(formatError(createError(code, message, suggestion)));
@@ -951,6 +1095,7 @@ var createCommand = new Command3("create").description("Create a new isolated de
951
1095
  console.log(` Workspace: ${workspacePath.root}`);
952
1096
  console.log(` Container: ${containerName}`);
953
1097
  if (options.attach) {
1098
+ console.log();
954
1099
  console.log("Attaching to instance...");
955
1100
  const attachResult = await attachToInstance(containerName, deps.executor);
956
1101
  if (!attachResult.ok) {
@@ -1120,17 +1265,22 @@ function createGitStateDetector(executor = createExecutor()) {
1120
1265
  }
1121
1266
  };
1122
1267
  }
1123
- const { hasStaged, hasUnstaged, hasUntracked } = parseStatus(status.stdout);
1124
- const stashCount = parseStashCount(stash);
1125
- const { unpushedBranches, neverPushedBranches } = parseBranches(branch);
1268
+ const { hasStaged, stagedCount, hasUnstaged, unstagedCount, hasUntracked, untrackedCount } = parseStatus(status.stdout);
1269
+ const { stashCount, firstStashMessage } = parseStash(stash);
1270
+ const { unpushedBranches, unpushedCommitCounts, neverPushedBranches } = parseBranches(branch);
1126
1271
  const isDetachedHead = !head || !head.ok;
1127
1272
  const isClean = !hasStaged && !hasUnstaged && !hasUntracked && stashCount === 0 && unpushedBranches.length === 0 && neverPushedBranches.length === 0 && !isDetachedHead;
1128
1273
  const state = {
1129
1274
  hasStaged,
1275
+ stagedCount,
1130
1276
  hasUnstaged,
1277
+ unstagedCount,
1131
1278
  hasUntracked,
1279
+ untrackedCount,
1132
1280
  stashCount,
1281
+ firstStashMessage,
1133
1282
  unpushedBranches,
1283
+ unpushedCommitCounts,
1134
1284
  neverPushedBranches,
1135
1285
  isDetachedHead,
1136
1286
  isClean
@@ -1140,40 +1290,64 @@ function createGitStateDetector(executor = createExecutor()) {
1140
1290
  return { getGitState };
1141
1291
  }
1142
1292
  function parseStatus(stdout) {
1143
- let hasStaged = false;
1144
- let hasUnstaged = false;
1145
- let hasUntracked = false;
1293
+ let stagedCount = 0;
1294
+ let unstagedCount = 0;
1295
+ let untrackedCount = 0;
1146
1296
  if (!stdout.trim()) {
1147
- return { hasStaged, hasUnstaged, hasUntracked };
1297
+ return {
1298
+ hasStaged: false,
1299
+ stagedCount: 0,
1300
+ hasUnstaged: false,
1301
+ unstagedCount: 0,
1302
+ hasUntracked: false,
1303
+ untrackedCount: 0
1304
+ };
1148
1305
  }
1149
1306
  for (const line of stdout.split("\n")) {
1150
1307
  if (!line || line.length < 2) continue;
1151
1308
  if (line.startsWith("??")) {
1152
- hasUntracked = true;
1309
+ untrackedCount++;
1310
+ continue;
1311
+ }
1312
+ if (line.startsWith("!!")) {
1153
1313
  continue;
1154
1314
  }
1155
1315
  const indexStatus = line[0];
1156
1316
  const workTreeStatus = line[1];
1157
1317
  if ("MADRC".includes(indexStatus)) {
1158
- hasStaged = true;
1318
+ stagedCount++;
1159
1319
  }
1160
1320
  if (workTreeStatus !== " ") {
1161
- hasUnstaged = true;
1321
+ unstagedCount++;
1162
1322
  }
1163
1323
  }
1164
- return { hasStaged, hasUnstaged, hasUntracked };
1324
+ return {
1325
+ hasStaged: stagedCount > 0,
1326
+ stagedCount,
1327
+ hasUnstaged: unstagedCount > 0,
1328
+ unstagedCount,
1329
+ hasUntracked: untrackedCount > 0,
1330
+ untrackedCount
1331
+ };
1165
1332
  }
1166
- function parseStashCount(result) {
1333
+ function parseStash(result) {
1167
1334
  if (!result || !result.ok || !result.stdout.trim()) {
1168
- return 0;
1335
+ return { stashCount: 0, firstStashMessage: "" };
1336
+ }
1337
+ const lines = result.stdout.trim().split("\n");
1338
+ let firstStashMessage = "";
1339
+ if (lines[0]) {
1340
+ const colonIndex = lines[0].indexOf(": ");
1341
+ firstStashMessage = colonIndex !== -1 ? lines[0].slice(colonIndex + 2) : lines[0];
1169
1342
  }
1170
- return result.stdout.trim().split("\n").length;
1343
+ return { stashCount: lines.length, firstStashMessage };
1171
1344
  }
1172
1345
  function parseBranches(result) {
1173
1346
  const unpushedBranches = [];
1347
+ const unpushedCommitCounts = {};
1174
1348
  const neverPushedBranches = [];
1175
1349
  if (!result || !result.ok || !result.stdout.trim()) {
1176
- return { unpushedBranches, neverPushedBranches };
1350
+ return { unpushedBranches, unpushedCommitCounts, neverPushedBranches };
1177
1351
  }
1178
1352
  for (const line of result.stdout.trim().split("\n")) {
1179
1353
  if (!line.trim()) continue;
@@ -1183,10 +1357,13 @@ function parseBranches(result) {
1183
1357
  if (parts.length === 1) {
1184
1358
  neverPushedBranches.push(branchName);
1185
1359
  } else if (trackInfo.includes("[ahead")) {
1360
+ const aheadMatch = trackInfo.match(/\[ahead (\d+)/);
1361
+ const count = aheadMatch ? parseInt(aheadMatch[1], 10) : 0;
1186
1362
  unpushedBranches.push(branchName);
1363
+ unpushedCommitCounts[branchName] = count;
1187
1364
  }
1188
1365
  }
1189
- return { unpushedBranches, neverPushedBranches };
1366
+ return { unpushedBranches, unpushedCommitCounts, neverPushedBranches };
1190
1367
  }
1191
1368
 
1192
1369
  // src/lib/list-instances.ts
@@ -1372,24 +1549,671 @@ var purposeCommand = new Command5("purpose").description("Get or set the purpose
1372
1549
  }
1373
1550
  });
1374
1551
 
1375
- // src/commands/remove.ts
1552
+ // src/commands/rebuild.ts
1553
+ import chalk from "chalk";
1376
1554
  import { Command as Command6 } from "commander";
1377
- var removeCommand = new Command6("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--force", "Force removal, bypassing safety checks").action((name, _options) => {
1555
+ import { createInterface } from "readline";
1556
+
1557
+ // src/lib/rebuild-instance.ts
1558
+ import {
1559
+ cp as cp3,
1560
+ mkdir as mkdir7,
1561
+ readdir as readdir6,
1562
+ readFile as readFile6,
1563
+ rename as rename5,
1564
+ rm as rm3,
1565
+ stat as stat6,
1566
+ writeFile as writeFile6,
1567
+ appendFile as appendFile5
1568
+ } from "fs/promises";
1569
+ import { homedir as homedir5 } from "os";
1570
+ import { join as join4 } from "path";
1571
+ function createRebuildDefaultDeps() {
1572
+ const executor = createExecutor();
1573
+ return {
1574
+ executor,
1575
+ container: createContainerLifecycle(executor),
1576
+ workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
1577
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile6, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
1578
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile6, stat: stat6, writeFile: writeFile6 },
1579
+ rm: rm3,
1580
+ rename: rename5,
1581
+ logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
1582
+ };
1583
+ }
1584
+ async function refreshConfig(wsRoot, containerName, configSource, deps) {
1585
+ const devcontainerDir = join4(wsRoot, ".devcontainer");
1586
+ const tempDevcontainerDir = join4(wsRoot, ".devcontainer.new");
1587
+ if (configSource === "baseline") {
1588
+ try {
1589
+ try {
1590
+ const currentFiles = await deps.devcontainerFsDeps.readdir(devcontainerDir);
1591
+ const baselineFiles = await listBaselineFiles(deps.devcontainerFsDeps);
1592
+ const baselineSet = new Set(baselineFiles);
1593
+ const extras = currentFiles.filter((f) => !baselineSet.has(f));
1594
+ if (extras.length > 0) {
1595
+ deps.logger?.warn(`Extra files in .devcontainer/ will be deleted: ${extras.join(", ")}`);
1596
+ }
1597
+ } catch {
1598
+ }
1599
+ await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
1600
+ await deps.devcontainerFsDeps.mkdir(tempDevcontainerDir, { recursive: true });
1601
+ await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), tempDevcontainerDir, {
1602
+ recursive: true
1603
+ });
1604
+ await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, ".devcontainer.new");
1605
+ await deps.rm(devcontainerDir, { recursive: true, force: true });
1606
+ await deps.rename(tempDevcontainerDir, devcontainerDir);
1607
+ } catch (err) {
1608
+ await deps.rm(tempDevcontainerDir, { recursive: true, force: true });
1609
+ return {
1610
+ ok: false,
1611
+ error: {
1612
+ code: "CONFIG_REFRESH_FAILED",
1613
+ message: `Failed to refresh baseline config: ${err instanceof Error ? err.message : String(err)}`,
1614
+ suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
1615
+ }
1616
+ };
1617
+ }
1618
+ } else {
1619
+ const configExists = await hasDevcontainerConfig(wsRoot, deps.devcontainerFsDeps);
1620
+ if (!configExists) {
1621
+ return {
1622
+ ok: false,
1623
+ error: {
1624
+ code: "CONFIG_MISSING",
1625
+ message: "Repo-provided devcontainer config is missing.",
1626
+ suggestion: "Re-clone the repository or provide a devcontainer config manually."
1627
+ }
1628
+ };
1629
+ }
1630
+ const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
1631
+ if (dirExists) {
1632
+ const jsonExists = await deps.devcontainerFsDeps.stat(join4(devcontainerDir, "devcontainer.json")).catch(() => null);
1633
+ if (!jsonExists) {
1634
+ return {
1635
+ ok: false,
1636
+ error: {
1637
+ code: "CONFIG_CORRUPT",
1638
+ message: "Repo-provided devcontainer config is incomplete (missing devcontainer.json).",
1639
+ suggestion: "Ensure .devcontainer/devcontainer.json exists."
1640
+ }
1641
+ };
1642
+ }
1643
+ }
1644
+ }
1645
+ return { ok: true };
1646
+ }
1647
+ async function rebuildInstance(instanceName, deps, force = false, overrideConfigSource) {
1648
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1649
+ if (!lookup.found) {
1650
+ if (lookup.reason === "ambiguous") {
1651
+ return {
1652
+ ok: false,
1653
+ error: {
1654
+ code: "AMBIGUOUS_MATCH",
1655
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1656
+ suggestion: "Use the full workspace name to specify which instance."
1657
+ }
1658
+ };
1659
+ }
1660
+ return {
1661
+ ok: false,
1662
+ error: {
1663
+ code: "WORKSPACE_NOT_FOUND",
1664
+ message: `Instance '${instanceName}' not found`,
1665
+ suggestion: "Use `agent-env list` to see available instances."
1666
+ }
1667
+ };
1668
+ }
1669
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1670
+ const state = await readState(wsPath, deps.stateFsDeps);
1671
+ const containerName = state.containerName;
1672
+ const dockerAvailable = await deps.container.isDockerAvailable();
1673
+ if (!dockerAvailable) {
1674
+ return {
1675
+ ok: false,
1676
+ error: {
1677
+ code: "ORBSTACK_REQUIRED",
1678
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
1679
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
1680
+ }
1681
+ };
1682
+ }
1683
+ const configSource = overrideConfigSource ?? state.configSource;
1684
+ if (!configSource) {
1685
+ return {
1686
+ ok: false,
1687
+ error: {
1688
+ code: "CONFIG_SOURCE_UNKNOWN",
1689
+ message: `Instance '${instanceName}' was created before config tracking was added.`,
1690
+ suggestion: 'Set configSource manually in .agent-env/state.json ("baseline" or "repo"), then retry.'
1691
+ }
1692
+ };
1693
+ }
1694
+ const configResult = await refreshConfig(wsPath.root, containerName, configSource, deps);
1695
+ if (!configResult.ok) {
1696
+ return { ok: false, error: configResult.error };
1697
+ }
1698
+ const statusResult = await deps.container.containerStatus(containerName);
1699
+ const wasRunning = statusResult.ok && statusResult.status === "running";
1700
+ if (wasRunning && !force) {
1701
+ return {
1702
+ ok: false,
1703
+ error: {
1704
+ code: "CONTAINER_RUNNING",
1705
+ message: `Container '${containerName}' is currently running`,
1706
+ suggestion: "Stop any active sessions first, or use --force to rebuild a running container."
1707
+ },
1708
+ wasRunning: true
1709
+ };
1710
+ }
1711
+ if (statusResult.ok && statusResult.status !== "not-found") {
1712
+ const stopResult = await deps.container.containerStop(containerName);
1713
+ if (!stopResult.ok) {
1714
+ return {
1715
+ ok: false,
1716
+ error: stopResult.error,
1717
+ wasRunning
1718
+ };
1719
+ }
1720
+ }
1721
+ if (statusResult.ok && statusResult.status !== "not-found") {
1722
+ const removeResult = await deps.container.containerRemove(containerName);
1723
+ if (!removeResult.ok) {
1724
+ return {
1725
+ ok: false,
1726
+ error: removeResult.error,
1727
+ wasRunning
1728
+ };
1729
+ }
1730
+ }
1731
+ const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
1732
+ if (!containerResult.ok) {
1733
+ return {
1734
+ ok: false,
1735
+ error: containerResult.error,
1736
+ wasRunning
1737
+ };
1738
+ }
1739
+ let actualContainerName = containerName;
1740
+ if (containerResult.containerId) {
1741
+ const discovered = await deps.container.getContainerNameById(containerResult.containerId);
1742
+ if (discovered) {
1743
+ actualContainerName = discovered;
1744
+ }
1745
+ }
1746
+ const updatedState = {
1747
+ ...state,
1748
+ containerName: actualContainerName,
1749
+ lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
1750
+ };
1751
+ await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1752
+ return {
1753
+ ok: true,
1754
+ containerName: actualContainerName,
1755
+ wasRunning
1756
+ };
1757
+ }
1758
+
1759
+ // src/commands/rebuild.ts
1760
+ function promptForConfirmation(instanceName) {
1761
+ return new Promise((resolve2) => {
1762
+ const rl = createInterface({
1763
+ input: process.stdin,
1764
+ output: process.stderr
1765
+ });
1766
+ rl.question(
1767
+ `
1768
+ ${chalk.yellow("Warning:")} Rebuilding '${instanceName}' will destroy the current container and create a new one.
1769
+ Any active sessions will be lost. Continue? (y/N) `,
1770
+ (answer) => {
1771
+ rl.close();
1772
+ resolve2(answer.toLowerCase() === "y" || answer.toLowerCase() === "yes");
1773
+ }
1774
+ );
1775
+ rl.on("SIGINT", () => {
1776
+ rl.close();
1777
+ resolve2(false);
1778
+ });
1779
+ });
1780
+ }
1781
+ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by recreating its container").argument("<name>", "Instance name to rebuild").option("--force", "Rebuild even if the container is currently running").option("--yes", "Skip confirmation prompt").action(async (name, options) => {
1782
+ const deps = createRebuildDefaultDeps();
1783
+ let confirmed = false;
1784
+ if (!options.yes && !options.force && process.stdin.isTTY) {
1785
+ confirmed = await promptForConfirmation(name);
1786
+ if (!confirmed) {
1787
+ console.log("Rebuild cancelled");
1788
+ return;
1789
+ }
1790
+ }
1791
+ const force = options.force || options.yes || confirmed;
1792
+ if (force) {
1793
+ console.log(`Force-rebuilding instance '${name}'...`);
1794
+ } else {
1795
+ console.log(`Rebuilding instance '${name}'...`);
1796
+ }
1797
+ const result = await rebuildInstance(name, deps, force);
1798
+ if (!result.ok) {
1799
+ if (result.error.code === "CONTAINER_RUNNING") {
1800
+ console.error("");
1801
+ console.error(
1802
+ chalk.yellow("Container is currently running.") + " Active sessions will be terminated during rebuild."
1803
+ );
1804
+ console.error("");
1805
+ console.error(`Use ${chalk.bold("--force")} to rebuild anyway.`);
1806
+ } else {
1807
+ const { code, message, suggestion } = result.error;
1808
+ console.error(formatError(createError(code, message, suggestion)));
1809
+ }
1810
+ process.exit(1);
1811
+ return;
1812
+ }
1813
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${name}' rebuilt successfully`);
1814
+ console.log(` Container: ${result.containerName}`);
1815
+ });
1816
+
1817
+ // src/commands/remove.ts
1818
+ import chalk3 from "chalk";
1819
+ import { Command as Command7 } from "commander";
1820
+ import { createInterface as createInterface2 } from "readline";
1821
+
1822
+ // src/lib/audit-log.ts
1823
+ import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
1824
+ import { homedir as homedir6 } from "os";
1825
+ import { join as join5 } from "path";
1826
+ function createAuditLogDefaultDeps() {
1827
+ return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
1828
+ }
1829
+ function getAuditLogPath(deps) {
1830
+ return join5(deps.homedir(), AGENT_ENV_DIR, "audit.log");
1831
+ }
1832
+ async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
1833
+ const logPath = getAuditLogPath(deps);
1834
+ await deps.mkdir(join5(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
1835
+ const line = JSON.stringify(entry) + "\n";
1836
+ await deps.appendFile(logPath, line, "utf-8");
1837
+ }
1838
+ function createAuditEntry(instanceName, gitState, confirmationMethod) {
1839
+ return {
1840
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1841
+ action: "force-remove",
1842
+ instanceName,
1843
+ gitState,
1844
+ confirmationMethod
1845
+ };
1846
+ }
1847
+
1848
+ // src/lib/remove-instance.ts
1849
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile7, rm as rm4, stat as stat7 } from "fs/promises";
1850
+ import { homedir as homedir7 } from "os";
1851
+ function createRemoveDefaultDeps() {
1852
+ const executor = createExecutor();
1853
+ return {
1854
+ executor,
1855
+ container: createContainerLifecycle(executor),
1856
+ gitDetector: createGitStateDetector(executor),
1857
+ workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
1858
+ stateFsDeps: { readFile: readFile7 },
1859
+ deleteFsDeps: { rm: rm4 }
1860
+ };
1861
+ }
1862
+ function evaluateSafetyChecks(gitState) {
1863
+ const blockers = [];
1864
+ if (gitState.hasStaged) {
1865
+ const count = gitState.stagedCount;
1866
+ blockers.push(`${count} staged ${count === 1 ? "file" : "files"} detected`);
1867
+ }
1868
+ if (gitState.hasUnstaged) {
1869
+ const count = gitState.unstagedCount;
1870
+ blockers.push(`${count} unstaged ${count === 1 ? "change" : "changes"} detected`);
1871
+ }
1872
+ if (gitState.hasUntracked) {
1873
+ const count = gitState.untrackedCount;
1874
+ blockers.push(`${count} untracked ${count === 1 ? "file" : "files"} detected`);
1875
+ }
1876
+ if (gitState.stashCount > 0) {
1877
+ const stashLabel = `${gitState.stashCount} stash${gitState.stashCount === 1 ? "" : "es"}`;
1878
+ const message = gitState.firstStashMessage ? ` \u2014 "${gitState.firstStashMessage}"` : "";
1879
+ blockers.push(`stashed changes detected (${stashLabel}${message})`);
1880
+ }
1881
+ if (gitState.unpushedBranches.length > 0) {
1882
+ const branchDetails = gitState.unpushedBranches.map((b) => {
1883
+ const count = gitState.unpushedCommitCounts[b];
1884
+ return count ? `${b} (${count} ${count === 1 ? "commit" : "commits"})` : b;
1885
+ }).join(", ");
1886
+ blockers.push(`unpushed commits on branches: ${branchDetails}`);
1887
+ }
1888
+ if (gitState.neverPushedBranches.length > 0) {
1889
+ blockers.push(`branches never pushed: ${gitState.neverPushedBranches.join(", ")}`);
1890
+ }
1891
+ if (gitState.isDetachedHead) {
1892
+ blockers.push("detached HEAD state (investigate manually)");
1893
+ }
1894
+ return blockers;
1895
+ }
1896
+ async function removeInstance(instanceName, deps, force = false) {
1897
+ const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1898
+ if (!lookup.found) {
1899
+ if (lookup.reason === "ambiguous") {
1900
+ return {
1901
+ ok: false,
1902
+ error: {
1903
+ code: "AMBIGUOUS_MATCH",
1904
+ message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1905
+ suggestion: "Use the full workspace name to specify which instance."
1906
+ }
1907
+ };
1908
+ }
1909
+ return {
1910
+ ok: false,
1911
+ error: {
1912
+ code: "WORKSPACE_NOT_FOUND",
1913
+ message: `Instance '${instanceName}' not found`,
1914
+ suggestion: "Use `agent-env list` to see available instances."
1915
+ }
1916
+ };
1917
+ }
1918
+ const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1919
+ const state = await readState(wsPath, deps.stateFsDeps);
1920
+ const containerName = state.containerName;
1921
+ const dockerAvailable = await deps.container.isDockerAvailable();
1922
+ if (!dockerAvailable) {
1923
+ return {
1924
+ ok: false,
1925
+ error: {
1926
+ code: "ORBSTACK_REQUIRED",
1927
+ message: "Docker is not available. OrbStack or Docker Desktop must be running.",
1928
+ suggestion: "Start OrbStack or Docker Desktop, then try again."
1929
+ }
1930
+ };
1931
+ }
1932
+ const gitResult = await deps.gitDetector.getGitState(wsPath.root);
1933
+ let detectedGitState;
1934
+ let detectedBlockers;
1935
+ if (!gitResult.ok) {
1936
+ if (!force) {
1937
+ return {
1938
+ ok: false,
1939
+ error: {
1940
+ code: "GIT_ERROR",
1941
+ message: `Failed to check git state: ${gitResult.error.message}`,
1942
+ suggestion: "Ensure the workspace contains a valid git repository."
1943
+ }
1944
+ };
1945
+ }
1946
+ } else {
1947
+ detectedGitState = gitResult.state;
1948
+ const blockers = evaluateSafetyChecks(gitResult.state);
1949
+ if (blockers.length > 0) {
1950
+ detectedBlockers = blockers;
1951
+ if (!force) {
1952
+ return {
1953
+ ok: false,
1954
+ error: {
1955
+ code: "SAFETY_CHECK_FAILED",
1956
+ message: "Safety checks failed",
1957
+ suggestion: "Resolve the issues above, or use --force to bypass safety checks."
1958
+ },
1959
+ gitState: gitResult.state,
1960
+ blockers
1961
+ };
1962
+ }
1963
+ }
1964
+ }
1965
+ let containerCleanupFailed = false;
1966
+ const stopResult = await deps.container.containerStop(containerName);
1967
+ if (!stopResult.ok) {
1968
+ if (force) {
1969
+ console.error(
1970
+ `Warning: Failed to stop container ${containerName}: ${stopResult.error.message}`
1971
+ );
1972
+ containerCleanupFailed = true;
1973
+ } else {
1974
+ return {
1975
+ ok: false,
1976
+ error: stopResult.error
1977
+ };
1978
+ }
1979
+ }
1980
+ const removeResult = await deps.container.containerRemove(containerName);
1981
+ if (!removeResult.ok) {
1982
+ if (force) {
1983
+ console.error(
1984
+ `Warning: Failed to remove container ${containerName}: ${removeResult.error.message}`
1985
+ );
1986
+ containerCleanupFailed = true;
1987
+ } else {
1988
+ return {
1989
+ ok: false,
1990
+ error: removeResult.error
1991
+ };
1992
+ }
1993
+ }
1994
+ try {
1995
+ await deleteWorkspace(wsPath, deps.deleteFsDeps);
1996
+ } catch (err) {
1997
+ return {
1998
+ ok: false,
1999
+ error: {
2000
+ code: "WORKSPACE_DELETE_FAILED",
2001
+ message: `Failed to delete workspace: ${err instanceof Error ? err.message : String(err)}`,
2002
+ suggestion: `Container was removed but workspace remains at ${wsPath.root}. Remove manually with: rm -rf ${wsPath.root}`
2003
+ }
2004
+ };
2005
+ }
2006
+ if (force) {
2007
+ return {
2008
+ ok: true,
2009
+ forced: true,
2010
+ gitState: detectedGitState,
2011
+ blockers: detectedBlockers,
2012
+ containerCleanupFailed
2013
+ };
2014
+ }
2015
+ return { ok: true };
2016
+ }
2017
+
2018
+ // src/lib/safety-report.ts
2019
+ import chalk2 from "chalk";
2020
+ var BLOCKER_NEVER_PUSHED = "never pushed";
2021
+ var BLOCKER_DETACHED_HEAD = "detached HEAD";
2022
+ function classifyBlocker(blocker) {
2023
+ if (blocker.includes(BLOCKER_NEVER_PUSHED) || blocker.includes(BLOCKER_DETACHED_HEAD)) {
2024
+ return "Danger";
2025
+ }
2026
+ return "Warning";
2027
+ }
2028
+ var SUGGESTION_CONFIG = [
2029
+ {
2030
+ condition: (gitState) => gitState.hasStaged,
2031
+ generator: () => "Run `git commit` to commit staged changes"
2032
+ },
2033
+ {
2034
+ condition: (gitState) => gitState.hasUnstaged,
2035
+ generator: () => "Run `git add` and `git commit` to save unstaged changes"
2036
+ },
2037
+ {
2038
+ condition: (gitState) => gitState.hasUntracked,
2039
+ generator: () => "Run `git add` to track untracked files, then commit"
2040
+ },
2041
+ {
2042
+ condition: (gitState) => gitState.stashCount > 0,
2043
+ generator: () => "Run `git stash pop` to apply stashed changes, or `git stash drop` to discard them"
2044
+ },
2045
+ {
2046
+ condition: (gitState) => gitState.unpushedBranches.length > 0,
2047
+ generator: (gitState) => `Run \`git push\` to push unpushed commits on: ${gitState.unpushedBranches.join(", ")}`
2048
+ },
2049
+ {
2050
+ condition: (gitState) => gitState.neverPushedBranches.length > 0,
2051
+ generator: (gitState) => `Run \`git push -u origin <branch>\` for never-pushed branches: ${gitState.neverPushedBranches.join(", ")}`
2052
+ },
2053
+ {
2054
+ condition: (gitState) => gitState.isDetachedHead,
2055
+ generator: () => "Run `git checkout <branch>` to reattach HEAD, or `git checkout -b <new-branch>` to save work"
2056
+ }
2057
+ ];
2058
+ function getSuggestions(gitState) {
2059
+ return SUGGESTION_CONFIG.filter((entry) => entry.condition(gitState)).map(
2060
+ (entry) => entry.generator(gitState)
2061
+ );
2062
+ }
2063
+ function formatSafetyReport(instanceName, blockers, gitState) {
2064
+ const lines = [];
2065
+ lines.push(`Cannot remove '${instanceName}' \u2014 safety checks failed:`);
2066
+ lines.push("");
2067
+ const items = blockers.map((blocker) => ({
2068
+ severity: classifyBlocker(blocker),
2069
+ message: blocker
2070
+ }));
2071
+ for (const item of items) {
2072
+ const prefix = item.severity === "Danger" ? chalk2.red("[Danger]") : chalk2.yellow("[Warning]");
2073
+ lines.push(` ${prefix} ${item.message}`);
2074
+ }
2075
+ const suggestions = getSuggestions(gitState);
2076
+ if (suggestions.length > 0) {
2077
+ lines.push("");
2078
+ lines.push(chalk2.bold("Suggestions:"));
2079
+ for (const suggestion of suggestions) {
2080
+ lines.push(` - ${suggestion}`);
2081
+ }
2082
+ }
2083
+ lines.push("");
2084
+ lines.push(chalk2.gray("Or use --force to bypass safety checks (data loss is permanent)."));
2085
+ return lines.join("\n");
2086
+ }
2087
+
2088
+ // src/commands/remove.ts
2089
+ function promptForConfirmation2(instanceName) {
2090
+ return new Promise((resolve2) => {
2091
+ let resolved = false;
2092
+ const rl = createInterface2({
2093
+ input: process.stdin,
2094
+ output: process.stderr
2095
+ });
2096
+ rl.question(`
2097
+ Type the instance name "${instanceName}" to confirm: `, (answer) => {
2098
+ if (!resolved) {
2099
+ resolved = true;
2100
+ rl.close();
2101
+ resolve2(answer);
2102
+ }
2103
+ });
2104
+ rl.on("close", () => {
2105
+ if (!resolved) {
2106
+ resolved = true;
2107
+ resolve2(null);
2108
+ }
2109
+ });
2110
+ });
2111
+ }
2112
+ async function writeAuditLog(name, gitState, confirmationMethod) {
2113
+ try {
2114
+ const auditDeps = createAuditLogDefaultDeps();
2115
+ const entry = createAuditEntry(name, gitState, confirmationMethod);
2116
+ await writeAuditLogEntry(entry, auditDeps);
2117
+ } catch {
2118
+ console.error("Warning: Failed to write audit log entry.");
2119
+ }
2120
+ }
2121
+ function showForceWarning(name, blockers, gitState) {
2122
+ console.error("");
2123
+ console.error(chalk3.red.bold("\u26A0\uFE0F WARNING: Force removing with unsaved work"));
2124
+ console.error("");
1378
2125
  console.error(
1379
- formatError(
1380
- createError(
1381
- "NotImplemented",
1382
- `Remove command not yet implemented for instance: ${name}.`,
1383
- "Actual implementation will be in Epic 5. For now, this is a placeholder."
1384
- )
2126
+ formatSafetyReport(name, blockers, gitState).replace(
2127
+ /Or use --force.*/,
2128
+ chalk3.red("This data will be PERMANENTLY DELETED.")
1385
2129
  )
1386
2130
  );
1387
- process.exit(1);
2131
+ }
2132
+ async function resolveConfirmation(name, options) {
2133
+ if (options.yes) {
2134
+ return "yes-flag";
2135
+ }
2136
+ if (!process.stdin.isTTY) {
2137
+ console.error("");
2138
+ console.error(
2139
+ chalk3.red(
2140
+ "Cannot prompt for confirmation in non-interactive mode. Use --yes to skip confirmation."
2141
+ )
2142
+ );
2143
+ return null;
2144
+ }
2145
+ const answer = await promptForConfirmation2(name);
2146
+ if (answer === null || answer !== name) {
2147
+ console.log("Removal cancelled");
2148
+ return null;
2149
+ }
2150
+ return "typed-name";
2151
+ }
2152
+ var removeCommand = new Command7("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--force", "Force removal, bypassing safety checks").option(
2153
+ "--yes",
2154
+ "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
2155
+ ).action(async (name, options) => {
2156
+ if (options.yes && !options.force) {
2157
+ console.error(
2158
+ formatError(
2159
+ createError(
2160
+ "INVALID_OPTIONS",
2161
+ "--yes can only be used with --force",
2162
+ "Use `agent-env remove <name> --force --yes` to force-remove without confirmation."
2163
+ )
2164
+ )
2165
+ );
2166
+ process.exit(1);
2167
+ return;
2168
+ }
2169
+ const deps = createRemoveDefaultDeps();
2170
+ const checkResult = await removeInstance(name, deps, false);
2171
+ if (checkResult.ok) {
2172
+ if (options.force) {
2173
+ console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
2174
+ await writeAuditLog(name, checkResult.gitState ?? null, "not-required");
2175
+ } else {
2176
+ console.log(`Instance '${name}' removed`);
2177
+ }
2178
+ return;
2179
+ }
2180
+ if (checkResult.error.code !== "SAFETY_CHECK_FAILED") {
2181
+ const { code, message, suggestion } = checkResult.error;
2182
+ console.error(formatError(createError(code, message, suggestion)));
2183
+ process.exit(1);
2184
+ return;
2185
+ }
2186
+ if (!options.force) {
2187
+ if (checkResult.gitState && checkResult.blockers) {
2188
+ console.error(formatSafetyReport(name, checkResult.blockers, checkResult.gitState));
2189
+ }
2190
+ process.exit(1);
2191
+ return;
2192
+ }
2193
+ const { gitState, blockers } = checkResult;
2194
+ if (gitState && blockers && blockers.length > 0) {
2195
+ showForceWarning(name, blockers, gitState);
2196
+ }
2197
+ const confirmationMethod = await resolveConfirmation(name, options);
2198
+ if (!confirmationMethod) {
2199
+ process.exit(1);
2200
+ return;
2201
+ }
2202
+ const forceResult = await removeInstance(name, deps, true);
2203
+ if (!forceResult.ok) {
2204
+ const { code, message, suggestion } = forceResult.error;
2205
+ console.error(formatError(createError(code, message, suggestion)));
2206
+ process.exit(1);
2207
+ return;
2208
+ }
2209
+ console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
2210
+ await writeAuditLog(name, gitState ?? null, confirmationMethod);
1388
2211
  });
1389
2212
 
1390
2213
  // src/components/InteractiveMenu.tsx
1391
2214
  import { Select } from "@inkjs/ui";
1392
2215
  import { Box as Box2, Text as Text3 } from "ink";
2216
+ import { useState } from "react";
1393
2217
  import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1394
2218
  var COLUMN_PADDING = 2;
1395
2219
  var SELECT_PREFIX_WIDTH = 4;
@@ -1430,11 +2254,32 @@ function buildOptionLabel(instance, terminalWidth) {
1430
2254
  }
1431
2255
  return parts.join(" ");
1432
2256
  }
2257
+ function ActionMenu({
2258
+ instanceName,
2259
+ onSelectAction
2260
+ }) {
2261
+ const options = [
2262
+ { label: "\u{1F680} Attach to session", value: "attach" },
2263
+ { label: "\u{1F6E0} Rebuild container", value: "rebuild" },
2264
+ { label: "\u{1F4DD} Show purpose", value: "purpose" },
2265
+ { label: "\u{1F5D1} Remove instance", value: "remove" }
2266
+ ];
2267
+ return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
2268
+ /* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsxs3(Text3, { children: [
2269
+ "Manage",
2270
+ " ",
2271
+ /* @__PURE__ */ jsx3(Text3, { bold: true, color: "cyan", children: instanceName }),
2272
+ ":"
2273
+ ] }) }),
2274
+ /* @__PURE__ */ jsx3(Select, { options, onChange: onSelectAction })
2275
+ ] });
2276
+ }
1433
2277
  function InteractiveMenu({
1434
2278
  instances,
1435
- onSelect,
2279
+ onAction,
1436
2280
  terminalWidth
1437
2281
  }) {
2282
+ const [selectedInstance, setSelectedInstance] = useState(null);
1438
2283
  const width = terminalWidth ?? process.stdout.columns ?? 80;
1439
2284
  if (instances.length === 0) {
1440
2285
  return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
@@ -1447,13 +2292,22 @@ function InteractiveMenu({
1447
2292
  ] })
1448
2293
  ] });
1449
2294
  }
2295
+ if (selectedInstance) {
2296
+ return /* @__PURE__ */ jsx3(
2297
+ ActionMenu,
2298
+ {
2299
+ instanceName: selectedInstance,
2300
+ onSelectAction: (action) => onAction(action, selectedInstance)
2301
+ }
2302
+ );
2303
+ }
1450
2304
  const options = instances.map((instance) => ({
1451
2305
  label: buildOptionLabel(instance, width),
1452
2306
  value: instance.name
1453
2307
  }));
1454
2308
  return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
1455
- /* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance to attach:" }) }),
1456
- /* @__PURE__ */ jsx3(Select, { options, onChange: onSelect })
2309
+ /* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance:" }) }),
2310
+ /* @__PURE__ */ jsx3(Select, { options, onChange: setSelectedInstance })
1457
2311
  ] });
1458
2312
  }
1459
2313
 
@@ -1476,38 +2330,66 @@ async function launchInteractiveMenu(deps) {
1476
2330
  return { ok: true, action: "empty" };
1477
2331
  }
1478
2332
  let selectedName;
1479
- const selectionPromise = new Promise((resolve) => {
1480
- const { waitUntilExit } = deps.renderMenu(listResult.instances, (name2) => {
1481
- selectedName = name2;
1482
- resolve(name2);
1483
- });
2333
+ let selectedAction;
2334
+ const selectionPromise = new Promise((resolve2) => {
2335
+ const { waitUntilExit } = deps.renderMenu(
2336
+ listResult.instances,
2337
+ (action2, name2) => {
2338
+ selectedAction = action2;
2339
+ selectedName = name2;
2340
+ resolve2({ action: action2, name: name2 });
2341
+ }
2342
+ );
1484
2343
  void waitUntilExit().then(() => {
1485
- if (!selectedName) {
1486
- resolve("");
2344
+ if (!selectedName || !selectedAction) {
2345
+ resolve2({ action: "attach", name: "" });
1487
2346
  }
1488
2347
  });
1489
2348
  });
1490
- const name = await selectionPromise;
2349
+ const { action, name } = await selectionPromise;
1491
2350
  if (!name) {
1492
2351
  return { ok: true, action: "empty" };
1493
2352
  }
1494
- const attachDeps = deps.createAttachDeps();
1495
- const attachResult = await deps.attachInstance(name, attachDeps);
1496
- if (!attachResult.ok) {
1497
- return {
1498
- ok: false,
1499
- error: attachResult.error
1500
- };
2353
+ switch (action) {
2354
+ case "attach": {
2355
+ const attachDeps = deps.createAttachDeps();
2356
+ const attachResult = await deps.attachInstance(name, attachDeps);
2357
+ if (!attachResult.ok) return { ok: false, error: attachResult.error };
2358
+ return { ok: true, action: "attached", instanceName: name };
2359
+ }
2360
+ case "rebuild": {
2361
+ const rebuildDeps = deps.createRebuildDeps();
2362
+ const rebuildResult = await deps.rebuildInstance(name, rebuildDeps, true);
2363
+ if (!rebuildResult.ok) return { ok: false, error: rebuildResult.error };
2364
+ return { ok: true, action: "rebuilt", instanceName: name };
2365
+ }
2366
+ case "purpose": {
2367
+ const instance = listResult.instances.find((i) => i.name === name);
2368
+ if (instance) {
2369
+ console.log(`
2370
+ Purpose for ${name}:`);
2371
+ console.log(instance.purpose || "No purpose set.");
2372
+ }
2373
+ return { ok: true, action: "purpose-shown", instanceName: name };
2374
+ }
2375
+ case "remove": {
2376
+ const removeDeps = deps.createRemoveDeps();
2377
+ const removeResult = await deps.removeInstance(name, removeDeps, false);
2378
+ if (!removeResult.ok) return { ok: false, error: removeResult.error };
2379
+ return { ok: true, action: "removed", instanceName: name };
2380
+ }
1501
2381
  }
1502
- return { ok: true, action: "attached", instanceName: name };
1503
2382
  }
1504
2383
 
1505
2384
  // src/cli.ts
1506
- var version = package_default.version;
2385
+ var __dirname = dirname3(fileURLToPath2(import.meta.url));
2386
+ var isLinked = existsSync(resolve(__dirname, "..", "..", "..", "pnpm-workspace.yaml"));
2387
+ var version = package_default.version + (isLinked ? "+local" : "");
1507
2388
  program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version);
1508
2389
  program.addCommand(createCommand);
1509
2390
  program.addCommand(listCommand);
1510
2391
  program.addCommand(attachCommand);
2392
+ program.addCommand(rebuildCommand);
1511
2393
  program.addCommand(removeCommand);
1512
2394
  program.addCommand(purposeCommand);
1513
2395
  program.addCommand(completionCommand);
@@ -1519,10 +2401,14 @@ program.action(async () => {
1519
2401
  const result = await launchInteractiveMenu({
1520
2402
  listInstances,
1521
2403
  attachInstance,
2404
+ rebuildInstance,
2405
+ removeInstance,
1522
2406
  createAttachDeps: createAttachDefaultDeps,
1523
- renderMenu: (instances, onSelect) => {
2407
+ createRebuildDeps: createRebuildDefaultDeps,
2408
+ createRemoveDeps: createRemoveDefaultDeps,
2409
+ renderMenu: (instances, onAction) => {
1524
2410
  const { waitUntilExit } = render2(
1525
- React2.createElement(InteractiveMenu, { instances, onSelect })
2411
+ React3.createElement(InteractiveMenu, { instances, onAction })
1526
2412
  );
1527
2413
  return { waitUntilExit };
1528
2414
  }
@@ -1531,6 +2417,10 @@ program.action(async () => {
1531
2417
  const { code, message, suggestion } = result.error;
1532
2418
  console.error(formatError(createError(code, message, suggestion)));
1533
2419
  process.exitCode = 1;
2420
+ } else if (result.action === "rebuilt") {
2421
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${result.instanceName}' rebuilt successfully`);
2422
+ } else if (result.action === "removed") {
2423
+ console.log(`\x1B[32m\u2713\x1B[0m Instance '${result.instanceName}' removed`);
1534
2424
  }
1535
2425
  });
1536
2426
  program.parse();