@zookanalytics/agent-env 0.1.2 → 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.
@@ -7,8 +7,13 @@
7
7
  "containerUser": "node",
8
8
  "initializeCommand": "bash .devcontainer/init-host.sh",
9
9
  "mounts": [
10
- "source=${localEnv:HOME}/.claude,target=/home/node/.claude,type=bind,readonly"
10
+ "source=${localEnv:HOME}/.claude,target=/home/node/.claude,type=bind,readonly",
11
+ "source=${localEnv:HOME}/.gitconfig,target=/home/node/.gitconfig,type=bind,readonly",
12
+ "source=/run/host-services/ssh-auth.sock,target=/run/host-services/ssh-auth.sock,type=bind"
11
13
  ],
14
+ "containerEnv": {
15
+ "SSH_AUTH_SOCK": "/run/host-services/ssh-auth.sock"
16
+ },
12
17
  "features": {
13
18
  "ghcr.io/devcontainers/features/git:1": {},
14
19
  "ghcr.io/devcontainers/features/git-lfs:1": {}
@@ -5,6 +5,8 @@
5
5
  set -euo pipefail
6
6
 
7
7
  CLAUDE_DIR="$HOME/.claude"
8
+ GITCONFIG="$HOME/.gitconfig"
9
+ SSH_SOCKET="/run/host-services/ssh-auth.sock"
8
10
 
9
11
  # Ensure ~/.claude directory exists (mounted read-only into container)
10
12
  if [ ! -d "$CLAUDE_DIR" ]; then
@@ -12,4 +14,17 @@ if [ ! -d "$CLAUDE_DIR" ]; then
12
14
  mkdir -p "$CLAUDE_DIR"
13
15
  fi
14
16
 
17
+ # Ensure ~/.gitconfig exists (mounted read-only into container)
18
+ if [ ! -f "$GITCONFIG" ]; then
19
+ echo "agent-env: Creating $GITCONFIG (mount source)"
20
+ touch "$GITCONFIG"
21
+ fi
22
+
23
+ # Verify SSH agent socket exists (provided by Docker Desktop / OrbStack on macOS)
24
+ if [ ! -S "$SSH_SOCKET" ]; then
25
+ echo "agent-env: Warning: SSH agent socket not found at $SSH_SOCKET"
26
+ echo "agent-env: SSH operations (git clone/push) may not work inside the container."
27
+ echo "agent-env: Ensure Docker Desktop or OrbStack is running on macOS."
28
+ fi
29
+
15
30
  echo "agent-env: Host initialization complete"
@@ -6,10 +6,6 @@ set -euo pipefail
6
6
 
7
7
  echo "=== agent-env: post-create initialization ==="
8
8
 
9
- # Include agent-env git config for SSH-based signing
10
- cp .devcontainer/git-config /home/node/.devcontainer-git-config 2>/dev/null || true
11
- git config --global include.path /home/node/.devcontainer-git-config
12
-
13
9
  # Verify tool installation
14
10
  echo "--- Tool verification ---"
15
11
  echo "Node.js: $(node --version)"
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.2",
45
+ version: "0.1.3",
43
46
  description: "CLI for creating isolated, AI-ready development environments",
44
47
  type: "module",
45
48
  bin: {
@@ -176,6 +179,26 @@ function createContainerLifecycle(executor = createExecutor()) {
176
179
  const name = result.stdout.trim().replace(/^\//, "");
177
180
  return name || null;
178
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
+ }
179
202
  async function devcontainerUp(workspacePath, containerName) {
180
203
  const dockerOk = await isDockerAvailable();
181
204
  if (!dockerOk) {
@@ -207,7 +230,14 @@ function createContainerLifecycle(executor = createExecutor()) {
207
230
  }
208
231
  }
209
232
  if (!result.ok) {
210
- 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");
211
241
  return {
212
242
  ok: false,
213
243
  status: "not-found",
@@ -216,7 +246,7 @@ function createContainerLifecycle(executor = createExecutor()) {
216
246
  code: "CONTAINER_ERROR",
217
247
  message: `devcontainer up failed for '${containerName}':
218
248
  ${details}`,
219
- 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."
220
250
  }
221
251
  };
222
252
  }
@@ -268,6 +298,7 @@ function createContainerLifecycle(executor = createExecutor()) {
268
298
  isDockerAvailable,
269
299
  containerStatus,
270
300
  getContainerNameById,
301
+ findContainerByWorkspaceLabel,
271
302
  devcontainerUp,
272
303
  containerStop,
273
304
  containerRemove
@@ -337,8 +368,8 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
337
368
  await deps.mkdir(targetDir, { recursive: true });
338
369
  await deps.cp(baselinePath, targetDir, { recursive: true });
339
370
  }
340
- async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps) {
341
- 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);
342
373
  const content = await deps.readFile(configPath, "utf-8");
343
374
  const config = JSON.parse(content);
344
375
  const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
@@ -346,6 +377,11 @@ async function patchContainerName(workspacePath, containerName, deps = defaultFs
346
377
  config.runArgs = [...filtered, `--name=${containerName}`];
347
378
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
348
379
  }
380
+ async function listBaselineFiles(deps = defaultFsDeps) {
381
+ const baselinePath = getBaselineConfigPath();
382
+ const entries = await deps.readdir(baselinePath);
383
+ return entries.sort();
384
+ }
349
385
 
350
386
  // src/lib/state.ts
351
387
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
@@ -392,7 +428,8 @@ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
392
428
  await deps.writeFile(tmpPath, content, "utf-8");
393
429
  await deps.rename(tmpPath, wsPath.stateFile);
394
430
  }
395
- function createInitialState(name, repo, containerName) {
431
+ function createInitialState(name, repo, options) {
432
+ const { containerName, configSource } = options ?? {};
396
433
  const now = (/* @__PURE__ */ new Date()).toISOString();
397
434
  return {
398
435
  name,
@@ -400,7 +437,8 @@ function createInitialState(name, repo, containerName) {
400
437
  createdAt: now,
401
438
  lastAttached: now,
402
439
  purpose: null,
403
- containerName: containerName ?? `${CONTAINER_PREFIX}${name}`
440
+ containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
441
+ configSource: configSource ?? "baseline"
404
442
  };
405
443
  }
406
444
  function isValidState(value) {
@@ -569,7 +607,11 @@ function createDefaultDeps() {
569
607
  workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
570
608
  stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
571
609
  devcontainerFsDeps: { cp: cp2, mkdir: mkdir4, readFile: readFile3, stat: stat3, writeFile: writeFile3 },
572
- rm: rm2
610
+ rm: rm2,
611
+ logger: {
612
+ warn: (msg) => console.warn(msg),
613
+ info: (msg) => console.info(msg)
614
+ }
573
615
  };
574
616
  }
575
617
  async function createInstance(instanceName, repoUrl, deps) {
@@ -615,7 +657,7 @@ async function createInstance(instanceName, repoUrl, deps) {
615
657
  timeout: GIT_CLONE_TIMEOUT
616
658
  });
617
659
  if (!cloneResult.ok) {
618
- await safeRollback(wsPath.root, deps.rm);
660
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
619
661
  return {
620
662
  ok: false,
621
663
  error: {
@@ -628,7 +670,7 @@ async function createInstance(instanceName, repoUrl, deps) {
628
670
  try {
629
671
  await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
630
672
  } catch (err) {
631
- await safeRollback(wsPath.root, deps.rm);
673
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
632
674
  return {
633
675
  ok: false,
634
676
  error: {
@@ -639,11 +681,12 @@ async function createInstance(instanceName, repoUrl, deps) {
639
681
  };
640
682
  }
641
683
  const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
684
+ let configSource = "baseline";
642
685
  if (!hasConfig) {
643
686
  try {
644
687
  await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
645
688
  } catch (err) {
646
- await safeRollback(wsPath.root, deps.rm);
689
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
647
690
  return {
648
691
  ok: false,
649
692
  error: {
@@ -655,7 +698,7 @@ async function createInstance(instanceName, repoUrl, deps) {
655
698
  try {
656
699
  await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps);
657
700
  } catch (err) {
658
- await safeRollback(wsPath.root, deps.rm);
701
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
659
702
  return {
660
703
  ok: false,
661
704
  error: {
@@ -664,10 +707,25 @@ async function createInstance(instanceName, repoUrl, deps) {
664
707
  }
665
708
  };
666
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
+ };
667
724
  }
668
725
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName);
669
726
  if (!containerResult.ok) {
670
- 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);
671
729
  return {
672
730
  ok: false,
673
731
  error: containerResult.error ?? {
@@ -683,11 +741,14 @@ async function createInstance(instanceName, repoUrl, deps) {
683
741
  actualContainerName = discovered;
684
742
  }
685
743
  } else {
686
- console.warn(
744
+ deps.logger?.warn(
687
745
  `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
688
746
  );
689
747
  }
690
- const state = createInitialState(wsPath.name, repoUrl, actualContainerName);
748
+ const state = createInitialState(wsPath.name, repoUrl, {
749
+ containerName: actualContainerName,
750
+ configSource
751
+ });
691
752
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
692
753
  await ensureGitExclude(wsPath.root, deps.stateFsDeps);
693
754
  return {
@@ -696,11 +757,11 @@ async function createInstance(instanceName, repoUrl, deps) {
696
757
  containerName: actualContainerName
697
758
  };
698
759
  }
699
- async function safeRollback(workspacePath, rmFn) {
760
+ async function safeRollback(workspacePath, rmFn, logger) {
700
761
  try {
701
762
  await rmFn(workspacePath, { recursive: true, force: true });
702
763
  } catch {
703
- console.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
764
+ logger?.warn(`Warning: Failed to clean up workspace at ${workspacePath}`);
704
765
  }
705
766
  }
706
767
 
@@ -1488,24 +1549,289 @@ var purposeCommand = new Command5("purpose").description("Get or set the purpose
1488
1549
  }
1489
1550
  });
1490
1551
 
1491
- // src/commands/remove.ts
1492
- import chalk2 from "chalk";
1552
+ // src/commands/rebuild.ts
1553
+ import chalk from "chalk";
1493
1554
  import { Command as Command6 } from "commander";
1494
1555
  import { createInterface } from "readline";
1495
1556
 
1496
- // src/lib/audit-log.ts
1497
- import { appendFile as appendFile5, mkdir as mkdir7 } from "fs/promises";
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";
1498
1569
  import { homedir as homedir5 } from "os";
1499
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";
1500
1826
  function createAuditLogDefaultDeps() {
1501
- return { appendFile: appendFile5, mkdir: mkdir7, homedir: homedir5 };
1827
+ return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
1502
1828
  }
1503
1829
  function getAuditLogPath(deps) {
1504
- return join4(deps.homedir(), AGENT_ENV_DIR, "audit.log");
1830
+ return join5(deps.homedir(), AGENT_ENV_DIR, "audit.log");
1505
1831
  }
1506
1832
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
1507
1833
  const logPath = getAuditLogPath(deps);
1508
- await deps.mkdir(join4(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
1834
+ await deps.mkdir(join5(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
1509
1835
  const line = JSON.stringify(entry) + "\n";
1510
1836
  await deps.appendFile(logPath, line, "utf-8");
1511
1837
  }
@@ -1520,17 +1846,17 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
1520
1846
  }
1521
1847
 
1522
1848
  // src/lib/remove-instance.ts
1523
- import { mkdir as mkdir8, readdir as readdir6, readFile as readFile6, rm as rm3, stat as stat6 } from "fs/promises";
1524
- import { homedir as homedir6 } from "os";
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";
1525
1851
  function createRemoveDefaultDeps() {
1526
1852
  const executor = createExecutor();
1527
1853
  return {
1528
1854
  executor,
1529
1855
  container: createContainerLifecycle(executor),
1530
1856
  gitDetector: createGitStateDetector(executor),
1531
- workspaceFsDeps: { mkdir: mkdir8, readdir: readdir6, stat: stat6, homedir: homedir6 },
1532
- stateFsDeps: { readFile: readFile6 },
1533
- deleteFsDeps: { rm: rm3 }
1857
+ workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
1858
+ stateFsDeps: { readFile: readFile7 },
1859
+ deleteFsDeps: { rm: rm4 }
1534
1860
  };
1535
1861
  }
1536
1862
  function evaluateSafetyChecks(gitState) {
@@ -1690,7 +2016,7 @@ async function removeInstance(instanceName, deps, force = false) {
1690
2016
  }
1691
2017
 
1692
2018
  // src/lib/safety-report.ts
1693
- import chalk from "chalk";
2019
+ import chalk2 from "chalk";
1694
2020
  var BLOCKER_NEVER_PUSHED = "never pushed";
1695
2021
  var BLOCKER_DETACHED_HEAD = "detached HEAD";
1696
2022
  function classifyBlocker(blocker) {
@@ -1743,27 +2069,27 @@ function formatSafetyReport(instanceName, blockers, gitState) {
1743
2069
  message: blocker
1744
2070
  }));
1745
2071
  for (const item of items) {
1746
- const prefix = item.severity === "Danger" ? chalk.red("[Danger]") : chalk.yellow("[Warning]");
2072
+ const prefix = item.severity === "Danger" ? chalk2.red("[Danger]") : chalk2.yellow("[Warning]");
1747
2073
  lines.push(` ${prefix} ${item.message}`);
1748
2074
  }
1749
2075
  const suggestions = getSuggestions(gitState);
1750
2076
  if (suggestions.length > 0) {
1751
2077
  lines.push("");
1752
- lines.push(chalk.bold("Suggestions:"));
2078
+ lines.push(chalk2.bold("Suggestions:"));
1753
2079
  for (const suggestion of suggestions) {
1754
2080
  lines.push(` - ${suggestion}`);
1755
2081
  }
1756
2082
  }
1757
2083
  lines.push("");
1758
- lines.push(chalk.gray("Or use --force to bypass safety checks (data loss is permanent)."));
2084
+ lines.push(chalk2.gray("Or use --force to bypass safety checks (data loss is permanent)."));
1759
2085
  return lines.join("\n");
1760
2086
  }
1761
2087
 
1762
2088
  // src/commands/remove.ts
1763
- function promptForConfirmation(instanceName) {
1764
- return new Promise((resolve) => {
2089
+ function promptForConfirmation2(instanceName) {
2090
+ return new Promise((resolve2) => {
1765
2091
  let resolved = false;
1766
- const rl = createInterface({
2092
+ const rl = createInterface2({
1767
2093
  input: process.stdin,
1768
2094
  output: process.stderr
1769
2095
  });
@@ -1772,13 +2098,13 @@ Type the instance name "${instanceName}" to confirm: `, (answer) => {
1772
2098
  if (!resolved) {
1773
2099
  resolved = true;
1774
2100
  rl.close();
1775
- resolve(answer);
2101
+ resolve2(answer);
1776
2102
  }
1777
2103
  });
1778
2104
  rl.on("close", () => {
1779
2105
  if (!resolved) {
1780
2106
  resolved = true;
1781
- resolve(null);
2107
+ resolve2(null);
1782
2108
  }
1783
2109
  });
1784
2110
  });
@@ -1794,12 +2120,12 @@ async function writeAuditLog(name, gitState, confirmationMethod) {
1794
2120
  }
1795
2121
  function showForceWarning(name, blockers, gitState) {
1796
2122
  console.error("");
1797
- console.error(chalk2.red.bold("\u26A0\uFE0F WARNING: Force removing with unsaved work"));
2123
+ console.error(chalk3.red.bold("\u26A0\uFE0F WARNING: Force removing with unsaved work"));
1798
2124
  console.error("");
1799
2125
  console.error(
1800
2126
  formatSafetyReport(name, blockers, gitState).replace(
1801
2127
  /Or use --force.*/,
1802
- chalk2.red("This data will be PERMANENTLY DELETED.")
2128
+ chalk3.red("This data will be PERMANENTLY DELETED.")
1803
2129
  )
1804
2130
  );
1805
2131
  }
@@ -1810,20 +2136,20 @@ async function resolveConfirmation(name, options) {
1810
2136
  if (!process.stdin.isTTY) {
1811
2137
  console.error("");
1812
2138
  console.error(
1813
- chalk2.red(
2139
+ chalk3.red(
1814
2140
  "Cannot prompt for confirmation in non-interactive mode. Use --yes to skip confirmation."
1815
2141
  )
1816
2142
  );
1817
2143
  return null;
1818
2144
  }
1819
- const answer = await promptForConfirmation(name);
2145
+ const answer = await promptForConfirmation2(name);
1820
2146
  if (answer === null || answer !== name) {
1821
2147
  console.log("Removal cancelled");
1822
2148
  return null;
1823
2149
  }
1824
2150
  return "typed-name";
1825
2151
  }
1826
- 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").option(
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(
1827
2153
  "--yes",
1828
2154
  "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
1829
2155
  ).action(async (name, options) => {
@@ -1887,6 +2213,7 @@ var removeCommand = new Command6("remove").description("Remove an instance with
1887
2213
  // src/components/InteractiveMenu.tsx
1888
2214
  import { Select } from "@inkjs/ui";
1889
2215
  import { Box as Box2, Text as Text3 } from "ink";
2216
+ import { useState } from "react";
1890
2217
  import { jsx as jsx3, jsxs as jsxs3 } from "react/jsx-runtime";
1891
2218
  var COLUMN_PADDING = 2;
1892
2219
  var SELECT_PREFIX_WIDTH = 4;
@@ -1927,11 +2254,32 @@ function buildOptionLabel(instance, terminalWidth) {
1927
2254
  }
1928
2255
  return parts.join(" ");
1929
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
+ }
1930
2277
  function InteractiveMenu({
1931
2278
  instances,
1932
- onSelect,
2279
+ onAction,
1933
2280
  terminalWidth
1934
2281
  }) {
2282
+ const [selectedInstance, setSelectedInstance] = useState(null);
1935
2283
  const width = terminalWidth ?? process.stdout.columns ?? 80;
1936
2284
  if (instances.length === 0) {
1937
2285
  return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
@@ -1944,13 +2292,22 @@ function InteractiveMenu({
1944
2292
  ] })
1945
2293
  ] });
1946
2294
  }
2295
+ if (selectedInstance) {
2296
+ return /* @__PURE__ */ jsx3(
2297
+ ActionMenu,
2298
+ {
2299
+ instanceName: selectedInstance,
2300
+ onSelectAction: (action) => onAction(action, selectedInstance)
2301
+ }
2302
+ );
2303
+ }
1947
2304
  const options = instances.map((instance) => ({
1948
2305
  label: buildOptionLabel(instance, width),
1949
2306
  value: instance.name
1950
2307
  }));
1951
2308
  return /* @__PURE__ */ jsxs3(Box2, { flexDirection: "column", children: [
1952
- /* @__PURE__ */ jsx3(Box2, { marginBottom: 1, children: /* @__PURE__ */ jsx3(Text3, { bold: true, children: "Select an instance to attach:" }) }),
1953
- /* @__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 })
1954
2311
  ] });
1955
2312
  }
1956
2313
 
@@ -1973,38 +2330,66 @@ async function launchInteractiveMenu(deps) {
1973
2330
  return { ok: true, action: "empty" };
1974
2331
  }
1975
2332
  let selectedName;
1976
- const selectionPromise = new Promise((resolve) => {
1977
- const { waitUntilExit } = deps.renderMenu(listResult.instances, (name2) => {
1978
- selectedName = name2;
1979
- resolve(name2);
1980
- });
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
+ );
1981
2343
  void waitUntilExit().then(() => {
1982
- if (!selectedName) {
1983
- resolve("");
2344
+ if (!selectedName || !selectedAction) {
2345
+ resolve2({ action: "attach", name: "" });
1984
2346
  }
1985
2347
  });
1986
2348
  });
1987
- const name = await selectionPromise;
2349
+ const { action, name } = await selectionPromise;
1988
2350
  if (!name) {
1989
2351
  return { ok: true, action: "empty" };
1990
2352
  }
1991
- const attachDeps = deps.createAttachDeps();
1992
- const attachResult = await deps.attachInstance(name, attachDeps);
1993
- if (!attachResult.ok) {
1994
- return {
1995
- ok: false,
1996
- error: attachResult.error
1997
- };
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
+ }
1998
2381
  }
1999
- return { ok: true, action: "attached", instanceName: name };
2000
2382
  }
2001
2383
 
2002
2384
  // src/cli.ts
2003
- 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" : "");
2004
2388
  program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version);
2005
2389
  program.addCommand(createCommand);
2006
2390
  program.addCommand(listCommand);
2007
2391
  program.addCommand(attachCommand);
2392
+ program.addCommand(rebuildCommand);
2008
2393
  program.addCommand(removeCommand);
2009
2394
  program.addCommand(purposeCommand);
2010
2395
  program.addCommand(completionCommand);
@@ -2016,10 +2401,14 @@ program.action(async () => {
2016
2401
  const result = await launchInteractiveMenu({
2017
2402
  listInstances,
2018
2403
  attachInstance,
2404
+ rebuildInstance,
2405
+ removeInstance,
2019
2406
  createAttachDeps: createAttachDefaultDeps,
2020
- renderMenu: (instances, onSelect) => {
2407
+ createRebuildDeps: createRebuildDefaultDeps,
2408
+ createRemoveDeps: createRemoveDefaultDeps,
2409
+ renderMenu: (instances, onAction) => {
2021
2410
  const { waitUntilExit } = render2(
2022
- React2.createElement(InteractiveMenu, { instances, onSelect })
2411
+ React3.createElement(InteractiveMenu, { instances, onAction })
2023
2412
  );
2024
2413
  return { waitUntilExit };
2025
2414
  }
@@ -2028,6 +2417,10 @@ program.action(async () => {
2028
2417
  const { code, message, suggestion } = result.error;
2029
2418
  console.error(formatError(createError(code, message, suggestion)));
2030
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`);
2031
2424
  }
2032
2425
  });
2033
2426
  program.parse();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zookanalytics/agent-env",
3
- "version": "0.1.2",
3
+ "version": "0.1.3",
4
4
  "description": "CLI for creating isolated, AI-ready development environments",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,11 +0,0 @@
1
- # agent-env git configuration defaults
2
- # Included via git config include.path in post-create.sh
3
-
4
- [gpg]
5
- format = ssh
6
-
7
- [commit]
8
- gpgsign = true
9
-
10
- [tag]
11
- gpgsign = true