@zookanalytics/agent-env 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -42,7 +42,7 @@ import React3 from "react";
42
42
  // package.json
43
43
  var package_default = {
44
44
  name: "@zookanalytics/agent-env",
45
- version: "0.4.0",
45
+ version: "0.5.0",
46
46
  description: "CLI for creating isolated, AI-ready development environments",
47
47
  type: "module",
48
48
  bin: {
@@ -103,9 +103,9 @@ var package_default = {
103
103
  import { Command } from "commander";
104
104
 
105
105
  // src/lib/attach-instance.ts
106
- import { appendFile as appendFile4, mkdir as mkdir6, readdir as readdir5, readFile as readFile5, rename as rename4, stat as stat5, writeFile as writeFile5 } from "fs/promises";
106
+ import { appendFile as appendFile4, mkdir as mkdir6, readdir as readdir5, readFile as readFile7, rename as rename4, stat as stat5, writeFile as writeFile6 } from "fs/promises";
107
107
  import { homedir as homedir4 } from "os";
108
- import { join as join5 } from "path";
108
+ import { join as join6 } from "path";
109
109
 
110
110
  // src/lib/container.ts
111
111
  var DEVCONTAINER_UP_TIMEOUT = 3e5;
@@ -410,14 +410,14 @@ import {
410
410
  cp as cp2,
411
411
  mkdir as mkdir5,
412
412
  readdir as readdir4,
413
- readFile as readFile4,
413
+ readFile as readFile6,
414
414
  rename as rename3,
415
415
  rm as rm2,
416
416
  stat as stat4,
417
- writeFile as writeFile4
417
+ writeFile as writeFile5
418
418
  } from "fs/promises";
419
419
  import { homedir as homedir3 } from "os";
420
- import { dirname as dirname2, join as join4 } from "path";
420
+ import { dirname as dirname2, join as join5 } from "path";
421
421
 
422
422
  // src/lib/devcontainer.ts
423
423
  import { parse as parseJsonc } from "jsonc-parser";
@@ -425,16 +425,35 @@ import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promis
425
425
  import { dirname, join } from "path";
426
426
  import { fileURLToPath } from "url";
427
427
 
428
+ // src/lib/container-env.ts
429
+ var CONTAINER_STATE_PATH = "/etc/agent-env/state.json";
430
+ var CONTAINER_AGENT_ENV_DIR = "/etc/agent-env";
431
+ var defaultContainerEnvDeps = {
432
+ getEnv: (key) => process.env[key]
433
+ };
434
+ function isInsideContainer(deps = defaultContainerEnvDeps) {
435
+ return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
436
+ }
437
+
428
438
  // src/lib/types.ts
429
439
  var AGENT_ENV_DIR = ".agent-env";
430
440
  var WORKSPACES_DIR = "workspaces";
431
441
  var STATE_FILE = "state.json";
432
442
  var STATE_FILE_TMP = "state.json.tmp";
433
443
  var CONTAINER_PREFIX = "ae-";
444
+ var MAX_INSTANCE_NAME_LENGTH = 20;
445
+ var MAX_REPO_SLUG_LENGTH = 39;
446
+ var MAX_CONTAINER_NAME_LENGTH = 63;
447
+ if (CONTAINER_PREFIX.length + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH !== MAX_CONTAINER_NAME_LENGTH) {
448
+ throw new Error(
449
+ "BUG: MAX_CONTAINER_NAME_LENGTH does not equal CONTAINER_PREFIX + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH"
450
+ );
451
+ }
434
452
  function createFallbackState(workspaceName) {
435
453
  return {
436
- name: workspaceName,
437
- repo: "unknown",
454
+ instance: workspaceName,
455
+ repoSlug: "unknown",
456
+ repoUrl: "unknown",
438
457
  createdAt: "unknown",
439
458
  lastAttached: "unknown",
440
459
  purpose: null,
@@ -452,6 +471,11 @@ function getBaselineConfigPath() {
452
471
  const packageRoot = dirname(dirname(dirname(currentFile)));
453
472
  return join(packageRoot, "config", "baseline");
454
473
  }
474
+ function getTemplatesPath() {
475
+ const currentFile = fileURLToPath(import.meta.url);
476
+ const packageRoot = dirname(dirname(dirname(currentFile)));
477
+ return join(packageRoot, "config", "templates");
478
+ }
455
479
  async function hasDevcontainerConfig(workspacePath, deps = defaultFsDeps) {
456
480
  try {
457
481
  const dirStats = await deps.stat(join(workspacePath, DEVCONTAINER_DIR));
@@ -487,21 +511,70 @@ async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
487
511
  await deps.mkdir(targetDir, { recursive: true });
488
512
  await deps.cp(baselinePath, targetDir, { recursive: true });
489
513
  }
490
- async function patchContainerName(workspacePath, containerName, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
491
- const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
492
- const content = await deps.readFile(configPath, "utf-8");
493
- const config = JSON.parse(content);
514
+ async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
515
+ const templatesPath = getTemplatesPath();
516
+ const srcFile = join(templatesPath, "statusBar.template.json");
517
+ try {
518
+ await deps.stat(srcFile);
519
+ } catch (err) {
520
+ if (err.code === "ENOENT") return;
521
+ throw err;
522
+ }
523
+ const targetDir = join(workspacePath, AGENT_ENV_DIR);
524
+ await deps.mkdir(targetDir, { recursive: true });
525
+ await deps.cp(srcFile, join(targetDir, "statusBar.template.json"));
526
+ }
527
+ var STATUS_BAR_JSON_FILENAME = "statusBar.json";
528
+ function applyContainerNamePatch(config, containerName) {
494
529
  const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
495
530
  const filtered = existing.filter((arg) => !arg.startsWith("--name="));
496
531
  config.runArgs = [...filtered, `--name=${containerName}`];
497
- await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
532
+ return config;
498
533
  }
499
- async function patchContainerEnv(workspacePath, envVars, deps = defaultFsDeps, configDir = DEVCONTAINER_DIR) {
500
- const configPath = join(workspacePath, configDir, DEVCONTAINER_JSON);
501
- const content = await deps.readFile(configPath, "utf-8");
502
- const config = JSON.parse(content);
534
+ function applyContainerEnvPatch(config, envVars) {
503
535
  const existing = typeof config.containerEnv === "object" && config.containerEnv !== null ? config.containerEnv : {};
504
536
  config.containerEnv = { ...existing, ...envVars };
537
+ return config;
538
+ }
539
+ function applyVscodeSettingsPatch(config) {
540
+ if (typeof config.customizations !== "object" || config.customizations === null) {
541
+ config.customizations = {};
542
+ }
543
+ const customizations = config.customizations;
544
+ if (typeof customizations.vscode !== "object" || customizations.vscode === null) {
545
+ customizations.vscode = {};
546
+ }
547
+ const vscode = customizations.vscode;
548
+ if (typeof vscode.settings !== "object" || vscode.settings === null) {
549
+ vscode.settings = {};
550
+ }
551
+ const settings = vscode.settings;
552
+ const existingFilewatcherCommands = Array.isArray(settings["filewatcher.commands"]) ? settings["filewatcher.commands"] : [];
553
+ const statusBarWatcher = {
554
+ match: `${STATUS_BAR_JSON_FILENAME}$`,
555
+ event: "onFolderChange",
556
+ vscodeTask: "betterStatusBar.refreshButtons"
557
+ };
558
+ const hasStatusBarWatcher = existingFilewatcherCommands.some((cmd) => {
559
+ if (typeof cmd !== "object" || cmd === null) return false;
560
+ const c = cmd;
561
+ return c.match === statusBarWatcher.match && c.event === statusBarWatcher.event && c.vscodeTask === statusBarWatcher.vscodeTask;
562
+ });
563
+ const mergedFilewatcherCommands = hasStatusBarWatcher ? existingFilewatcherCommands : [...existingFilewatcherCommands, statusBarWatcher];
564
+ vscode.settings = {
565
+ ...settings,
566
+ "betterStatusBar.configurationFile": `${CONTAINER_AGENT_ENV_DIR}/${STATUS_BAR_JSON_FILENAME}`,
567
+ "filewatcher.commands": mergedFilewatcherCommands
568
+ };
569
+ return config;
570
+ }
571
+ async function applyBaselinePatches(workspacePath, containerName, envVars, deps, configDir) {
572
+ const configPath = join(workspacePath, configDir, "devcontainer.json");
573
+ const content = await deps.readFile(configPath, "utf-8");
574
+ let config = JSON.parse(content);
575
+ config = applyContainerNamePatch(config, containerName);
576
+ config = applyContainerEnvPatch(config, envVars);
577
+ config = applyVscodeSettingsPatch(config);
505
578
  await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
506
579
  }
507
580
  async function resolveDockerfilePath(workspacePath, deps) {
@@ -575,19 +648,9 @@ function parseDockerfileImages(content, logger) {
575
648
  }
576
649
 
577
650
  // src/lib/purpose-instance.ts
578
- import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile3, rename as rename2, stat as stat3, writeFile as writeFile3 } from "fs/promises";
651
+ import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile5, rename as rename2, stat as stat3, writeFile as writeFile4 } from "fs/promises";
579
652
  import { homedir as homedir2 } from "os";
580
653
 
581
- // src/lib/container-env.ts
582
- var CONTAINER_STATE_PATH = "/etc/agent-env/state.json";
583
- var CONTAINER_AGENT_ENV_DIR = "/etc/agent-env";
584
- var defaultContainerEnvDeps = {
585
- getEnv: (key) => process.env[key]
586
- };
587
- function isInsideContainer(deps = defaultContainerEnvDeps) {
588
- return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
589
- }
590
-
591
654
  // src/lib/state.ts
592
655
  import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
593
656
  import { join as join2 } from "path";
@@ -597,7 +660,7 @@ async function readState(wsPath, deps = defaultStateFsDeps) {
597
660
  const content = await deps.readFile(wsPath.stateFile, "utf-8");
598
661
  const parsed = JSON.parse(content);
599
662
  if (!isValidState(parsed)) {
600
- return createFallbackState(wsPath.name);
663
+ return migrateOldState(parsed, wsPath.name) ?? createFallbackState(wsPath.name);
601
664
  }
602
665
  return parsed;
603
666
  } catch (err) {
@@ -614,36 +677,71 @@ async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
614
677
  await deps.writeFile(tmpPath, content, "utf-8");
615
678
  await deps.rename(tmpPath, wsPath.stateFile);
616
679
  }
617
- function createInitialState(name, repo, options) {
680
+ function createInitialState(instance, repoSlug, repoUrl, options) {
618
681
  const { containerName, configSource, purpose } = options ?? {};
619
682
  const now = (/* @__PURE__ */ new Date()).toISOString();
683
+ const workspaceName = `${repoSlug}-${instance}`;
620
684
  return {
621
- name,
622
- repo,
685
+ instance,
686
+ repoSlug,
687
+ repoUrl,
623
688
  createdAt: now,
624
689
  lastAttached: now,
625
690
  purpose: purpose ?? null,
626
- containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
691
+ containerName: containerName ?? `${CONTAINER_PREFIX}${workspaceName}`,
627
692
  configSource: configSource ?? "baseline"
628
693
  };
629
694
  }
695
+ function extractRepoName(url) {
696
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
697
+ const lastSep = Math.max(cleaned.lastIndexOf("/"), cleaned.lastIndexOf(":"));
698
+ const name = lastSep >= 0 ? cleaned.slice(lastSep + 1) : cleaned;
699
+ return name.toLowerCase() || "unknown";
700
+ }
701
+ function migrateOldState(parsed, workspaceName) {
702
+ if (typeof parsed !== "object" || parsed === null) return null;
703
+ const obj = parsed;
704
+ if (typeof obj.name !== "string" || typeof obj.repo !== "string") return null;
705
+ const repoSlug = extractRepoName(obj.repo);
706
+ const lowerName = obj.name.toLowerCase();
707
+ const prefix = `${repoSlug}-`;
708
+ const instance = lowerName.startsWith(prefix) && obj.name.length > prefix.length ? obj.name.slice(prefix.length) : obj.name;
709
+ const configSource = obj.configSource === "baseline" || obj.configSource === "repo" ? obj.configSource : void 0;
710
+ const state = {
711
+ instance,
712
+ repoSlug,
713
+ repoUrl: obj.repo,
714
+ createdAt: typeof obj.createdAt === "string" ? obj.createdAt : "unknown",
715
+ lastAttached: typeof obj.lastAttached === "string" ? obj.lastAttached : "unknown",
716
+ purpose: typeof obj.purpose === "string" ? obj.purpose : null,
717
+ containerName: typeof obj.containerName === "string" ? obj.containerName : `${CONTAINER_PREFIX}${workspaceName}`
718
+ };
719
+ if (configSource) {
720
+ state.configSource = configSource;
721
+ }
722
+ return state;
723
+ }
630
724
  function isValidState(value) {
631
725
  if (typeof value !== "object" || value === null) return false;
632
726
  const obj = value;
633
- return typeof obj.name === "string" && typeof obj.repo === "string" && typeof obj.createdAt === "string" && typeof obj.lastAttached === "string" && (obj.purpose === void 0 || obj.purpose === null || typeof obj.purpose === "string") && typeof obj.containerName === "string";
727
+ return typeof obj.instance === "string" && typeof obj.repoSlug === "string" && typeof obj.repoUrl === "string" && typeof obj.createdAt === "string" && typeof obj.lastAttached === "string" && (obj.purpose === void 0 || obj.purpose === null || typeof obj.purpose === "string") && typeof obj.containerName === "string";
634
728
  }
635
- var GIT_EXCLUDE_PATTERN = `${AGENT_ENV_DIR}/`;
729
+ var GIT_EXCLUDE_PATTERNS = [`${AGENT_ENV_DIR}/`];
636
730
  async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
637
731
  const excludePath = join2(workspaceRoot, ".git", "info", "exclude");
638
732
  try {
639
733
  const content = await deps.readFile(excludePath, "utf-8");
640
734
  const lines = content.split("\n");
641
- if (lines.some((line) => line.trim() === GIT_EXCLUDE_PATTERN)) {
735
+ const missing = GIT_EXCLUDE_PATTERNS.filter(
736
+ (pattern) => !lines.some((line) => line.trim() === pattern)
737
+ );
738
+ if (missing.length === 0) {
642
739
  return;
643
740
  }
644
741
  const prefix = content.endsWith("\n") ? "" : "\n";
645
- await deps.appendFile(excludePath, `${prefix}${GIT_EXCLUDE_PATTERN}
646
- `, "utf-8");
742
+ const toAppend = missing.map((p) => `${p}
743
+ `).join("");
744
+ await deps.appendFile(excludePath, `${prefix}${toAppend}`, "utf-8");
647
745
  } catch (err) {
648
746
  if (err.code === "ENOENT") {
649
747
  return;
@@ -652,10 +750,54 @@ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
652
750
  }
653
751
  }
654
752
 
753
+ // src/lib/status-bar.ts
754
+ import { readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
755
+ import { join as join3 } from "path";
756
+ var STATUS_BAR_TEMPLATE_JSON = "statusBar.template.json";
757
+ var STATUS_BAR_JSON = "statusBar.json";
758
+ var PURPOSE_PLACEHOLDER = "{{PURPOSE}}";
759
+ var NO_PURPOSE_TEXT = "(no purpose set)";
760
+ var defaultDeps = { readFile: readFile3, writeFile: writeFile3 };
761
+ async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = defaultDeps) {
762
+ const vscodeTemplatePath = join3(workspaceRoot, ".vscode", STATUS_BAR_TEMPLATE_JSON);
763
+ let templateContent = null;
764
+ try {
765
+ templateContent = await deps.readFile(vscodeTemplatePath, "utf-8");
766
+ } catch (err) {
767
+ if (err.code !== "ENOENT") {
768
+ throw err;
769
+ }
770
+ }
771
+ const agentEnvTemplatePath = join3(agentEnvDir, STATUS_BAR_TEMPLATE_JSON);
772
+ if (templateContent === null) {
773
+ try {
774
+ templateContent = await deps.readFile(agentEnvTemplatePath, "utf-8");
775
+ } catch (err) {
776
+ if (err.code !== "ENOENT") {
777
+ throw err;
778
+ }
779
+ }
780
+ }
781
+ if (templateContent === null) {
782
+ throw Object.assign(
783
+ new Error(
784
+ `No status bar template found. Checked ${vscodeTemplatePath} and ${agentEnvTemplatePath}. Create a template manually or use \`agent-env init-template\` when available.`
785
+ ),
786
+ { code: "TEMPLATE_NOT_FOUND" }
787
+ );
788
+ }
789
+ const rawText = purpose ?? NO_PURPOSE_TEXT;
790
+ const replacementText = JSON.stringify(rawText).slice(1, -1);
791
+ const output = templateContent.replaceAll(PURPOSE_PLACEHOLDER, replacementText);
792
+ const outputPath = join3(agentEnvDir, STATUS_BAR_JSON);
793
+ await deps.writeFile(outputPath, output, "utf-8");
794
+ }
795
+
655
796
  // src/lib/workspace.ts
656
- import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2 } from "fs/promises";
797
+ import { createHash } from "crypto";
798
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile4, rm, stat as stat2 } from "fs/promises";
657
799
  import { homedir } from "os";
658
- import { join as join3 } from "path";
800
+ import { join as join4 } from "path";
659
801
  var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
660
802
  var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
661
803
  function validateNameSegment(value, label) {
@@ -668,8 +810,38 @@ function validateNameSegment(value, label) {
668
810
  );
669
811
  }
670
812
  }
813
+ function deriveRepoSlug(url) {
814
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
815
+ const lastSlash = cleaned.lastIndexOf("/");
816
+ const lastColon = cleaned.lastIndexOf(":");
817
+ const lastSeparator = Math.max(lastSlash, lastColon);
818
+ if (lastSeparator === -1) {
819
+ if (!cleaned) {
820
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
821
+ }
822
+ return compressSlug(cleaned.toLowerCase());
823
+ }
824
+ const repoName = cleaned.slice(lastSeparator + 1);
825
+ if (!repoName) {
826
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
827
+ }
828
+ return compressSlug(repoName.toLowerCase());
829
+ }
830
+ function compressSlug(slug, maxLength = MAX_REPO_SLUG_LENGTH) {
831
+ if (slug.length <= maxLength) {
832
+ return slug;
833
+ }
834
+ const hash = createHash("sha256").update(slug).digest("hex").slice(0, 6);
835
+ const overhead = 8;
836
+ const available = Math.max(0, maxLength - overhead);
837
+ const prefixLen = Math.ceil(available / 2);
838
+ const suffixLen = available - prefixLen;
839
+ const prefix = slug.slice(0, prefixLen);
840
+ const suffix = slug.slice(slug.length - suffixLen);
841
+ return `${prefix}_${hash}_${suffix}`;
842
+ }
671
843
  function getWorkspacesBaseDir(deps = defaultFsDeps2) {
672
- return join3(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
844
+ return join4(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
673
845
  }
674
846
  function deriveWorkspaceName(repo, instance) {
675
847
  validateNameSegment(repo, "repo");
@@ -681,15 +853,15 @@ function deriveContainerName(workspaceName) {
681
853
  }
682
854
  function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
683
855
  const name = deriveWorkspaceName(repo, instance);
684
- const root = join3(getWorkspacesBaseDir(deps), name);
685
- const agentEnvDir = join3(root, AGENT_ENV_DIR);
686
- const stateFile = join3(agentEnvDir, STATE_FILE);
856
+ const root = join4(getWorkspacesBaseDir(deps), name);
857
+ const agentEnvDir = join4(root, AGENT_ENV_DIR);
858
+ const stateFile = join4(agentEnvDir, STATE_FILE);
687
859
  return { root, name, agentEnvDir, stateFile };
688
860
  }
689
861
  function getWorkspacePathByName(workspaceName, deps = defaultFsDeps2) {
690
- const root = join3(getWorkspacesBaseDir(deps), workspaceName);
691
- const agentEnvDir = join3(root, AGENT_ENV_DIR);
692
- const stateFile = join3(agentEnvDir, STATE_FILE);
862
+ const root = join4(getWorkspacesBaseDir(deps), workspaceName);
863
+ const agentEnvDir = join4(root, AGENT_ENV_DIR);
864
+ const stateFile = join4(agentEnvDir, STATE_FILE);
693
865
  return { root, name: workspaceName, agentEnvDir, stateFile };
694
866
  }
695
867
  async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
@@ -716,6 +888,108 @@ async function scanWorkspaces(deps = defaultFsDeps2) {
716
888
  throw err;
717
889
  }
718
890
  }
891
+ function looksLikeUrl(value) {
892
+ return value.includes("/") || value.includes(":");
893
+ }
894
+ async function resolveRepo(opts, executor) {
895
+ const repoFlag = opts.repo?.trim();
896
+ if (repoFlag !== void 0 && repoFlag !== "") {
897
+ if (looksLikeUrl(repoFlag)) {
898
+ try {
899
+ const slug2 = deriveRepoSlug(repoFlag);
900
+ return { resolved: true, repoSlug: slug2 };
901
+ } catch {
902
+ return {
903
+ resolved: false,
904
+ error: {
905
+ code: "INVALID_REPO",
906
+ message: `Cannot derive repo slug from: ${repoFlag}`,
907
+ suggestion: "Provide a valid git URL or repo slug."
908
+ }
909
+ };
910
+ }
911
+ }
912
+ const slug = repoFlag.toLowerCase();
913
+ if (!VALID_NAME_PATTERN.test(slug)) {
914
+ return {
915
+ resolved: false,
916
+ error: {
917
+ code: "INVALID_REPO",
918
+ message: `Invalid repo slug: "${repoFlag}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`,
919
+ suggestion: "Provide a valid repo slug or git URL."
920
+ }
921
+ };
922
+ }
923
+ return { resolved: true, repoSlug: slug };
924
+ }
925
+ if (opts.cwd) {
926
+ const result = await executor("git", ["remote", "get-url", "origin"], {
927
+ cwd: opts.cwd
928
+ });
929
+ if (result.ok && result.stdout.trim()) {
930
+ try {
931
+ const slug = deriveRepoSlug(result.stdout.trim());
932
+ return { resolved: true, repoSlug: slug };
933
+ } catch {
934
+ }
935
+ }
936
+ }
937
+ return { resolved: false };
938
+ }
939
+ var defaultResolveInstanceDeps = {
940
+ fsDeps: defaultFsDeps2,
941
+ readFile: readFile4
942
+ };
943
+ async function resolveInstance(instanceName, repoSlug, deps = defaultResolveInstanceDeps) {
944
+ const workspaces = await scanWorkspaces(deps.fsDeps);
945
+ if (workspaces.includes(instanceName)) {
946
+ return { found: true, workspaceName: instanceName };
947
+ }
948
+ if (repoSlug) {
949
+ const expectedName = `${repoSlug}-${instanceName}`;
950
+ if (workspaces.includes(expectedName)) {
951
+ return { found: true, workspaceName: expectedName };
952
+ }
953
+ }
954
+ const matches = [];
955
+ for (const wsName of workspaces) {
956
+ const wsPath = getWorkspacePathByName(wsName, deps.fsDeps);
957
+ try {
958
+ const content = await deps.readFile(wsPath.stateFile, "utf-8");
959
+ const state = JSON.parse(content);
960
+ if (typeof state === "object" && state !== null && state.instance === instanceName) {
961
+ matches.push(wsName);
962
+ if (matches.length > 1) break;
963
+ }
964
+ } catch {
965
+ }
966
+ }
967
+ if (matches.length === 1) {
968
+ return { found: true, workspaceName: matches[0] };
969
+ }
970
+ if (matches.length > 1) {
971
+ const repoSlugs = matches.map((ws) => {
972
+ const idx = ws.lastIndexOf(`-${instanceName}`);
973
+ return idx > 0 ? ws.slice(0, idx) : ws;
974
+ });
975
+ return {
976
+ found: false,
977
+ error: {
978
+ code: "AMBIGUOUS_INSTANCE",
979
+ message: `Multiple instances named '${instanceName}' exist across repos: ${repoSlugs.join(", ")}`,
980
+ suggestion: "Use --repo <slug> to specify which repo."
981
+ }
982
+ };
983
+ }
984
+ return {
985
+ found: false,
986
+ error: {
987
+ code: "WORKSPACE_NOT_FOUND",
988
+ message: `Instance '${instanceName}' not found`,
989
+ suggestion: "Use `agent-env list` to see available instances."
990
+ }
991
+ };
992
+ }
719
993
  var defaultDeleteFsDeps = { rm };
720
994
  async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
721
995
  await deps.rm(wsPath.root, { recursive: true, force: true });
@@ -726,7 +1000,8 @@ var MAX_PURPOSE_LENGTH = 200;
726
1000
  function createPurposeDefaultDeps() {
727
1001
  return {
728
1002
  workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
729
- stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 }
1003
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1004
+ statusBarDeps: { readFile: readFile5, writeFile: writeFile4 }
730
1005
  };
731
1006
  }
732
1007
  function validatePurposeLength(value) {
@@ -741,58 +1016,62 @@ function validatePurposeLength(value) {
741
1016
  }
742
1017
  return null;
743
1018
  }
744
- function mapLookupError(lookup, instanceName) {
745
- if (lookup.reason === "ambiguous") {
746
- return {
747
- ok: false,
748
- error: {
749
- code: "AMBIGUOUS_MATCH",
750
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
751
- suggestion: "Use the full workspace name to specify which instance."
752
- }
753
- };
754
- }
755
- return {
756
- ok: false,
757
- error: {
758
- code: "WORKSPACE_NOT_FOUND",
759
- message: `Instance '${instanceName}' not found`,
760
- suggestion: "Use `agent-env list` to see available instances."
761
- }
762
- };
763
- }
764
- async function getPurpose(instanceName, deps) {
765
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1019
+ async function getPurpose(instanceName, deps, repoSlug) {
1020
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1021
+ fsDeps: deps.workspaceFsDeps,
1022
+ readFile: deps.stateFsDeps.readFile
1023
+ });
766
1024
  if (!lookup.found) {
767
- return mapLookupError(lookup, instanceName);
1025
+ return { ok: false, error: lookup.error };
768
1026
  }
769
1027
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
770
1028
  const state = await readState(wsPath, deps.stateFsDeps);
771
1029
  return { ok: true, purpose: state.purpose };
772
1030
  }
773
- async function setPurpose(instanceName, value, deps) {
1031
+ async function setPurpose(instanceName, value, deps, repoSlug) {
774
1032
  const lengthError = validatePurposeLength(value);
775
1033
  if (lengthError) return lengthError;
776
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1034
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1035
+ fsDeps: deps.workspaceFsDeps,
1036
+ readFile: deps.stateFsDeps.readFile
1037
+ });
777
1038
  if (!lookup.found) {
778
- return mapLookupError(lookup, instanceName);
1039
+ return { ok: false, error: lookup.error };
779
1040
  }
780
1041
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
781
1042
  const state = await readState(wsPath, deps.stateFsDeps);
782
1043
  const cleared = value === "";
1044
+ const newPurpose = cleared ? null : value;
783
1045
  const updatedState = {
784
1046
  ...state,
785
- purpose: cleared ? null : value
1047
+ purpose: newPurpose
786
1048
  };
787
1049
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1050
+ try {
1051
+ await regenerateStatusBar(wsPath.root, wsPath.agentEnvDir, newPurpose, deps.statusBarDeps);
1052
+ } catch (err) {
1053
+ if (err.code === "TEMPLATE_NOT_FOUND") {
1054
+ return {
1055
+ ok: false,
1056
+ error: {
1057
+ code: "TEMPLATE_NOT_FOUND",
1058
+ message: err.message,
1059
+ suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1060
+ }
1061
+ };
1062
+ }
1063
+ throw err;
1064
+ }
788
1065
  return { ok: true, cleared };
789
1066
  }
790
1067
  function createContainerPurposeDefaultDeps() {
791
1068
  return {
792
- stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1069
+ stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
793
1070
  containerEnvDeps: { getEnv: (key) => process.env[key] },
1071
+ statusBarDeps: { readFile: readFile5, writeFile: writeFile4 },
794
1072
  statePath: CONTAINER_STATE_PATH,
795
- agentEnvDir: CONTAINER_AGENT_ENV_DIR
1073
+ agentEnvDir: CONTAINER_AGENT_ENV_DIR,
1074
+ workspaceRoot: process.cwd()
796
1075
  };
797
1076
  }
798
1077
  async function readContainerState(deps) {
@@ -843,39 +1122,78 @@ async function setContainerPurpose(value, deps) {
843
1122
  const read = await readContainerState(deps);
844
1123
  if (!read.ok) return read;
845
1124
  const cleared = value === "";
1125
+ const newPurpose = cleared ? null : value;
846
1126
  const updatedState = {
847
1127
  ...read.state,
848
- purpose: cleared ? null : value
1128
+ purpose: newPurpose
849
1129
  };
850
1130
  const wsPath = {
851
1131
  root: deps.agentEnvDir,
852
- name: read.state.name,
1132
+ name: `${read.state.repoSlug}-${read.state.instance}`,
853
1133
  agentEnvDir: deps.agentEnvDir,
854
1134
  stateFile: deps.statePath
855
1135
  };
856
1136
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1137
+ try {
1138
+ await regenerateStatusBar(deps.workspaceRoot, deps.agentEnvDir, newPurpose, deps.statusBarDeps);
1139
+ } catch (err) {
1140
+ if (err.code === "TEMPLATE_NOT_FOUND") {
1141
+ return {
1142
+ ok: false,
1143
+ error: {
1144
+ code: "TEMPLATE_NOT_FOUND",
1145
+ message: err.message,
1146
+ suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1147
+ }
1148
+ };
1149
+ }
1150
+ throw err;
1151
+ }
857
1152
  return { ok: true, cleared };
858
1153
  }
859
1154
 
860
1155
  // src/lib/create-instance.ts
861
- var GIT_CLONE_TIMEOUT = 12e4;
862
- function extractRepoName(url) {
863
- const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
864
- const lastSlash = cleaned.lastIndexOf("/");
865
- const lastColon = cleaned.lastIndexOf(":");
866
- const lastSeparator = Math.max(lastSlash, lastColon);
867
- if (lastSeparator === -1) {
868
- if (!cleaned) {
869
- throw new Error(`Cannot extract repository name from URL: ${url}`);
870
- }
871
- return cleaned;
1156
+ var VALID_INSTANCE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
1157
+ function validateCreateInputs(instanceName, purposeText) {
1158
+ if (!instanceName) {
1159
+ return {
1160
+ ok: false,
1161
+ error: {
1162
+ code: "INVALID_INSTANCE_NAME",
1163
+ message: "Instance name must not be empty."
1164
+ }
1165
+ };
872
1166
  }
873
- const repoName = cleaned.slice(lastSeparator + 1);
874
- if (!repoName) {
875
- throw new Error(`Cannot extract repository name from URL: ${url}`);
1167
+ if (!VALID_INSTANCE_NAME_PATTERN.test(instanceName)) {
1168
+ return {
1169
+ ok: false,
1170
+ error: {
1171
+ code: "INVALID_INSTANCE_NAME",
1172
+ message: `Invalid instance name: "${instanceName}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`
1173
+ }
1174
+ };
876
1175
  }
877
- return repoName;
1176
+ if (instanceName.length > MAX_INSTANCE_NAME_LENGTH) {
1177
+ return {
1178
+ ok: false,
1179
+ error: {
1180
+ code: "INSTANCE_NAME_TOO_LONG",
1181
+ message: `Instance name must be ${MAX_INSTANCE_NAME_LENGTH} characters or fewer (got ${instanceName.length})`
1182
+ }
1183
+ };
1184
+ }
1185
+ if (purposeText.length > MAX_PURPOSE_LENGTH) {
1186
+ return {
1187
+ ok: false,
1188
+ error: {
1189
+ code: "PURPOSE_TOO_LONG",
1190
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${purposeText.length})`
1191
+ }
1192
+ };
1193
+ }
1194
+ return null;
878
1195
  }
1196
+ var GIT_CLONE_TIMEOUT = 12e4;
879
1197
  async function resolveRepoUrl(repoArg, executor) {
880
1198
  if (repoArg !== ".") {
881
1199
  return { ok: true, url: repoArg };
@@ -927,8 +1245,8 @@ function createDefaultDeps() {
927
1245
  executor,
928
1246
  container: createContainerLifecycle(executor),
929
1247
  workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
930
- stateFsDeps: { readFile: readFile4, writeFile: writeFile4, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 },
931
- devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile4, stat: stat4, writeFile: writeFile4 },
1248
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 },
1249
+ devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile6, stat: stat4, writeFile: writeFile5 },
932
1250
  rm: rm2,
933
1251
  logger: {
934
1252
  warn: (msg) => console.warn(msg),
@@ -936,13 +1254,35 @@ function createDefaultDeps() {
936
1254
  }
937
1255
  };
938
1256
  }
939
- async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps) {
1257
+ async function resolveConfigChoice(hasConfig, baselineChoice, askUser) {
1258
+ if (!hasConfig) {
1259
+ return "baseline";
1260
+ }
1261
+ if (baselineChoice === "force-baseline") {
1262
+ return "baseline";
1263
+ }
1264
+ if (baselineChoice === "force-repo-config") {
1265
+ return "repo";
1266
+ }
1267
+ if (askUser) {
1268
+ return askUser();
1269
+ }
1270
+ return "repo";
1271
+ }
1272
+ function deriveBaselineChoice(baseline) {
1273
+ if (baseline === true) return "force-baseline";
1274
+ if (baseline === false) return "force-repo-config";
1275
+ return "ask-user";
1276
+ }
1277
+ async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps, baselineChoice = "ask-user", askUser) {
940
1278
  const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
941
- if (hasConfig) {
1279
+ const choice = await resolveConfigChoice(hasConfig, baselineChoice, askUser);
1280
+ if (choice === "repo") {
942
1281
  return { ok: true, configSource: "repo" };
943
1282
  }
944
1283
  try {
945
1284
  await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
1285
+ await copyStatusBarTemplate(wsPath.root, deps.devcontainerFsDeps);
946
1286
  } catch (err) {
947
1287
  await safeRollback(wsPath.root, deps.rm, deps.logger);
948
1288
  return {
@@ -954,9 +1294,9 @@ async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeT
954
1294
  };
955
1295
  }
956
1296
  try {
957
- await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
958
- await patchContainerEnv(
1297
+ await applyBaselinePatches(
959
1298
  wsPath.root,
1299
+ containerName,
960
1300
  {
961
1301
  AGENT_ENV_INSTANCE: wsPath.name,
962
1302
  AGENT_ENV_REPO: repoName,
@@ -977,44 +1317,7 @@ async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeT
977
1317
  }
978
1318
  return { ok: true, configSource: "baseline" };
979
1319
  }
980
- async function createInstance(instanceName, repoUrl, deps, options) {
981
- const purposeText = options?.purpose ?? "";
982
- const purposeState = options?.purpose ?? null;
983
- if (purposeText.length > MAX_PURPOSE_LENGTH) {
984
- return {
985
- ok: false,
986
- error: {
987
- code: "PURPOSE_TOO_LONG",
988
- message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${purposeText.length})`
989
- }
990
- };
991
- }
992
- let repoName;
993
- try {
994
- repoName = extractRepoName(repoUrl);
995
- } catch {
996
- return {
997
- ok: false,
998
- error: {
999
- code: "GIT_ERROR",
1000
- message: `Invalid repository URL: ${repoUrl}`,
1001
- suggestion: "Provide a valid HTTPS or SSH git URL."
1002
- }
1003
- };
1004
- }
1005
- const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
1006
- const containerName = deriveContainerName(wsPath.name);
1007
- const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
1008
- if (exists) {
1009
- return {
1010
- ok: false,
1011
- error: {
1012
- code: "INSTANCE_EXISTS",
1013
- message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
1014
- suggestion: `Choose a different instance name or remove the existing one first.`
1015
- }
1016
- };
1017
- }
1320
+ async function cloneAndPrepareWorkspace(repoUrl, wsPath, deps) {
1018
1321
  try {
1019
1322
  await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
1020
1323
  } catch (err) {
@@ -1054,12 +1357,63 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1054
1357
  }
1055
1358
  };
1056
1359
  }
1360
+ return { ok: true };
1361
+ }
1362
+ async function discoverContainerName(containerName, containerId, deps) {
1363
+ if (containerId) {
1364
+ const discovered = await deps.container.getContainerNameById(containerId);
1365
+ if (discovered) {
1366
+ return discovered;
1367
+ }
1368
+ } else {
1369
+ deps.logger?.warn(
1370
+ `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
1371
+ );
1372
+ }
1373
+ return containerName;
1374
+ }
1375
+ async function createInstance(instanceName, repoUrl, deps, options) {
1376
+ const purposeText = options?.purpose ?? "";
1377
+ const purposeState = options?.purpose ?? null;
1378
+ const validationError = validateCreateInputs(instanceName, purposeText);
1379
+ if (validationError) return validationError;
1380
+ let repoName;
1381
+ try {
1382
+ repoName = deriveRepoSlug(repoUrl);
1383
+ } catch {
1384
+ return {
1385
+ ok: false,
1386
+ error: {
1387
+ code: "GIT_ERROR",
1388
+ message: `Invalid repository URL: ${repoUrl}`,
1389
+ suggestion: "Provide a valid HTTPS or SSH git URL."
1390
+ }
1391
+ };
1392
+ }
1393
+ const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
1394
+ const containerName = deriveContainerName(wsPath.name);
1395
+ const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
1396
+ if (exists) {
1397
+ return {
1398
+ ok: false,
1399
+ error: {
1400
+ code: "INSTANCE_EXISTS",
1401
+ message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
1402
+ suggestion: `Choose a different instance name or remove the existing one first.`
1403
+ }
1404
+ };
1405
+ }
1406
+ const prepResult = await cloneAndPrepareWorkspace(repoUrl, wsPath, deps);
1407
+ if (!prepResult.ok) return prepResult;
1408
+ const baselineChoice = deriveBaselineChoice(options?.baseline);
1057
1409
  const configResult = await setupDevcontainerConfig(
1058
1410
  wsPath,
1059
1411
  containerName,
1060
1412
  repoName,
1061
1413
  purposeText,
1062
- deps
1414
+ deps,
1415
+ baselineChoice,
1416
+ options?.askUser
1063
1417
  );
1064
1418
  if (!configResult.ok) {
1065
1419
  return configResult;
@@ -1077,7 +1431,7 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1077
1431
  }
1078
1432
  };
1079
1433
  }
1080
- const baselineConfigPath = configSource === "baseline" ? join4(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1434
+ const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1081
1435
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1082
1436
  remoteEnv: {
1083
1437
  AGENT_INSTANCE: wsPath.name,
@@ -1088,18 +1442,12 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1088
1442
  if (!containerResult.ok) {
1089
1443
  return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
1090
1444
  }
1091
- let actualContainerName = containerName;
1092
- if (containerResult.containerId) {
1093
- const discovered = await deps.container.getContainerNameById(containerResult.containerId);
1094
- if (discovered) {
1095
- actualContainerName = discovered;
1096
- }
1097
- } else {
1098
- deps.logger?.warn(
1099
- `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
1100
- );
1101
- }
1102
- const state = createInitialState(wsPath.name, repoUrl, {
1445
+ const actualContainerName = await discoverContainerName(
1446
+ containerName,
1447
+ containerResult.containerId ?? void 0,
1448
+ deps
1449
+ );
1450
+ const state = createInitialState(instanceName, repoName, repoUrl, {
1103
1451
  containerName: actualContainerName,
1104
1452
  configSource,
1105
1453
  purpose: purposeState
@@ -1179,44 +1527,16 @@ function createAttachDefaultDeps() {
1179
1527
  executor,
1180
1528
  container: createContainerLifecycle(executor),
1181
1529
  workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1182
- stateFsDeps: { readFile: readFile5, writeFile: writeFile5, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1530
+ stateFsDeps: { readFile: readFile7, writeFile: writeFile6, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1183
1531
  };
1184
1532
  }
1185
- async function findWorkspaceByName(instanceName, deps) {
1186
- const workspaces = await scanWorkspaces(deps);
1187
- if (workspaces.includes(instanceName)) {
1188
- return { found: true, workspaceName: instanceName };
1189
- }
1190
- const suffixMatches = workspaces.filter((ws) => ws.endsWith(`-${instanceName}`));
1191
- if (suffixMatches.length === 1) {
1192
- return { found: true, workspaceName: suffixMatches[0] };
1193
- }
1194
- if (suffixMatches.length > 1) {
1195
- return { found: false, reason: "ambiguous", matches: suffixMatches };
1196
- }
1197
- return { found: false, reason: "not-found" };
1198
- }
1199
- async function attachInstance(instanceName, deps, onContainerStarting, onAttaching) {
1200
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1533
+ async function attachInstance(instanceName, deps, onContainerStarting, onAttaching, repoSlug) {
1534
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1535
+ fsDeps: deps.workspaceFsDeps,
1536
+ readFile: deps.stateFsDeps.readFile
1537
+ });
1201
1538
  if (!lookup.found) {
1202
- if (lookup.reason === "ambiguous") {
1203
- return {
1204
- ok: false,
1205
- error: {
1206
- code: "AMBIGUOUS_MATCH",
1207
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
1208
- suggestion: "Use the full workspace name to specify which instance."
1209
- }
1210
- };
1211
- }
1212
- return {
1213
- ok: false,
1214
- error: {
1215
- code: "WORKSPACE_NOT_FOUND",
1216
- message: `Instance '${instanceName}' not found`,
1217
- suggestion: "Use `agent-env list` to see available instances."
1218
- }
1219
- };
1539
+ return { ok: false, error: lookup.error };
1220
1540
  }
1221
1541
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1222
1542
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -1245,7 +1565,7 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1245
1565
  if (statusResult.status === "stopped" || statusResult.status === "not-found") {
1246
1566
  onContainerStarting?.();
1247
1567
  const configSource = state.configSource ?? "baseline";
1248
- const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1568
+ const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1249
1569
  const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1250
1570
  remoteEnv: { AGENT_INSTANCE: wsPath.name },
1251
1571
  configPath: baselineConfigPath
@@ -1274,9 +1594,28 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1274
1594
  return { ok: true };
1275
1595
  }
1276
1596
 
1597
+ // src/lib/command-helpers.ts
1598
+ async function resolveRepoOrExit(opts) {
1599
+ const executor = createExecutor();
1600
+ const repoResult = await resolveRepo(opts, executor);
1601
+ if (repoResult.resolved) {
1602
+ return repoResult.repoSlug;
1603
+ }
1604
+ if ("error" in repoResult && repoResult.error) {
1605
+ console.error(
1606
+ formatError(
1607
+ createError(repoResult.error.code, repoResult.error.message, repoResult.error.suggestion)
1608
+ )
1609
+ );
1610
+ process.exit(1);
1611
+ }
1612
+ return void 0;
1613
+ }
1614
+
1277
1615
  // src/commands/attach.ts
1278
- var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").action(async (name) => {
1616
+ var attachCommand = new Command("attach").description("Attach to an instance's tmux session").argument("<name>", "Instance name to attach to").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(async (name, options) => {
1279
1617
  const deps = createAttachDefaultDeps();
1618
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
1280
1619
  const result = await attachInstance(
1281
1620
  name,
1282
1621
  deps,
@@ -1286,7 +1625,8 @@ var attachCommand = new Command("attach").description("Attach to an instance's t
1286
1625
  () => {
1287
1626
  console.log();
1288
1627
  console.log("Attaching to tmux session...");
1289
- }
1628
+ },
1629
+ repoSlug
1290
1630
  );
1291
1631
  if (!result.ok) {
1292
1632
  const { code, message, suggestion } = result.error;
@@ -1474,21 +1814,144 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
1474
1814
 
1475
1815
  // src/commands/create.ts
1476
1816
  import { Command as Command3 } from "commander";
1477
- var createCommand = new Command3("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url>", 'Git repository URL to clone (use "." for current directory)').option("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").action(async (name, options) => {
1817
+ import { createInterface } from "readline";
1818
+
1819
+ // src/lib/list-repos.ts
1820
+ async function listRepos(deps) {
1821
+ try {
1822
+ const wsFsDeps = deps?.workspaceFsDeps;
1823
+ const stateFsDeps = deps?.stateFsDeps;
1824
+ const workspaceNames = (await scanWorkspaces(wsFsDeps)).sort();
1825
+ if (workspaceNames.length === 0) {
1826
+ return { ok: true, repos: [] };
1827
+ }
1828
+ const repoMap = /* @__PURE__ */ new Map();
1829
+ for (const wsName of workspaceNames) {
1830
+ const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1831
+ const state = await readState(wsPath, stateFsDeps);
1832
+ if (state.repoSlug === "unknown") {
1833
+ continue;
1834
+ }
1835
+ const existing = repoMap.get(state.repoSlug);
1836
+ if (existing) {
1837
+ existing.count += 1;
1838
+ } else {
1839
+ repoMap.set(state.repoSlug, { url: state.repoUrl, count: 1 });
1840
+ }
1841
+ }
1842
+ const repos = Array.from(repoMap.entries()).map(([slug, { url, count }]) => ({
1843
+ slug,
1844
+ url,
1845
+ instanceCount: count
1846
+ })).sort((a, b) => a.slug.localeCompare(b.slug));
1847
+ return { ok: true, repos };
1848
+ } catch (err) {
1849
+ const message = err instanceof Error ? err.message : String(err);
1850
+ return {
1851
+ ok: false,
1852
+ repos: null,
1853
+ error: { code: "LIST_REPOS_ERROR", message: `Failed to list repos: ${message}` }
1854
+ };
1855
+ }
1856
+ }
1857
+
1858
+ // src/lib/resolve-repo-arg.ts
1859
+ function isRepoUrl(value) {
1860
+ return value.includes("://") || value.startsWith("git@");
1861
+ }
1862
+ async function resolveRepoArg(repoArg, deps) {
1863
+ if (repoArg === ".") {
1864
+ return { ok: true, url: ".", resolvedFromSlug: false };
1865
+ }
1866
+ if (isRepoUrl(repoArg)) {
1867
+ return { ok: true, url: repoArg, resolvedFromSlug: false };
1868
+ }
1869
+ const listFn = deps?.listRepos ?? listRepos;
1870
+ const result = await listFn();
1871
+ if (!result.ok) {
1872
+ return {
1873
+ ok: false,
1874
+ error: {
1875
+ code: "REPO_LOOKUP_ERROR",
1876
+ message: `Failed to look up repo registry: ${result.error.message}`,
1877
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
1878
+ }
1879
+ };
1880
+ }
1881
+ const slugArg = repoArg.toLowerCase();
1882
+ const match = result.repos.find((r) => r.slug === slugArg);
1883
+ if (!match) {
1884
+ return {
1885
+ ok: false,
1886
+ error: {
1887
+ code: "REPO_NOT_FOUND",
1888
+ message: `Repository '${repoArg}' not found.`,
1889
+ suggestion: "Use a full URL or run `agent-env repos` to see tracked repos."
1890
+ }
1891
+ };
1892
+ }
1893
+ return { ok: true, url: match.url, resolvedFromSlug: true };
1894
+ }
1895
+
1896
+ // src/commands/create.ts
1897
+ function createBaselinePrompt() {
1898
+ return async () => {
1899
+ if (!process.stdin.isTTY) {
1900
+ return "repo";
1901
+ }
1902
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
1903
+ return new Promise((resolve2) => {
1904
+ console.log();
1905
+ console.log("This repo has a .devcontainer/ config.");
1906
+ console.log(" [1] Use repo config (default)");
1907
+ console.log(" [2] Use agent-env baseline");
1908
+ rl.question("Choose [1/2]: ", (answer) => {
1909
+ rl.close();
1910
+ resolve2(answer.trim() === "2" ? "baseline" : "repo");
1911
+ });
1912
+ });
1913
+ };
1914
+ }
1915
+ var createCommand = new Command3("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url|slug>", 'Git repo URL, registered slug, or "." for current directory').option("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").option("--baseline", "Force agent-env baseline config (ignore repo .devcontainer/)").option("--no-baseline", "Force repo config (skip baseline prompt)").action(async (name, options) => {
1478
1916
  if (!options.repo) {
1479
1917
  console.error(
1480
1918
  formatError(
1481
1919
  createError(
1482
1920
  "MISSING_OPTION",
1483
1921
  "The --repo flag is required.",
1484
- "Usage: agent-env create <name> --repo <url>"
1922
+ "Usage: agent-env create <name> --repo <url|slug>"
1923
+ )
1924
+ )
1925
+ );
1926
+ process.exit(1);
1927
+ }
1928
+ const argv = process.argv;
1929
+ const hasBaselineFlag = argv.includes("--baseline");
1930
+ const hasNoBaselineFlag = argv.includes("--no-baseline");
1931
+ if (hasBaselineFlag && hasNoBaselineFlag) {
1932
+ console.error(
1933
+ formatError(
1934
+ createError(
1935
+ "INVALID_OPTIONS",
1936
+ "Cannot specify both --baseline and --no-baseline",
1937
+ "Use --baseline to force agent-env baseline, or --no-baseline to use repo config."
1485
1938
  )
1486
1939
  )
1487
1940
  );
1488
1941
  process.exit(1);
1489
1942
  }
1490
1943
  const deps = createDefaultDeps();
1491
- const resolved = await resolveRepoUrl(options.repo, deps.executor);
1944
+ const slugResult = await resolveRepoArg(options.repo);
1945
+ if (!slugResult.ok) {
1946
+ const { code, message, suggestion } = slugResult.error;
1947
+ console.error(formatError(createError(code, message, suggestion)));
1948
+ process.exit(1);
1949
+ }
1950
+ const repoInput = slugResult.url;
1951
+ if (slugResult.resolvedFromSlug) {
1952
+ console.log(`Resolved repo '${options.repo}' \u2192 ${repoInput}`);
1953
+ }
1954
+ const resolved = await resolveRepoUrl(repoInput, deps.executor);
1492
1955
  if (!resolved.ok) {
1493
1956
  const { code, message, suggestion } = resolved.error;
1494
1957
  console.error(formatError(createError(code, message, suggestion)));
@@ -1496,7 +1959,12 @@ var createCommand = new Command3("create").description("Create a new isolated de
1496
1959
  }
1497
1960
  const repoUrl = resolved.url;
1498
1961
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
1499
- const result = await createInstance(name, repoUrl, deps, { purpose: options.purpose });
1962
+ const baselineOption = hasBaselineFlag ? true : hasNoBaselineFlag ? false : void 0;
1963
+ const result = await createInstance(name, repoUrl, deps, {
1964
+ purpose: options.purpose,
1965
+ baseline: baselineOption,
1966
+ askUser: createBaselinePrompt()
1967
+ });
1500
1968
  if (!result.ok) {
1501
1969
  const { code, message, suggestion } = result.error;
1502
1970
  console.error(formatError(createError(code, message, suggestion)));
@@ -1622,6 +2090,7 @@ function InstanceList({
1622
2090
  return { ...instance, indicators, indicatorText };
1623
2091
  });
1624
2092
  const nameWidth = Math.max(4, ...augmentedInstances.map((i) => i.name.length)) + 2;
2093
+ const repoWidth = Math.max(4, ...augmentedInstances.map((i) => i.repoSlug.length)) + 2;
1625
2094
  const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
1626
2095
  const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
1627
2096
  const lastAttachedWidth = Math.max(13, ...augmentedInstances.map((i) => formatLastAttached(i.lastAttached).length)) + 2;
@@ -1629,6 +2098,7 @@ function InstanceList({
1629
2098
  return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1630
2099
  /* @__PURE__ */ jsxs2(Box, { children: [
1631
2100
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
2101
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("REPO", repoWidth) }),
1632
2102
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
1633
2103
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
1634
2104
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
@@ -1637,6 +2107,7 @@ function InstanceList({
1637
2107
  ] }),
1638
2108
  augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
1639
2109
  /* @__PURE__ */ jsx2(Text2, { children: pad(instance.name, nameWidth) }),
2110
+ /* @__PURE__ */ jsx2(Text2, { color: "blue", children: pad(instance.repoSlug, repoWidth) }),
1640
2111
  /* @__PURE__ */ jsx2(Text2, { color: statusColor(instance.status), children: pad(statusLabel(instance.status, dockerAvailable), statusWidth) }),
1641
2112
  /* @__PURE__ */ jsx2(Box, { width: gitWidth, children: instance.indicators.map((ind, idx) => /* @__PURE__ */ jsxs2(Text2, { color: ind.color, children: [
1642
2113
  idx > 0 ? " " : "",
@@ -1789,7 +2260,7 @@ function parseBranches(result) {
1789
2260
  }
1790
2261
 
1791
2262
  // src/lib/list-instances.ts
1792
- async function listInstances(deps) {
2263
+ async function listInstances(deps, opts) {
1793
2264
  try {
1794
2265
  const container = deps?.container ?? createContainerLifecycle();
1795
2266
  const gitDetector = deps?.gitDetector ?? createGitStateDetector();
@@ -1800,43 +2271,55 @@ async function listInstances(deps) {
1800
2271
  return { ok: true, instances: [], dockerAvailable: true };
1801
2272
  }
1802
2273
  const dockerAvailable = await container.isDockerAvailable();
1803
- const instancePromises = workspaceNames.map(async (wsName) => {
2274
+ const repoFilter = opts?.repoFilter?.toLowerCase();
2275
+ const filteredWorkspaces = [];
2276
+ for (const wsName of workspaceNames) {
1804
2277
  const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1805
2278
  const state = await readState(wsPath, stateFsDeps);
1806
- const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
1807
- const gitPromise = gitDetector.getGitState(wsPath.root);
1808
- const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
1809
- let status;
1810
- if (!dockerAvailable || containerResult === null) {
1811
- status = "unknown";
1812
- } else if (!containerResult.ok) {
1813
- status = "unknown";
1814
- } else if (containerResult.status === "not-found") {
1815
- status = "orphaned";
1816
- } else {
1817
- status = containerResult.status;
2279
+ if (repoFilter && state.repoSlug.toLowerCase() !== repoFilter) {
2280
+ continue;
1818
2281
  }
1819
- let sshConnection = null;
1820
- if (status === "running" && containerResult && containerResult.ok) {
1821
- if ("22/tcp" in containerResult.ports) {
1822
- const orbDomains = containerResult.labels["dev.orbstack.domains"];
1823
- const hostname = orbDomains?.split(",")[0]?.trim() || `${state.containerName}.orb.local`;
1824
- sshConnection = `node@${hostname}`;
1825
- const hostPort = containerResult.ports["22/tcp"];
1826
- if (hostPort && hostPort !== "22") {
1827
- sshConnection += ` (localhost:${hostPort})`;
2282
+ filteredWorkspaces.push({ wsName, wsPath, state });
2283
+ }
2284
+ const instancePromises = filteredWorkspaces.map(
2285
+ async ({ wsName, wsPath, state }) => {
2286
+ const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
2287
+ const gitPromise = gitDetector.getGitState(wsPath.root);
2288
+ const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
2289
+ let status;
2290
+ if (!dockerAvailable || containerResult === null) {
2291
+ status = "unknown";
2292
+ } else if (!containerResult.ok) {
2293
+ status = "unknown";
2294
+ } else if (containerResult.status === "not-found") {
2295
+ status = "orphaned";
2296
+ } else {
2297
+ status = containerResult.status;
2298
+ }
2299
+ let sshConnection = null;
2300
+ if (status === "running" && containerResult && containerResult.ok) {
2301
+ if ("22/tcp" in containerResult.ports) {
2302
+ const orbDomains = containerResult.labels["dev.orbstack.domains"];
2303
+ const hostname = orbDomains?.split(",")[0]?.trim() || `${state.containerName}.orb.local`;
2304
+ sshConnection = `node@${hostname}`;
2305
+ const hostPort = containerResult.ports["22/tcp"];
2306
+ if (hostPort && hostPort !== "22") {
2307
+ sshConnection += ` (localhost:${hostPort})`;
2308
+ }
1828
2309
  }
1829
2310
  }
2311
+ return {
2312
+ name: wsName,
2313
+ repoSlug: state.repoSlug,
2314
+ repoUrl: state.repoUrl,
2315
+ status,
2316
+ lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
2317
+ purpose: state.purpose,
2318
+ gitState,
2319
+ sshConnection
2320
+ };
1830
2321
  }
1831
- return {
1832
- name: wsName,
1833
- status,
1834
- lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
1835
- purpose: state.purpose,
1836
- gitState,
1837
- sshConnection
1838
- };
1839
- });
2322
+ );
1840
2323
  const instances = await Promise.all(instancePromises);
1841
2324
  return { ok: true, instances, dockerAvailable };
1842
2325
  } catch (err) {
@@ -1851,8 +2334,10 @@ async function listInstances(deps) {
1851
2334
  }
1852
2335
 
1853
2336
  // src/commands/list.ts
1854
- var listCommand = new Command4("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").action(async (options) => {
1855
- const result = await listInstances();
2337
+ var listCommand = new Command4("list").alias("ps").description("List all instances with status").option("--json", "Output in JSON format").option("--repo <slug>", "Filter instances by repo slug").action(async (options) => {
2338
+ const result = await listInstances(void 0, {
2339
+ repoFilter: options.repo
2340
+ });
1856
2341
  if (!result.ok) {
1857
2342
  const error = createError(
1858
2343
  result.error.code,
@@ -1877,6 +2362,8 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1877
2362
  ok: true,
1878
2363
  data: result.instances.map((i) => ({
1879
2364
  name: i.name,
2365
+ repoSlug: i.repoSlug,
2366
+ repoUrl: i.repoUrl,
1880
2367
  status: i.status,
1881
2368
  lastAttached: i.lastAttached,
1882
2369
  purpose: i.purpose,
@@ -1906,11 +2393,11 @@ var defaultPurposeCommandDeps = {
1906
2393
  function createPurposeCommand(deps = defaultPurposeCommandDeps) {
1907
2394
  return new Command5("purpose").description(
1908
2395
  "Get or set the purpose/label for an instance. Inside a container: no instance name needed (agent-env purpose [value])"
1909
- ).argument("[nameOrValue]", "Instance name (host) or purpose value (container)").argument("[value]", "New purpose value (omit to get current, empty string to clear)").action(async (nameOrValue, value) => {
2396
+ ).argument("[nameOrValue]", "Instance name (host) or purpose value (container)").argument("[value]", "New purpose value (omit to get current, empty string to clear)").option("--repo <slug>", "Repo slug or URL to scope instance lookup (host mode only)").action(async (nameOrValue, value, options) => {
1910
2397
  if (deps.isInsideContainer()) {
1911
2398
  await handleContainerMode(nameOrValue);
1912
2399
  } else {
1913
- await handleHostMode(nameOrValue, value);
2400
+ await handleHostMode(nameOrValue, value, options?.repo);
1914
2401
  }
1915
2402
  });
1916
2403
  }
@@ -1925,7 +2412,7 @@ async function handleContainerMode(purposeValue) {
1925
2412
  handleSetResult(result);
1926
2413
  }
1927
2414
  }
1928
- async function handleHostMode(name, value) {
2415
+ async function handleHostMode(name, value, repo) {
1929
2416
  if (!name) {
1930
2417
  console.error(
1931
2418
  formatError(
@@ -1937,13 +2424,15 @@ async function handleHostMode(name, value) {
1937
2424
  )
1938
2425
  );
1939
2426
  process.exit(1);
2427
+ return;
1940
2428
  }
2429
+ const repoSlug = await resolveRepoOrExit({ repo, cwd: process.cwd() });
1941
2430
  const deps = createPurposeDefaultDeps();
1942
2431
  if (value === void 0) {
1943
- const result = await getPurpose(name, deps);
2432
+ const result = await getPurpose(name, deps, repoSlug);
1944
2433
  handleGetResult(result);
1945
2434
  } else {
1946
- const result = await setPurpose(name, value, deps);
2435
+ const result = await setPurpose(name, value, deps, repoSlug);
1947
2436
  handleSetResult(result);
1948
2437
  }
1949
2438
  }
@@ -1975,44 +2464,57 @@ function handleSetResult(result) {
1975
2464
  // src/commands/rebuild.ts
1976
2465
  import chalk from "chalk";
1977
2466
  import { Command as Command6 } from "commander";
1978
- import { createInterface } from "readline";
2467
+ import { createInterface as createInterface2 } from "readline";
1979
2468
 
1980
2469
  // src/lib/rebuild-instance.ts
1981
2470
  import {
1982
2471
  cp as cp3,
1983
2472
  mkdir as mkdir7,
1984
2473
  readdir as readdir6,
1985
- readFile as readFile6,
2474
+ readFile as readFile8,
1986
2475
  rename as rename5,
1987
2476
  rm as rm3,
1988
2477
  stat as stat6,
1989
- writeFile as writeFile6,
2478
+ writeFile as writeFile7,
1990
2479
  appendFile as appendFile5
1991
2480
  } from "fs/promises";
1992
2481
  import { homedir as homedir5 } from "os";
1993
- import { join as join6 } from "path";
2482
+ import { join as join7 } from "path";
1994
2483
  function createRebuildDefaultDeps() {
1995
2484
  const executor = createExecutor();
1996
2485
  return {
1997
2486
  executor,
1998
2487
  container: createContainerLifecycle(executor),
1999
2488
  workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
2000
- stateFsDeps: { readFile: readFile6, writeFile: writeFile6, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
2001
- devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile6, stat: stat6, writeFile: writeFile6 },
2489
+ stateFsDeps: { readFile: readFile8, writeFile: writeFile7, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
2490
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile8, stat: stat6, writeFile: writeFile7 },
2002
2491
  rm: rm3,
2003
2492
  rename: rename5,
2004
2493
  logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
2005
2494
  };
2006
2495
  }
2007
- async function refreshConfig(wsRoot, containerName, configSource, deps) {
2496
+ async function refreshConfig(wsRoot, containerName, configSource, envVars, deps) {
2008
2497
  if (configSource === "baseline") {
2009
- const agentEnvDir = join6(wsRoot, AGENT_ENV_DIR);
2498
+ const agentEnvDir = join7(wsRoot, AGENT_ENV_DIR);
2010
2499
  try {
2011
2500
  await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
2012
2501
  await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
2013
2502
  recursive: true
2014
2503
  });
2015
- await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
2504
+ const templatePath = join7(agentEnvDir, "statusBar.template.json");
2505
+ try {
2506
+ await deps.devcontainerFsDeps.stat(templatePath);
2507
+ } catch (err) {
2508
+ if (err.code !== "ENOENT") throw err;
2509
+ await copyStatusBarTemplate(wsRoot, deps.devcontainerFsDeps);
2510
+ }
2511
+ await applyBaselinePatches(
2512
+ wsRoot,
2513
+ containerName,
2514
+ envVars,
2515
+ deps.devcontainerFsDeps,
2516
+ AGENT_ENV_DIR
2517
+ );
2016
2518
  } catch (err) {
2017
2519
  return {
2018
2520
  ok: false,
@@ -2035,10 +2537,10 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
2035
2537
  }
2036
2538
  };
2037
2539
  }
2038
- const devcontainerDir = join6(wsRoot, ".devcontainer");
2540
+ const devcontainerDir = join7(wsRoot, ".devcontainer");
2039
2541
  const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
2040
2542
  if (dirExists) {
2041
- const jsonExists = await deps.devcontainerFsDeps.stat(join6(devcontainerDir, "devcontainer.json")).catch(() => null);
2543
+ const jsonExists = await deps.devcontainerFsDeps.stat(join7(devcontainerDir, "devcontainer.json")).catch(() => null);
2042
2544
  if (!jsonExists) {
2043
2545
  return {
2044
2546
  ok: false,
@@ -2053,27 +2555,13 @@ async function refreshConfig(wsRoot, containerName, configSource, deps) {
2053
2555
  }
2054
2556
  return { ok: true };
2055
2557
  }
2056
- async function lookupWorkspace(instanceName, deps) {
2057
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
2558
+ async function lookupWorkspace(instanceName, deps, repoSlug) {
2559
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2560
+ fsDeps: deps.workspaceFsDeps,
2561
+ readFile: deps.stateFsDeps.readFile
2562
+ });
2058
2563
  if (!lookup.found) {
2059
- if (lookup.reason === "ambiguous") {
2060
- return {
2061
- ok: false,
2062
- error: {
2063
- code: "AMBIGUOUS_MATCH",
2064
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
2065
- suggestion: "Use the full workspace name to specify which instance."
2066
- }
2067
- };
2068
- }
2069
- return {
2070
- ok: false,
2071
- error: {
2072
- code: "WORKSPACE_NOT_FOUND",
2073
- message: `Instance '${instanceName}' not found`,
2074
- suggestion: "Use `agent-env list` to see available instances."
2075
- }
2076
- };
2564
+ return { ok: false, error: lookup.error };
2077
2565
  }
2078
2566
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2079
2567
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -2152,14 +2640,33 @@ async function teardownContainer(containerName, container, statusResult) {
2152
2640
  }
2153
2641
  return { ok: true };
2154
2642
  }
2155
- async function rebuildInstance(instanceName, deps, options) {
2643
+ async function startAndDiscoverContainer(wsPath, containerName, configSource, purpose, buildNoCache, container) {
2644
+ const baselineConfigPath = configSource === "baseline" ? join7(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2645
+ const containerResult = await container.devcontainerUp(wsPath.root, containerName, {
2646
+ buildNoCache,
2647
+ remoteEnv: { AGENT_INSTANCE: wsPath.name, AGENT_ENV_PURPOSE: purpose },
2648
+ configPath: baselineConfigPath
2649
+ });
2650
+ if (!containerResult.ok) {
2651
+ return { ok: false, error: containerResult.error };
2652
+ }
2653
+ let actualName = containerName;
2654
+ if (containerResult.containerId) {
2655
+ const discovered = await container.getContainerNameById(containerResult.containerId);
2656
+ if (discovered) {
2657
+ actualName = discovered;
2658
+ }
2659
+ }
2660
+ return { ok: true, containerName: actualName };
2661
+ }
2662
+ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2156
2663
  const {
2157
2664
  force = false,
2158
2665
  configSource: overrideConfigSource,
2159
2666
  pull = true,
2160
2667
  noCache = true
2161
2668
  } = options ?? {};
2162
- const wsLookup = await lookupWorkspace(instanceName, deps);
2669
+ const wsLookup = await lookupWorkspace(instanceName, deps, repoSlug);
2163
2670
  if (!wsLookup.ok) {
2164
2671
  return { ok: false, error: wsLookup.error };
2165
2672
  }
@@ -2187,7 +2694,12 @@ async function rebuildInstance(instanceName, deps, options) {
2187
2694
  }
2188
2695
  };
2189
2696
  }
2190
- const configResult = await refreshConfig(wsPath.root, containerName, configSource, deps);
2697
+ const envVars = {
2698
+ AGENT_ENV_INSTANCE: wsPath.name,
2699
+ AGENT_ENV_REPO: state.repoSlug ?? "",
2700
+ AGENT_ENV_PURPOSE: state.purpose ?? ""
2701
+ };
2702
+ const configResult = await refreshConfig(wsPath.root, containerName, configSource, envVars, deps);
2191
2703
  if (!configResult.ok) {
2192
2704
  return { ok: false, error: configResult.error };
2193
2705
  }
@@ -2213,36 +2725,26 @@ async function rebuildInstance(instanceName, deps, options) {
2213
2725
  if (!teardownResult.ok) {
2214
2726
  return { ok: false, error: teardownResult.error, wasRunning };
2215
2727
  }
2216
- const buildNoCache = noCache && hasDockerfile;
2217
- const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2218
- const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
2219
- buildNoCache,
2220
- remoteEnv: { AGENT_INSTANCE: wsPath.name },
2221
- configPath: baselineConfigPath
2222
- });
2223
- if (!containerResult.ok) {
2224
- return {
2225
- ok: false,
2226
- error: containerResult.error,
2227
- wasRunning
2228
- };
2229
- }
2230
- let actualContainerName = containerName;
2231
- if (containerResult.containerId) {
2232
- const discovered = await deps.container.getContainerNameById(containerResult.containerId);
2233
- if (discovered) {
2234
- actualContainerName = discovered;
2235
- }
2728
+ const startResult = await startAndDiscoverContainer(
2729
+ wsPath,
2730
+ containerName,
2731
+ configSource,
2732
+ state.purpose ?? "",
2733
+ noCache && hasDockerfile,
2734
+ deps.container
2735
+ );
2736
+ if (!startResult.ok) {
2737
+ return { ok: false, error: startResult.error, wasRunning };
2236
2738
  }
2237
2739
  const updatedState = {
2238
2740
  ...state,
2239
- containerName: actualContainerName,
2741
+ containerName: startResult.containerName,
2240
2742
  lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
2241
2743
  };
2242
2744
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
2243
2745
  return {
2244
2746
  ok: true,
2245
- containerName: actualContainerName,
2747
+ containerName: startResult.containerName,
2246
2748
  wasRunning
2247
2749
  };
2248
2750
  }
@@ -2250,7 +2752,7 @@ async function rebuildInstance(instanceName, deps, options) {
2250
2752
  // src/commands/rebuild.ts
2251
2753
  function promptForConfirmation(instanceName) {
2252
2754
  return new Promise((resolve2) => {
2253
- const rl = createInterface({
2755
+ const rl = createInterface2({
2254
2756
  input: process.stdin,
2255
2757
  output: process.stderr
2256
2758
  });
@@ -2269,9 +2771,10 @@ Any active sessions will be lost. Continue? (y/N) `,
2269
2771
  });
2270
2772
  });
2271
2773
  }
2272
- 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").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").action(
2774
+ 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").option("--no-pull", "Skip pulling fresh base images").option("--use-cache", "Allow Docker build layer cache reuse").option("--repo <slug>", "Repo slug or URL to scope instance lookup").action(
2273
2775
  async (name, options) => {
2274
2776
  const deps = createRebuildDefaultDeps();
2777
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2275
2778
  let confirmed = false;
2276
2779
  if (!options.yes && !options.force && process.stdin.isTTY) {
2277
2780
  confirmed = await promptForConfirmation(name);
@@ -2291,7 +2794,7 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2291
2794
  } else {
2292
2795
  console.log(`Rebuilding instance '${name}'...`);
2293
2796
  }
2294
- const result = await rebuildInstance(name, deps, rebuildOptions);
2797
+ const result = await rebuildInstance(name, deps, rebuildOptions, repoSlug);
2295
2798
  if (!result.ok) {
2296
2799
  if (result.error.code === "CONTAINER_RUNNING") {
2297
2800
  console.error("");
@@ -2315,21 +2818,21 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2315
2818
  // src/commands/remove.ts
2316
2819
  import chalk3 from "chalk";
2317
2820
  import { Command as Command7 } from "commander";
2318
- import { createInterface as createInterface2 } from "readline";
2821
+ import { createInterface as createInterface3 } from "readline";
2319
2822
 
2320
2823
  // src/lib/audit-log.ts
2321
2824
  import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
2322
2825
  import { homedir as homedir6 } from "os";
2323
- import { join as join7 } from "path";
2826
+ import { join as join8 } from "path";
2324
2827
  function createAuditLogDefaultDeps() {
2325
2828
  return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
2326
2829
  }
2327
2830
  function getAuditLogPath(deps) {
2328
- return join7(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2831
+ return join8(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2329
2832
  }
2330
2833
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
2331
2834
  const logPath = getAuditLogPath(deps);
2332
- await deps.mkdir(join7(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2835
+ await deps.mkdir(join8(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2333
2836
  const line = JSON.stringify(entry) + "\n";
2334
2837
  await deps.appendFile(logPath, line, "utf-8");
2335
2838
  }
@@ -2344,7 +2847,7 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
2344
2847
  }
2345
2848
 
2346
2849
  // src/lib/remove-instance.ts
2347
- import { mkdir as mkdir9, readdir as readdir7, readFile as readFile7, rm as rm4, stat as stat7 } from "fs/promises";
2850
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile9, rm as rm4, stat as stat7 } from "fs/promises";
2348
2851
  import { homedir as homedir7 } from "os";
2349
2852
  function createRemoveDefaultDeps() {
2350
2853
  const executor = createExecutor();
@@ -2353,7 +2856,7 @@ function createRemoveDefaultDeps() {
2353
2856
  container: createContainerLifecycle(executor),
2354
2857
  gitDetector: createGitStateDetector(executor),
2355
2858
  workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
2356
- stateFsDeps: { readFile: readFile7 },
2859
+ stateFsDeps: { readFile: readFile9 },
2357
2860
  deleteFsDeps: { rm: rm4 }
2358
2861
  };
2359
2862
  }
@@ -2391,27 +2894,13 @@ function evaluateSafetyChecks(gitState) {
2391
2894
  }
2392
2895
  return blockers;
2393
2896
  }
2394
- async function removeInstance(instanceName, deps, force = false) {
2395
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
2897
+ async function removeInstance(instanceName, deps, force = false, repoSlug) {
2898
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2899
+ fsDeps: deps.workspaceFsDeps,
2900
+ readFile: deps.stateFsDeps.readFile
2901
+ });
2396
2902
  if (!lookup.found) {
2397
- if (lookup.reason === "ambiguous") {
2398
- return {
2399
- ok: false,
2400
- error: {
2401
- code: "AMBIGUOUS_MATCH",
2402
- message: `Multiple instances match '${instanceName}': ${lookup.matches.join(", ")}`,
2403
- suggestion: "Use the full workspace name to specify which instance."
2404
- }
2405
- };
2406
- }
2407
- return {
2408
- ok: false,
2409
- error: {
2410
- code: "WORKSPACE_NOT_FOUND",
2411
- message: `Instance '${instanceName}' not found`,
2412
- suggestion: "Use `agent-env list` to see available instances."
2413
- }
2414
- };
2903
+ return { ok: false, error: lookup.error };
2415
2904
  }
2416
2905
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2417
2906
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -2587,7 +3076,7 @@ function formatSafetyReport(instanceName, blockers, gitState) {
2587
3076
  function promptForConfirmation2(instanceName) {
2588
3077
  return new Promise((resolve2) => {
2589
3078
  let resolved = false;
2590
- const rl = createInterface2({
3079
+ const rl = createInterface3({
2591
3080
  input: process.stdin,
2592
3081
  output: process.stderr
2593
3082
  });
@@ -2647,7 +3136,7 @@ async function resolveConfirmation(name, options) {
2647
3136
  }
2648
3137
  return "typed-name";
2649
3138
  }
2650
- 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(
3139
+ var removeCommand = new Command7("remove").description("Remove an instance with safety checks").argument("<name>", "Instance name to remove").option("--repo <slug>", "Repo slug or URL to scope instance lookup").option("--force", "Force removal, bypassing safety checks").option(
2651
3140
  "--yes",
2652
3141
  "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
2653
3142
  ).action(async (name, options) => {
@@ -2664,8 +3153,9 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2664
3153
  process.exit(1);
2665
3154
  return;
2666
3155
  }
3156
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2667
3157
  const deps = createRemoveDefaultDeps();
2668
- const checkResult = await removeInstance(name, deps, false);
3158
+ const checkResult = await removeInstance(name, deps, false, repoSlug);
2669
3159
  if (checkResult.ok) {
2670
3160
  if (options.force) {
2671
3161
  console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
@@ -2697,7 +3187,7 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2697
3187
  process.exit(1);
2698
3188
  return;
2699
3189
  }
2700
- const forceResult = await removeInstance(name, deps, true);
3190
+ const forceResult = await removeInstance(name, deps, true, repoSlug);
2701
3191
  if (!forceResult.ok) {
2702
3192
  const { code, message, suggestion } = forceResult.error;
2703
3193
  console.error(formatError(createError(code, message, suggestion)));
@@ -2708,6 +3198,58 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2708
3198
  await writeAuditLog(name, gitState ?? null, confirmationMethod);
2709
3199
  });
2710
3200
 
3201
+ // src/commands/repos.ts
3202
+ import { Command as Command8 } from "commander";
3203
+ var reposCommand = new Command8("repos").description("List tracked repositories").option("--json", "Output in JSON format").action(async (options) => {
3204
+ const result = await listRepos();
3205
+ if (!result.ok) {
3206
+ const error = createError(
3207
+ result.error.code,
3208
+ result.error.message,
3209
+ "Check if ~/.agent-env/workspaces/ is accessible."
3210
+ );
3211
+ if (options.json) {
3212
+ const output = {
3213
+ ok: false,
3214
+ data: null,
3215
+ error: { code: error.code, message: error.message, suggestion: error.suggestion }
3216
+ };
3217
+ console.log(JSON.stringify(output, null, 2));
3218
+ } else {
3219
+ console.error(formatError(error));
3220
+ }
3221
+ process.exitCode = 1;
3222
+ return;
3223
+ }
3224
+ if (options.json) {
3225
+ const output = {
3226
+ ok: true,
3227
+ data: result.repos.map((r) => ({
3228
+ slug: r.slug,
3229
+ url: r.url,
3230
+ instanceCount: r.instanceCount
3231
+ })),
3232
+ error: null
3233
+ };
3234
+ console.log(JSON.stringify(output, null, 2));
3235
+ return;
3236
+ }
3237
+ if (result.repos.length === 0) {
3238
+ console.log(
3239
+ "No repositories tracked. Create an instance with: agent-env create <name> --repo <url|slug>"
3240
+ );
3241
+ return;
3242
+ }
3243
+ const slugWidth = Math.max(4, ...result.repos.map((r) => r.slug.length));
3244
+ const countWidth = 10;
3245
+ const header = `${"REPO".padEnd(slugWidth)} ${"INSTANCES".padEnd(countWidth)} URL`;
3246
+ console.log(header);
3247
+ for (const repo of result.repos) {
3248
+ const line = `${repo.slug.padEnd(slugWidth)} ${String(repo.instanceCount).padEnd(countWidth)} ${repo.url}`;
3249
+ console.log(line);
3250
+ }
3251
+ });
3252
+
2711
3253
  // src/components/InteractiveMenu.tsx
2712
3254
  import { Select } from "@inkjs/ui";
2713
3255
  import { Box as Box2, Text as Text3 } from "ink";
@@ -2890,6 +3432,7 @@ program.addCommand(attachCommand);
2890
3432
  program.addCommand(rebuildCommand);
2891
3433
  program.addCommand(removeCommand);
2892
3434
  program.addCommand(purposeCommand);
3435
+ program.addCommand(reposCommand);
2893
3436
  program.addCommand(completionCommand);
2894
3437
  program.action(async () => {
2895
3438
  if (!process.stdin.isTTY) {