@zookanalytics/agent-env 0.4.0 → 0.6.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.6.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 readFile8, rename as rename5, stat as stat5, writeFile as writeFile7 } from "fs/promises";
107
107
  import { homedir as homedir4 } from "os";
108
- import { join as join5 } from "path";
108
+ import { join as join7 } from "path";
109
109
 
110
110
  // src/lib/container.ts
111
111
  var DEVCONTAINER_UP_TIMEOUT = 3e5;
@@ -406,21 +406,40 @@ function createContainerLifecycle(executor = createExecutor()) {
406
406
 
407
407
  // src/lib/create-instance.ts
408
408
  import {
409
+ access as access3,
409
410
  appendFile as appendFile3,
410
411
  cp as cp2,
411
412
  mkdir as mkdir5,
412
413
  readdir as readdir4,
413
- readFile as readFile4,
414
- rename as rename3,
414
+ readFile as readFile7,
415
+ rename as rename4,
415
416
  rm as rm2,
416
417
  stat as stat4,
417
- writeFile as writeFile4
418
+ writeFile as writeFile6
418
419
  } from "fs/promises";
419
420
  import { homedir as homedir3 } from "os";
420
- import { dirname as dirname2, join as join4 } from "path";
421
+ import { dirname as dirname2, join as join6 } from "path";
422
+
423
+ // src/lib/devcontainer-merge.ts
424
+ import { parse as parseJsonc2 } from "jsonc-parser";
425
+ import { constants } from "fs";
426
+ import { access as access2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
427
+ import { createRequire } from "module";
428
+ import { join as join2 } from "path";
429
+
430
+ // src/lib/container-env.ts
431
+ var CONTAINER_STATE_PATH = process.env.AGENT_ENV_STATE_PATH || "/etc/agent-env/state.json";
432
+ var CONTAINER_AGENT_ENV_DIR = process.env.AGENT_ENV_CONTAINER_DIR || "/etc/agent-env";
433
+ var defaultContainerEnvDeps = {
434
+ getEnv: (key) => process.env[key]
435
+ };
436
+ function isInsideContainer(deps = defaultContainerEnvDeps) {
437
+ return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
438
+ }
421
439
 
422
440
  // src/lib/devcontainer.ts
423
441
  import { parse as parseJsonc } from "jsonc-parser";
442
+ import { accessSync } from "fs";
424
443
  import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
425
444
  import { dirname, join } from "path";
426
445
  import { fileURLToPath } from "url";
@@ -431,14 +450,24 @@ var WORKSPACES_DIR = "workspaces";
431
450
  var STATE_FILE = "state.json";
432
451
  var STATE_FILE_TMP = "state.json.tmp";
433
452
  var CONTAINER_PREFIX = "ae-";
453
+ var MAX_INSTANCE_NAME_LENGTH = 20;
454
+ var MAX_REPO_SLUG_LENGTH = 39;
455
+ var MAX_CONTAINER_NAME_LENGTH = 63;
456
+ if (CONTAINER_PREFIX.length + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH !== MAX_CONTAINER_NAME_LENGTH) {
457
+ throw new Error(
458
+ "BUG: MAX_CONTAINER_NAME_LENGTH does not equal CONTAINER_PREFIX + MAX_REPO_SLUG_LENGTH + 1 + MAX_INSTANCE_NAME_LENGTH"
459
+ );
460
+ }
434
461
  function createFallbackState(workspaceName) {
435
462
  return {
436
- name: workspaceName,
437
- repo: "unknown",
463
+ instance: workspaceName,
464
+ repoSlug: "unknown",
465
+ repoUrl: "unknown",
438
466
  createdAt: "unknown",
439
467
  lastAttached: "unknown",
440
468
  purpose: null,
441
- containerName: `${CONTAINER_PREFIX}${workspaceName}`
469
+ containerName: `${CONTAINER_PREFIX}${workspaceName}`,
470
+ repoConfigDetected: false
442
471
  };
443
472
  }
444
473
 
@@ -447,62 +476,57 @@ var defaultFsDeps = { access, cp, mkdir, readdir, readFile, stat, writeFile };
447
476
  var DEVCONTAINER_DIR = ".devcontainer";
448
477
  var DEVCONTAINER_JSON = "devcontainer.json";
449
478
  var DOT_DEVCONTAINER_JSON = ".devcontainer.json";
450
- function getBaselineConfigPath() {
451
- const currentFile = fileURLToPath(import.meta.url);
452
- const packageRoot = dirname(dirname(dirname(currentFile)));
453
- return join(packageRoot, "config", "baseline");
454
- }
455
- async function hasDevcontainerConfig(workspacePath, deps = defaultFsDeps) {
456
- try {
457
- const dirStats = await deps.stat(join(workspacePath, DEVCONTAINER_DIR));
458
- if (dirStats.isDirectory()) {
459
- return true;
460
- }
461
- } catch {
462
- }
463
- try {
464
- const fileStats = await deps.stat(join(workspacePath, DEVCONTAINER_JSON));
465
- if (fileStats.isFile()) {
466
- return true;
467
- }
468
- } catch {
469
- }
470
- try {
471
- const dotFileStats = await deps.stat(join(workspacePath, DOT_DEVCONTAINER_JSON));
472
- if (dotFileStats.isFile()) {
473
- return true;
479
+ var cachedPackageRoot;
480
+ function getPackageRoot(checkAccess = accessSync) {
481
+ if (cachedPackageRoot) return cachedPackageRoot;
482
+ let dir = dirname(fileURLToPath(import.meta.url));
483
+ const startDir = dir;
484
+ for (; ; ) {
485
+ try {
486
+ checkAccess(join(dir, "package.json"));
487
+ cachedPackageRoot = dir;
488
+ return dir;
489
+ } catch (err) {
490
+ const code = err?.code;
491
+ if (code === "EACCES" || code === "EPERM") {
492
+ throw new Error(`Permission denied accessing ${join(dir, "package.json")}`);
493
+ }
494
+ const parent = dirname(dir);
495
+ if (parent === dir) {
496
+ throw new Error(`Could not find package.json in ${startDir} or any parent directory`);
497
+ }
498
+ dir = parent;
474
499
  }
475
- } catch {
476
500
  }
477
- return false;
478
501
  }
479
- async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
480
- const baselinePath = getBaselineConfigPath();
502
+ function getBaselineConfigPath() {
503
+ return join(getPackageRoot(), "config", "baseline");
504
+ }
505
+ function getTemplatesPath() {
506
+ return join(getPackageRoot(), "config", "templates");
507
+ }
508
+ async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
509
+ const templatesPath = getTemplatesPath();
510
+ const srcFile = join(templatesPath, "statusBar.template.json");
481
511
  try {
482
- await deps.stat(baselinePath);
483
- } catch {
484
- throw new Error(`Baseline config not found at ${baselinePath}. Package may be corrupted.`);
512
+ await deps.stat(srcFile);
513
+ } catch (err) {
514
+ if (err.code === "ENOENT") return;
515
+ throw err;
485
516
  }
486
517
  const targetDir = join(workspacePath, AGENT_ENV_DIR);
487
518
  await deps.mkdir(targetDir, { recursive: true });
488
- await deps.cp(baselinePath, targetDir, { recursive: true });
519
+ await deps.cp(srcFile, join(targetDir, "statusBar.template.json"));
489
520
  }
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);
494
- const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
495
- const filtered = existing.filter((arg) => !arg.startsWith("--name="));
496
- config.runArgs = [...filtered, `--name=${containerName}`];
497
- await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
498
- }
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);
503
- const existing = typeof config.containerEnv === "object" && config.containerEnv !== null ? config.containerEnv : {};
504
- config.containerEnv = { ...existing, ...envVars };
505
- await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
521
+ async function copyManagedAssets(workspacePath, deps = defaultFsDeps) {
522
+ const baselinePath = getBaselineConfigPath();
523
+ const targetDir = join(workspacePath, AGENT_ENV_DIR);
524
+ await deps.mkdir(targetDir, { recursive: true });
525
+ await deps.cp(baselinePath, targetDir, {
526
+ recursive: true,
527
+ filter: (source) => !source.endsWith("devcontainer.json")
528
+ });
529
+ await copyStatusBarTemplate(workspacePath, deps);
506
530
  }
507
531
  async function resolveDockerfilePath(workspacePath, deps) {
508
532
  const candidates = [
@@ -574,32 +598,399 @@ function parseDockerfileImages(content, logger) {
574
598
  return [...images];
575
599
  }
576
600
 
577
- // 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";
579
- import { homedir as homedir2 } from "os";
580
-
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]
601
+ // src/lib/devcontainer-merge.ts
602
+ var defaultMergeDeps = { readFile: readFile2, writeFile: writeFile2, rename, access: access2 };
603
+ var STATUS_BAR_JSON_FILENAME = "statusBar.json";
604
+ var LABEL_LIFECYCLE_CMDS = {
605
+ postCreateCommand: "/usr/local/bin/post-create.sh",
606
+ postStartCommand: "sudo /usr/local/bin/start-sshd.sh; tmux new-session -d -s main 2>/dev/null || true"
586
607
  };
587
- function isInsideContainer(deps = defaultContainerEnvDeps) {
588
- return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
608
+ var COMPOSABLE_LIFECYCLE_CMDS = [
609
+ "postCreateCommand",
610
+ "postStartCommand",
611
+ "postAttachCommand",
612
+ "onCreateCommand",
613
+ "updateContentCommand"
614
+ ];
615
+ var AUTO_GENERATED_HEADER = "// AUTO-GENERATED by agent-env";
616
+ async function readRepoConfig(workspacePath, deps = defaultMergeDeps, logger) {
617
+ const candidates = [
618
+ join2(workspacePath, ".devcontainer", "devcontainer.json"),
619
+ join2(workspacePath, "devcontainer.json"),
620
+ join2(workspacePath, ".devcontainer.json")
621
+ ];
622
+ for (const candidate of candidates) {
623
+ let content;
624
+ try {
625
+ await deps.access(candidate, constants.F_OK);
626
+ content = await deps.readFile(candidate, "utf-8");
627
+ } catch (err) {
628
+ const code = err?.code;
629
+ if (code === "ENOENT") {
630
+ continue;
631
+ }
632
+ throw err;
633
+ }
634
+ if (content.startsWith(AUTO_GENERATED_HEADER)) {
635
+ logger?.warn(
636
+ `Skipping auto-generated config at ${candidate} \u2014 this appears to be agent-env's own output, not a repo config`
637
+ );
638
+ continue;
639
+ }
640
+ const errors = [];
641
+ const parsed = parseJsonc2(content, errors, { allowTrailingComma: true });
642
+ if (errors.length > 0) {
643
+ throw new Error(`Failed to parse devcontainer config at ${candidate}: Invalid JSONC`);
644
+ }
645
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
646
+ throw new Error(
647
+ `Failed to parse devcontainer config at ${candidate}: Expected a JSON object`
648
+ );
649
+ }
650
+ return parsed;
651
+ }
652
+ return void 0;
653
+ }
654
+ function validateRepoConfig(config, logger) {
655
+ const rejectedProps = ["build", "dockerFile", "dockerfile", "dockerComposeFile"];
656
+ for (const prop of rejectedProps) {
657
+ if (prop in config && config[prop] !== void 0) {
658
+ throw new Error(
659
+ `agent-env requires the managed image. Remove '${prop}' from .devcontainer/devcontainer.json to use agent-env.`
660
+ );
661
+ }
662
+ }
663
+ if ("image" in config && config.image !== void 0) {
664
+ const repoImage = String(config.image);
665
+ logger?.warn(
666
+ `Repo config specifies image '${repoImage}' which will be overridden by agent-env managed image.`
667
+ );
668
+ }
669
+ }
670
+ function composeName(instanceName, repoName) {
671
+ if (typeof repoName === "string" && repoName.trim()) {
672
+ return `${repoName} - ${instanceName}`;
673
+ }
674
+ return instanceName;
675
+ }
676
+ function composeLifecycle(managedCmd, repoCmd) {
677
+ if (repoCmd === void 0 || repoCmd === null) {
678
+ return managedCmd;
679
+ }
680
+ if (typeof repoCmd === "string") {
681
+ return { "agent-env": managedCmd, repo: repoCmd };
682
+ }
683
+ if (Array.isArray(repoCmd)) {
684
+ return { "agent-env": managedCmd, repo: repoCmd };
685
+ }
686
+ if (typeof repoCmd === "object") {
687
+ return { "agent-env": managedCmd, ...repoCmd };
688
+ }
689
+ return managedCmd;
589
690
  }
691
+ function composeAllLifecycle(managedLifecycleCmds, repoLifecycleCmds) {
692
+ const result = {};
693
+ for (const cmdName of COMPOSABLE_LIFECYCLE_CMDS) {
694
+ const managedCmd = managedLifecycleCmds[cmdName];
695
+ const repoCmd = repoLifecycleCmds[cmdName];
696
+ if (managedCmd && repoCmd !== void 0 && repoCmd !== null) {
697
+ result[cmdName] = composeLifecycle(managedCmd, repoCmd);
698
+ } else if (managedCmd && (repoCmd === void 0 || repoCmd === null)) {
699
+ } else if (!managedCmd && repoCmd !== void 0 && repoCmd !== null) {
700
+ if (typeof repoCmd === "string") {
701
+ result[cmdName] = { repo: repoCmd };
702
+ } else if (Array.isArray(repoCmd)) {
703
+ result[cmdName] = { repo: repoCmd };
704
+ } else if (typeof repoCmd === "object") {
705
+ result[cmdName] = repoCmd;
706
+ }
707
+ }
708
+ }
709
+ return result;
710
+ }
711
+ function mergeRunArgs(managedArgs, repoArgs) {
712
+ if (!Array.isArray(repoArgs)) {
713
+ return [...managedArgs];
714
+ }
715
+ const filtered = [];
716
+ let i = 0;
717
+ while (i < repoArgs.length) {
718
+ const arg = String(repoArgs[i]);
719
+ if (arg.startsWith("--name=")) {
720
+ i++;
721
+ continue;
722
+ }
723
+ if (arg === "--name") {
724
+ i += i + 1 < repoArgs.length ? 2 : 1;
725
+ continue;
726
+ }
727
+ filtered.push(arg);
728
+ i++;
729
+ }
730
+ return [...managedArgs, ...filtered];
731
+ }
732
+ function extractMountTarget(mount) {
733
+ if (typeof mount === "string") {
734
+ const parts = mount.split(",");
735
+ for (const part of parts) {
736
+ const trimmed = part.trim();
737
+ if (trimmed.startsWith("target=") || trimmed.startsWith("destination=")) {
738
+ return trimmed.split("=").slice(1).join("=");
739
+ }
740
+ }
741
+ return void 0;
742
+ }
743
+ if (typeof mount === "object" && mount !== null) {
744
+ const obj = mount;
745
+ if (typeof obj.target === "string") return obj.target;
746
+ if (typeof obj.destination === "string") return obj.destination;
747
+ }
748
+ return void 0;
749
+ }
750
+ function mergeMounts(managedMounts, repoMounts) {
751
+ if (!Array.isArray(repoMounts)) {
752
+ return [...managedMounts];
753
+ }
754
+ const managedTargets = /* @__PURE__ */ new Set();
755
+ for (const mount of managedMounts) {
756
+ const target = extractMountTarget(mount);
757
+ if (target) managedTargets.add(target);
758
+ }
759
+ const filteredRepo = [];
760
+ for (const mount of repoMounts) {
761
+ const target = extractMountTarget(mount);
762
+ if (target && managedTargets.has(target)) {
763
+ continue;
764
+ }
765
+ if (typeof mount === "string") {
766
+ filteredRepo.push(mount);
767
+ } else if (typeof mount === "object" && mount !== null) {
768
+ const obj = mount;
769
+ const parts = [];
770
+ if (obj.source) parts.push(`source=${obj.source}`);
771
+ if (obj.target) parts.push(`target=${obj.target}`);
772
+ else if (obj.destination) parts.push(`target=${obj.destination}`);
773
+ if (obj.type) parts.push(`type=${obj.type}`);
774
+ filteredRepo.push(parts.join(","));
775
+ }
776
+ }
777
+ return [...managedMounts, ...filteredRepo];
778
+ }
779
+ function deepMergeCustomizations(managed, repo) {
780
+ if (!repo || typeof repo !== "object") {
781
+ return {
782
+ vscode: {
783
+ settings: { ...managed.vscode.settings },
784
+ extensions: [...managed.vscode.extensions]
785
+ }
786
+ };
787
+ }
788
+ const repoCustom = repo;
789
+ const repoVscode = typeof repoCustom.vscode === "object" && repoCustom.vscode !== null ? repoCustom.vscode : {};
790
+ const repoExtensions = Array.isArray(repoVscode.extensions) ? repoVscode.extensions : [];
791
+ const allExtensions = [...managed.vscode.extensions, ...repoExtensions];
792
+ const seen = /* @__PURE__ */ new Set();
793
+ const dedupedExtensions = [];
794
+ for (const ext of allExtensions) {
795
+ const lower = ext.toLowerCase();
796
+ if (!seen.has(lower)) {
797
+ seen.add(lower);
798
+ dedupedExtensions.push(ext);
799
+ }
800
+ }
801
+ const repoSettings = typeof repoVscode.settings === "object" && repoVscode.settings !== null ? repoVscode.settings : {};
802
+ const repoFilewatcherCommands = Array.isArray(repoSettings["filewatcher.commands"]) ? repoSettings["filewatcher.commands"] : [];
803
+ const managedFilewatcherCommands = Array.isArray(managed.vscode.settings["filewatcher.commands"]) ? managed.vscode.settings["filewatcher.commands"] : [];
804
+ const mergedFilewatcherCommands = [...repoFilewatcherCommands];
805
+ for (const managedCmd of managedFilewatcherCommands) {
806
+ if (typeof managedCmd !== "object" || managedCmd === null) continue;
807
+ const mCmd = managedCmd;
808
+ const alreadyExists = mergedFilewatcherCommands.some((existing) => {
809
+ if (typeof existing !== "object" || existing === null) return false;
810
+ return existing.match === mCmd.match;
811
+ });
812
+ if (!alreadyExists) {
813
+ mergedFilewatcherCommands.push(managedCmd);
814
+ }
815
+ }
816
+ const mergedSettings = {
817
+ ...repoSettings,
818
+ ...managed.vscode.settings
819
+ };
820
+ if (mergedFilewatcherCommands.length > 0) {
821
+ mergedSettings["filewatcher.commands"] = mergedFilewatcherCommands;
822
+ }
823
+ const result = {};
824
+ for (const [key, value] of Object.entries(repoCustom)) {
825
+ if (key !== "vscode") {
826
+ result[key] = value;
827
+ }
828
+ }
829
+ result.vscode = {
830
+ ...repoVscode,
831
+ settings: mergedSettings,
832
+ extensions: dedupedExtensions
833
+ };
834
+ return result;
835
+ }
836
+ function buildManagedOnly(managed) {
837
+ return {
838
+ image: managed.image,
839
+ name: managed.instanceName,
840
+ initializeCommand: managed.initializeCmd,
841
+ runArgs: [...managed.runArgs],
842
+ containerEnv: { ...managed.containerEnv },
843
+ mounts: [...managed.mounts],
844
+ customizations: deepMergeCustomizations(managed.customizations)
845
+ };
846
+ }
847
+ function mergeDevcontainerConfigs(managed, repoConfig) {
848
+ if (!repoConfig) return buildManagedOnly(managed);
849
+ const {
850
+ name,
851
+ image: _image,
852
+ initializeCommand,
853
+ postCreateCommand,
854
+ postStartCommand,
855
+ postAttachCommand,
856
+ onCreateCommand,
857
+ updateContentCommand,
858
+ runArgs,
859
+ containerEnv,
860
+ customizations,
861
+ mounts,
862
+ ...repoRest
863
+ } = repoConfig;
864
+ return {
865
+ ...repoRest,
866
+ image: managed.image,
867
+ name: composeName(managed.instanceName, name),
868
+ initializeCommand: composeLifecycle(managed.initializeCmd, initializeCommand),
869
+ ...composeAllLifecycle(managed.lifecycleCmds, {
870
+ postCreateCommand,
871
+ postStartCommand,
872
+ postAttachCommand,
873
+ onCreateCommand,
874
+ updateContentCommand
875
+ }),
876
+ runArgs: mergeRunArgs(managed.runArgs, runArgs),
877
+ containerEnv: {
878
+ ...typeof containerEnv === "object" && containerEnv !== null ? Object.fromEntries(
879
+ Object.entries(containerEnv).map(([k, v]) => [k, String(v)])
880
+ ) : {},
881
+ ...managed.containerEnv
882
+ },
883
+ mounts: mergeMounts(managed.mounts, mounts),
884
+ customizations: deepMergeCustomizations(managed.customizations, customizations)
885
+ };
886
+ }
887
+ async function loadManagedDefaults(deps = defaultMergeDeps) {
888
+ const baselinePath = getBaselineConfigPath();
889
+ const configPath = join2(baselinePath, "devcontainer.json");
890
+ let content;
891
+ try {
892
+ content = await deps.readFile(configPath, "utf-8");
893
+ } catch {
894
+ throw new Error(
895
+ `Failed to load managed defaults from baseline config: ${configPath}. Ensure agent-env package is intact.`
896
+ );
897
+ }
898
+ const errors = [];
899
+ const config = parseJsonc2(content, errors, { allowTrailingComma: true });
900
+ if (errors.length > 0) {
901
+ throw new Error(
902
+ `Failed to load managed defaults from baseline config: ${configPath}. Ensure agent-env package is intact.`
903
+ );
904
+ }
905
+ if (typeof config.image !== "string") {
906
+ throw new Error(
907
+ `Failed to load managed defaults from baseline config: ${configPath}. Missing 'image' field.`
908
+ );
909
+ }
910
+ if (typeof config.initializeCommand !== "string") {
911
+ throw new Error(
912
+ `Failed to load managed defaults from baseline config: ${configPath}. Missing 'initializeCommand' field.`
913
+ );
914
+ }
915
+ const baseContainerEnv = {};
916
+ if (typeof config.containerEnv === "object" && config.containerEnv !== null) {
917
+ const env = config.containerEnv;
918
+ if (typeof env.AGENT_ENV_CONTAINER === "string") {
919
+ baseContainerEnv.AGENT_ENV_CONTAINER = env.AGENT_ENV_CONTAINER;
920
+ }
921
+ }
922
+ return {
923
+ image: config.image,
924
+ initializeCmd: config.initializeCommand,
925
+ baseContainerEnv
926
+ };
927
+ }
928
+ function getPackageVersion() {
929
+ try {
930
+ const req = createRequire(import.meta.url);
931
+ const pkg = req("../../package.json");
932
+ return pkg.version;
933
+ } catch {
934
+ return "unknown";
935
+ }
936
+ }
937
+ async function writeGeneratedConfig(outputPath, config, deps = defaultMergeDeps) {
938
+ const version2 = getPackageVersion();
939
+ const header = `${AUTO_GENERATED_HEADER} v${version2}. Do not edit.
940
+ `;
941
+ const json = JSON.stringify(config, null, 2);
942
+ const content = `${header}${json}
943
+ `;
944
+ const tmpPath = `${outputPath}.tmp`;
945
+ await deps.writeFile(tmpPath, content, "utf-8");
946
+ await deps.rename(tmpPath, outputPath);
947
+ }
948
+ function buildManagedConfig(defaults, params) {
949
+ const statusBarWatcher = {
950
+ match: `${STATUS_BAR_JSON_FILENAME}$`,
951
+ event: "onFolderChange",
952
+ vscodeTask: "betterStatusBar.refreshButtons"
953
+ };
954
+ return {
955
+ image: defaults.image,
956
+ instanceName: params.instanceName,
957
+ containerName: params.containerName,
958
+ initializeCmd: defaults.initializeCmd,
959
+ lifecycleCmds: { ...LABEL_LIFECYCLE_CMDS },
960
+ runArgs: [`--name=${params.containerName}`],
961
+ containerEnv: {
962
+ ...defaults.baseContainerEnv,
963
+ AGENT_ENV_INSTANCE: params.instanceName,
964
+ AGENT_ENV_REPO: params.repoSlug,
965
+ AGENT_ENV_PURPOSE: params.purpose
966
+ },
967
+ mounts: [],
968
+ customizations: {
969
+ vscode: {
970
+ settings: {
971
+ "betterStatusBar.configurationFile": `${CONTAINER_AGENT_ENV_DIR}/${STATUS_BAR_JSON_FILENAME}`,
972
+ "filewatcher.commands": [statusBarWatcher]
973
+ },
974
+ extensions: []
975
+ }
976
+ }
977
+ };
978
+ }
979
+
980
+ // src/lib/purpose-instance.ts
981
+ import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile6, rename as rename3, stat as stat3, writeFile as writeFile5 } from "fs/promises";
982
+ import { homedir as homedir2 } from "os";
590
983
 
591
984
  // src/lib/state.ts
592
- import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
593
- import { join as join2 } from "path";
594
- var defaultStateFsDeps = { readFile: readFile2, writeFile: writeFile2, rename, mkdir: mkdir2, appendFile };
985
+ import { appendFile, mkdir as mkdir2, readFile as readFile3, rename as rename2, writeFile as writeFile3 } from "fs/promises";
986
+ import { join as join3 } from "path";
987
+ var defaultStateFsDeps = { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir2, appendFile };
595
988
  async function readState(wsPath, deps = defaultStateFsDeps) {
596
989
  try {
597
990
  const content = await deps.readFile(wsPath.stateFile, "utf-8");
598
991
  const parsed = JSON.parse(content);
599
- if (!isValidState(parsed)) {
600
- return createFallbackState(wsPath.name);
601
- }
602
- return parsed;
992
+ const state = isValidState(parsed) ? parsed : migrateOldState(parsed, wsPath.name) ?? createFallbackState(wsPath.name);
993
+ return migrateConfigSource(state);
603
994
  } catch (err) {
604
995
  if (err instanceof SyntaxError || err.code === "ENOENT") {
605
996
  return createFallbackState(wsPath.name);
@@ -608,42 +999,87 @@ async function readState(wsPath, deps = defaultStateFsDeps) {
608
999
  }
609
1000
  }
610
1001
  async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
611
- const tmpPath = join2(wsPath.agentEnvDir, STATE_FILE_TMP);
1002
+ const tmpPath = join3(wsPath.agentEnvDir, STATE_FILE_TMP);
612
1003
  await deps.mkdir(wsPath.agentEnvDir, { recursive: true });
613
1004
  const content = JSON.stringify(state, null, 2) + "\n";
614
1005
  await deps.writeFile(tmpPath, content, "utf-8");
615
1006
  await deps.rename(tmpPath, wsPath.stateFile);
616
1007
  }
617
- function createInitialState(name, repo, options) {
618
- const { containerName, configSource, purpose } = options ?? {};
1008
+ function createInitialState(instance, repoSlug, repoUrl, options) {
1009
+ const { containerName, repoConfigDetected, purpose } = options ?? {
1010
+ repoConfigDetected: false
1011
+ };
619
1012
  const now = (/* @__PURE__ */ new Date()).toISOString();
1013
+ const workspaceName = `${repoSlug}-${instance}`;
620
1014
  return {
621
- name,
622
- repo,
1015
+ instance,
1016
+ repoSlug,
1017
+ repoUrl,
623
1018
  createdAt: now,
624
1019
  lastAttached: now,
625
1020
  purpose: purpose ?? null,
626
- containerName: containerName ?? `${CONTAINER_PREFIX}${name}`,
627
- configSource: configSource ?? "baseline"
1021
+ containerName: containerName ?? `${CONTAINER_PREFIX}${workspaceName}`,
1022
+ repoConfigDetected
1023
+ };
1024
+ }
1025
+ function extractRepoName(url) {
1026
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
1027
+ const lastSep = Math.max(cleaned.lastIndexOf("/"), cleaned.lastIndexOf(":"));
1028
+ const name = lastSep >= 0 ? cleaned.slice(lastSep + 1) : cleaned;
1029
+ return name.toLowerCase() || "unknown";
1030
+ }
1031
+ function migrateOldState(parsed, workspaceName) {
1032
+ if (typeof parsed !== "object" || parsed === null) return null;
1033
+ const obj = parsed;
1034
+ if (typeof obj.name !== "string" || typeof obj.repo !== "string") return null;
1035
+ const repoSlug = extractRepoName(obj.repo);
1036
+ const lowerName = obj.name.toLowerCase();
1037
+ const prefix = `${repoSlug}-`;
1038
+ const instance = lowerName.startsWith(prefix) && obj.name.length > prefix.length ? obj.name.slice(prefix.length) : obj.name;
1039
+ const configSource = obj.configSource === "baseline" || obj.configSource === "repo" ? obj.configSource : void 0;
1040
+ const state = {
1041
+ instance,
1042
+ repoSlug,
1043
+ repoUrl: obj.repo,
1044
+ createdAt: typeof obj.createdAt === "string" ? obj.createdAt : "unknown",
1045
+ lastAttached: typeof obj.lastAttached === "string" ? obj.lastAttached : "unknown",
1046
+ purpose: typeof obj.purpose === "string" ? obj.purpose : null,
1047
+ containerName: typeof obj.containerName === "string" ? obj.containerName : `${CONTAINER_PREFIX}${workspaceName}`
628
1048
  };
1049
+ if (configSource) {
1050
+ state.configSource = configSource;
1051
+ }
1052
+ return state;
629
1053
  }
630
1054
  function isValidState(value) {
631
1055
  if (typeof value !== "object" || value === null) return false;
632
1056
  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";
1057
+ 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
1058
  }
635
- var GIT_EXCLUDE_PATTERN = `${AGENT_ENV_DIR}/`;
1059
+ function migrateConfigSource(state) {
1060
+ const { configSource, repoConfigDetected, ...rest } = state;
1061
+ const normalizedRepoConfigDetected = repoConfigDetected !== void 0 ? repoConfigDetected : configSource === "repo";
1062
+ return {
1063
+ ...rest,
1064
+ repoConfigDetected: normalizedRepoConfigDetected
1065
+ };
1066
+ }
1067
+ var GIT_EXCLUDE_PATTERNS = [`${AGENT_ENV_DIR}/`];
636
1068
  async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
637
- const excludePath = join2(workspaceRoot, ".git", "info", "exclude");
1069
+ const excludePath = join3(workspaceRoot, ".git", "info", "exclude");
638
1070
  try {
639
1071
  const content = await deps.readFile(excludePath, "utf-8");
640
1072
  const lines = content.split("\n");
641
- if (lines.some((line) => line.trim() === GIT_EXCLUDE_PATTERN)) {
1073
+ const missing = GIT_EXCLUDE_PATTERNS.filter(
1074
+ (pattern) => !lines.some((line) => line.trim() === pattern)
1075
+ );
1076
+ if (missing.length === 0) {
642
1077
  return;
643
1078
  }
644
1079
  const prefix = content.endsWith("\n") ? "" : "\n";
645
- await deps.appendFile(excludePath, `${prefix}${GIT_EXCLUDE_PATTERN}
646
- `, "utf-8");
1080
+ const toAppend = missing.map((p) => `${p}
1081
+ `).join("");
1082
+ await deps.appendFile(excludePath, `${prefix}${toAppend}`, "utf-8");
647
1083
  } catch (err) {
648
1084
  if (err.code === "ENOENT") {
649
1085
  return;
@@ -652,10 +1088,55 @@ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
652
1088
  }
653
1089
  }
654
1090
 
1091
+ // src/lib/status-bar.ts
1092
+ import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
1093
+ import { join as join4 } from "path";
1094
+ var STATUS_BAR_TEMPLATE_JSON = "statusBar.template.json";
1095
+ var STATUS_BAR_JSON = "statusBar.json";
1096
+ var TEMPLATE_NOT_FOUND = "TEMPLATE_NOT_FOUND";
1097
+ var PURPOSE_PLACEHOLDER = "{{PURPOSE}}";
1098
+ var NO_PURPOSE_TEXT = "(no purpose set)";
1099
+ var defaultDeps = { readFile: readFile4, writeFile: writeFile4 };
1100
+ async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = defaultDeps) {
1101
+ const vscodeTemplatePath = join4(workspaceRoot, ".vscode", STATUS_BAR_TEMPLATE_JSON);
1102
+ let templateContent = null;
1103
+ try {
1104
+ templateContent = await deps.readFile(vscodeTemplatePath, "utf-8");
1105
+ } catch (err) {
1106
+ if (err.code !== "ENOENT") {
1107
+ throw err;
1108
+ }
1109
+ }
1110
+ const agentEnvTemplatePath = join4(agentEnvDir, STATUS_BAR_TEMPLATE_JSON);
1111
+ if (templateContent === null) {
1112
+ try {
1113
+ templateContent = await deps.readFile(agentEnvTemplatePath, "utf-8");
1114
+ } catch (err) {
1115
+ if (err.code !== "ENOENT") {
1116
+ throw err;
1117
+ }
1118
+ }
1119
+ }
1120
+ if (templateContent === null) {
1121
+ throw Object.assign(
1122
+ new Error(
1123
+ `No status bar template found. Checked ${vscodeTemplatePath} and ${agentEnvTemplatePath}. Create a template manually or use \`agent-env init-template\` when available.`
1124
+ ),
1125
+ { code: TEMPLATE_NOT_FOUND }
1126
+ );
1127
+ }
1128
+ const rawText = purpose ?? NO_PURPOSE_TEXT;
1129
+ const replacementText = JSON.stringify(rawText).slice(1, -1);
1130
+ const output = templateContent.replaceAll(PURPOSE_PLACEHOLDER, replacementText);
1131
+ const outputPath = join4(agentEnvDir, STATUS_BAR_JSON);
1132
+ await deps.writeFile(outputPath, output, "utf-8");
1133
+ }
1134
+
655
1135
  // src/lib/workspace.ts
656
- import { mkdir as mkdir3, readdir as readdir2, rm, stat as stat2 } from "fs/promises";
1136
+ import { createHash } from "crypto";
1137
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile5, rm, stat as stat2 } from "fs/promises";
657
1138
  import { homedir } from "os";
658
- import { join as join3 } from "path";
1139
+ import { join as join5 } from "path";
659
1140
  var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
660
1141
  var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
661
1142
  function validateNameSegment(value, label) {
@@ -668,8 +1149,38 @@ function validateNameSegment(value, label) {
668
1149
  );
669
1150
  }
670
1151
  }
1152
+ function deriveRepoSlug(url) {
1153
+ const cleaned = url.replace(/\/+$/, "").replace(/\.git$/, "");
1154
+ const lastSlash = cleaned.lastIndexOf("/");
1155
+ const lastColon = cleaned.lastIndexOf(":");
1156
+ const lastSeparator = Math.max(lastSlash, lastColon);
1157
+ if (lastSeparator === -1) {
1158
+ if (!cleaned) {
1159
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
1160
+ }
1161
+ return compressSlug(cleaned.toLowerCase());
1162
+ }
1163
+ const repoName = cleaned.slice(lastSeparator + 1);
1164
+ if (!repoName) {
1165
+ throw new Error(`Cannot derive repo slug from URL: ${url}`);
1166
+ }
1167
+ return compressSlug(repoName.toLowerCase());
1168
+ }
1169
+ function compressSlug(slug, maxLength = MAX_REPO_SLUG_LENGTH) {
1170
+ if (slug.length <= maxLength) {
1171
+ return slug;
1172
+ }
1173
+ const hash = createHash("sha256").update(slug).digest("hex").slice(0, 6);
1174
+ const overhead = 8;
1175
+ const available = Math.max(0, maxLength - overhead);
1176
+ const prefixLen = Math.ceil(available / 2);
1177
+ const suffixLen = available - prefixLen;
1178
+ const prefix = slug.slice(0, prefixLen);
1179
+ const suffix = slug.slice(slug.length - suffixLen);
1180
+ return `${prefix}_${hash}_${suffix}`;
1181
+ }
671
1182
  function getWorkspacesBaseDir(deps = defaultFsDeps2) {
672
- return join3(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
1183
+ return join5(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
673
1184
  }
674
1185
  function deriveWorkspaceName(repo, instance) {
675
1186
  validateNameSegment(repo, "repo");
@@ -681,15 +1192,15 @@ function deriveContainerName(workspaceName) {
681
1192
  }
682
1193
  function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
683
1194
  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);
1195
+ const root = join5(getWorkspacesBaseDir(deps), name);
1196
+ const agentEnvDir = join5(root, AGENT_ENV_DIR);
1197
+ const stateFile = join5(agentEnvDir, STATE_FILE);
687
1198
  return { root, name, agentEnvDir, stateFile };
688
1199
  }
689
1200
  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);
1201
+ const root = join5(getWorkspacesBaseDir(deps), workspaceName);
1202
+ const agentEnvDir = join5(root, AGENT_ENV_DIR);
1203
+ const stateFile = join5(agentEnvDir, STATE_FILE);
693
1204
  return { root, name: workspaceName, agentEnvDir, stateFile };
694
1205
  }
695
1206
  async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
@@ -716,6 +1227,108 @@ async function scanWorkspaces(deps = defaultFsDeps2) {
716
1227
  throw err;
717
1228
  }
718
1229
  }
1230
+ function looksLikeUrl(value) {
1231
+ return value.includes("/") || value.includes(":");
1232
+ }
1233
+ async function resolveRepo(opts, executor) {
1234
+ const repoFlag = opts.repo?.trim();
1235
+ if (repoFlag !== void 0 && repoFlag !== "") {
1236
+ if (looksLikeUrl(repoFlag)) {
1237
+ try {
1238
+ const slug2 = deriveRepoSlug(repoFlag);
1239
+ return { resolved: true, repoSlug: slug2 };
1240
+ } catch {
1241
+ return {
1242
+ resolved: false,
1243
+ error: {
1244
+ code: "INVALID_REPO",
1245
+ message: `Cannot derive repo slug from: ${repoFlag}`,
1246
+ suggestion: "Provide a valid git URL or repo slug."
1247
+ }
1248
+ };
1249
+ }
1250
+ }
1251
+ const slug = repoFlag.toLowerCase();
1252
+ if (!VALID_NAME_PATTERN.test(slug)) {
1253
+ return {
1254
+ resolved: false,
1255
+ error: {
1256
+ code: "INVALID_REPO",
1257
+ message: `Invalid repo slug: "${repoFlag}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`,
1258
+ suggestion: "Provide a valid repo slug or git URL."
1259
+ }
1260
+ };
1261
+ }
1262
+ return { resolved: true, repoSlug: slug };
1263
+ }
1264
+ if (opts.cwd) {
1265
+ const result = await executor("git", ["remote", "get-url", "origin"], {
1266
+ cwd: opts.cwd
1267
+ });
1268
+ if (result.ok && result.stdout.trim()) {
1269
+ try {
1270
+ const slug = deriveRepoSlug(result.stdout.trim());
1271
+ return { resolved: true, repoSlug: slug };
1272
+ } catch {
1273
+ }
1274
+ }
1275
+ }
1276
+ return { resolved: false };
1277
+ }
1278
+ var defaultResolveInstanceDeps = {
1279
+ fsDeps: defaultFsDeps2,
1280
+ readFile: readFile5
1281
+ };
1282
+ async function resolveInstance(instanceName, repoSlug, deps = defaultResolveInstanceDeps) {
1283
+ const workspaces = await scanWorkspaces(deps.fsDeps);
1284
+ if (workspaces.includes(instanceName)) {
1285
+ return { found: true, workspaceName: instanceName };
1286
+ }
1287
+ if (repoSlug) {
1288
+ const expectedName = `${repoSlug}-${instanceName}`;
1289
+ if (workspaces.includes(expectedName)) {
1290
+ return { found: true, workspaceName: expectedName };
1291
+ }
1292
+ }
1293
+ const matches = [];
1294
+ for (const wsName of workspaces) {
1295
+ const wsPath = getWorkspacePathByName(wsName, deps.fsDeps);
1296
+ try {
1297
+ const content = await deps.readFile(wsPath.stateFile, "utf-8");
1298
+ const state = JSON.parse(content);
1299
+ if (typeof state === "object" && state !== null && state.instance === instanceName) {
1300
+ matches.push(wsName);
1301
+ if (matches.length > 1) break;
1302
+ }
1303
+ } catch {
1304
+ }
1305
+ }
1306
+ if (matches.length === 1) {
1307
+ return { found: true, workspaceName: matches[0] };
1308
+ }
1309
+ if (matches.length > 1) {
1310
+ const repoSlugs = matches.map((ws) => {
1311
+ const idx = ws.lastIndexOf(`-${instanceName}`);
1312
+ return idx > 0 ? ws.slice(0, idx) : ws;
1313
+ });
1314
+ return {
1315
+ found: false,
1316
+ error: {
1317
+ code: "AMBIGUOUS_INSTANCE",
1318
+ message: `Multiple instances named '${instanceName}' exist across repos: ${repoSlugs.join(", ")}`,
1319
+ suggestion: "Use --repo <slug> to specify which repo."
1320
+ }
1321
+ };
1322
+ }
1323
+ return {
1324
+ found: false,
1325
+ error: {
1326
+ code: "WORKSPACE_NOT_FOUND",
1327
+ message: `Instance '${instanceName}' not found`,
1328
+ suggestion: "Use `agent-env list` to see available instances."
1329
+ }
1330
+ };
1331
+ }
719
1332
  var defaultDeleteFsDeps = { rm };
720
1333
  async function deleteWorkspace(wsPath, deps = defaultDeleteFsDeps) {
721
1334
  await deps.rm(wsPath.root, { recursive: true, force: true });
@@ -726,9 +1339,21 @@ var MAX_PURPOSE_LENGTH = 200;
726
1339
  function createPurposeDefaultDeps() {
727
1340
  return {
728
1341
  workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
729
- stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 }
1342
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir4, appendFile: appendFile2 },
1343
+ statusBarDeps: { readFile: readFile6, writeFile: writeFile5 }
730
1344
  };
731
1345
  }
1346
+ async function regenerateStatusBarSafe(workspaceRoot, agentEnvDir, purpose, statusBarDeps) {
1347
+ try {
1348
+ await regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, statusBarDeps);
1349
+ } catch (err) {
1350
+ if (err.code === TEMPLATE_NOT_FOUND) {
1351
+ return `Status bar template not found \u2014 VS Code status bar won't update. Create one at .vscode/statusBar.template.json or ${agentEnvDir}/statusBar.template.json.`;
1352
+ }
1353
+ throw err;
1354
+ }
1355
+ return void 0;
1356
+ }
732
1357
  function validatePurposeLength(value) {
733
1358
  if (value.length > MAX_PURPOSE_LENGTH) {
734
1359
  return {
@@ -741,58 +1366,53 @@ function validatePurposeLength(value) {
741
1366
  }
742
1367
  return null;
743
1368
  }
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);
1369
+ async function getPurpose(instanceName, deps, repoSlug) {
1370
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1371
+ fsDeps: deps.workspaceFsDeps,
1372
+ readFile: deps.stateFsDeps.readFile
1373
+ });
766
1374
  if (!lookup.found) {
767
- return mapLookupError(lookup, instanceName);
1375
+ return { ok: false, error: lookup.error };
768
1376
  }
769
1377
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
770
1378
  const state = await readState(wsPath, deps.stateFsDeps);
771
1379
  return { ok: true, purpose: state.purpose };
772
1380
  }
773
- async function setPurpose(instanceName, value, deps) {
1381
+ async function setPurpose(instanceName, value, deps, repoSlug) {
774
1382
  const lengthError = validatePurposeLength(value);
775
1383
  if (lengthError) return lengthError;
776
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
1384
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1385
+ fsDeps: deps.workspaceFsDeps,
1386
+ readFile: deps.stateFsDeps.readFile
1387
+ });
777
1388
  if (!lookup.found) {
778
- return mapLookupError(lookup, instanceName);
1389
+ return { ok: false, error: lookup.error };
779
1390
  }
780
1391
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
781
1392
  const state = await readState(wsPath, deps.stateFsDeps);
782
1393
  const cleared = value === "";
1394
+ const newPurpose = cleared ? null : value;
783
1395
  const updatedState = {
784
1396
  ...state,
785
- purpose: cleared ? null : value
1397
+ purpose: newPurpose
786
1398
  };
787
1399
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
788
- return { ok: true, cleared };
1400
+ const warning = await regenerateStatusBarSafe(
1401
+ wsPath.root,
1402
+ wsPath.agentEnvDir,
1403
+ newPurpose,
1404
+ deps.statusBarDeps
1405
+ );
1406
+ return { ok: true, cleared, warning };
789
1407
  }
790
1408
  function createContainerPurposeDefaultDeps() {
791
1409
  return {
792
- stateFsDeps: { readFile: readFile3, writeFile: writeFile3, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1410
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir4, appendFile: appendFile2 },
793
1411
  containerEnvDeps: { getEnv: (key) => process.env[key] },
1412
+ statusBarDeps: { readFile: readFile6, writeFile: writeFile5 },
794
1413
  statePath: CONTAINER_STATE_PATH,
795
- agentEnvDir: CONTAINER_AGENT_ENV_DIR
1414
+ agentEnvDir: CONTAINER_AGENT_ENV_DIR,
1415
+ workspaceRoot: process.cwd()
796
1416
  };
797
1417
  }
798
1418
  async function readContainerState(deps) {
@@ -808,7 +1428,7 @@ async function readContainerState(deps) {
808
1428
  }
809
1429
  };
810
1430
  }
811
- return { ok: true, state: parsed };
1431
+ return { ok: true, state: migrateConfigSource(parsed) };
812
1432
  } catch (err) {
813
1433
  if (err.code === "ENOENT") {
814
1434
  return {
@@ -843,39 +1463,69 @@ async function setContainerPurpose(value, deps) {
843
1463
  const read = await readContainerState(deps);
844
1464
  if (!read.ok) return read;
845
1465
  const cleared = value === "";
1466
+ const newPurpose = cleared ? null : value;
846
1467
  const updatedState = {
847
1468
  ...read.state,
848
- purpose: cleared ? null : value
1469
+ purpose: newPurpose
849
1470
  };
850
1471
  const wsPath = {
851
1472
  root: deps.agentEnvDir,
852
- name: read.state.name,
1473
+ name: `${read.state.repoSlug}-${read.state.instance}`,
853
1474
  agentEnvDir: deps.agentEnvDir,
854
1475
  stateFile: deps.statePath
855
1476
  };
856
1477
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
857
- return { ok: true, cleared };
1478
+ const warning = await regenerateStatusBarSafe(
1479
+ deps.workspaceRoot,
1480
+ deps.agentEnvDir,
1481
+ newPurpose,
1482
+ deps.statusBarDeps
1483
+ );
1484
+ return { ok: true, cleared, warning };
858
1485
  }
859
1486
 
860
1487
  // 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;
1488
+ var VALID_INSTANCE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
1489
+ function validateCreateInputs(instanceName, purposeText) {
1490
+ if (!instanceName) {
1491
+ return {
1492
+ ok: false,
1493
+ error: {
1494
+ code: "INVALID_INSTANCE_NAME",
1495
+ message: "Instance name must not be empty."
1496
+ }
1497
+ };
872
1498
  }
873
- const repoName = cleaned.slice(lastSeparator + 1);
874
- if (!repoName) {
875
- throw new Error(`Cannot extract repository name from URL: ${url}`);
1499
+ if (!VALID_INSTANCE_NAME_PATTERN.test(instanceName)) {
1500
+ return {
1501
+ ok: false,
1502
+ error: {
1503
+ code: "INVALID_INSTANCE_NAME",
1504
+ message: `Invalid instance name: "${instanceName}". Only alphanumeric, dash, dot, and underscore allowed (must start with alphanumeric).`
1505
+ }
1506
+ };
1507
+ }
1508
+ if (instanceName.length > MAX_INSTANCE_NAME_LENGTH) {
1509
+ return {
1510
+ ok: false,
1511
+ error: {
1512
+ code: "INSTANCE_NAME_TOO_LONG",
1513
+ message: `Instance name must be ${MAX_INSTANCE_NAME_LENGTH} characters or fewer (got ${instanceName.length})`
1514
+ }
1515
+ };
876
1516
  }
877
- return repoName;
1517
+ if (purposeText.length > MAX_PURPOSE_LENGTH) {
1518
+ return {
1519
+ ok: false,
1520
+ error: {
1521
+ code: "PURPOSE_TOO_LONG",
1522
+ message: `Purpose must be ${MAX_PURPOSE_LENGTH} characters or fewer (got ${purposeText.length})`
1523
+ }
1524
+ };
1525
+ }
1526
+ return null;
878
1527
  }
1528
+ var GIT_CLONE_TIMEOUT = 12e4;
879
1529
  async function resolveRepoUrl(repoArg, executor) {
880
1530
  if (repoArg !== ".") {
881
1531
  return { ok: true, url: repoArg };
@@ -927,8 +1577,9 @@ function createDefaultDeps() {
927
1577
  executor,
928
1578
  container: createContainerLifecycle(executor),
929
1579
  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 },
1580
+ stateFsDeps: { readFile: readFile7, writeFile: writeFile6, rename: rename4, mkdir: mkdir5, appendFile: appendFile3 },
1581
+ devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile7, stat: stat4, writeFile: writeFile6 },
1582
+ mergeDeps: { readFile: readFile7, writeFile: writeFile6, rename: rename4, access: access3 },
932
1583
  rm: rm2,
933
1584
  logger: {
934
1585
  warn: (msg) => console.warn(msg),
@@ -936,135 +1587,128 @@ function createDefaultDeps() {
936
1587
  }
937
1588
  };
938
1589
  }
939
- async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps) {
940
- const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
941
- if (hasConfig) {
942
- return { ok: true, configSource: "repo" };
943
- }
1590
+ async function setupMergedConfig(wsPath, containerName, repoName, purposeText, deps) {
944
1591
  try {
945
- await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
1592
+ const defaults = await loadManagedDefaults(deps.mergeDeps);
1593
+ const managed = buildManagedConfig(defaults, {
1594
+ instanceName: wsPath.name,
1595
+ containerName,
1596
+ repoSlug: repoName,
1597
+ purpose: purposeText
1598
+ });
1599
+ const repoConfig = await readRepoConfig(wsPath.root, deps.mergeDeps, deps.logger);
1600
+ if (repoConfig) {
1601
+ validateRepoConfig(repoConfig, deps.logger);
1602
+ }
1603
+ const merged = mergeDevcontainerConfigs(managed, repoConfig);
1604
+ await copyManagedAssets(wsPath.root, deps.devcontainerFsDeps);
1605
+ const configPath = join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
1606
+ await writeGeneratedConfig(configPath, merged, deps.mergeDeps);
1607
+ return { ok: true, repoConfigDetected: repoConfig !== void 0 };
946
1608
  } catch (err) {
947
1609
  await safeRollback(wsPath.root, deps.rm, deps.logger);
948
1610
  return {
949
1611
  ok: false,
950
1612
  error: {
951
1613
  code: "CONTAINER_ERROR",
952
- message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
1614
+ message: `Failed to set up devcontainer config: ${err instanceof Error ? err.message : String(err)}`
953
1615
  }
954
1616
  };
955
1617
  }
1618
+ }
1619
+ async function cloneAndPrepareWorkspace(repoUrl, wsPath, deps) {
956
1620
  try {
957
- await patchContainerName(wsPath.root, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
958
- await patchContainerEnv(
959
- wsPath.root,
960
- {
961
- AGENT_ENV_INSTANCE: wsPath.name,
962
- AGENT_ENV_REPO: repoName,
963
- AGENT_ENV_PURPOSE: purposeText
964
- },
965
- deps.devcontainerFsDeps,
966
- AGENT_ENV_DIR
967
- );
1621
+ await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
968
1622
  } catch (err) {
969
- await safeRollback(wsPath.root, deps.rm, deps.logger);
970
1623
  return {
971
1624
  ok: false,
972
1625
  error: {
973
- code: "CONTAINER_ERROR",
974
- message: `Failed to patch baseline devcontainer.json: ${err instanceof Error ? err.message : String(err)}`
975
- }
976
- };
977
- }
978
- return { ok: true, configSource: "baseline" };
979
- }
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})`
1626
+ code: "WORKSPACE_ERROR",
1627
+ message: `Failed to create workspace directory: ${err instanceof Error ? err.message : String(err)}`,
1628
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
989
1629
  }
990
1630
  };
991
1631
  }
992
- let repoName;
993
- try {
994
- repoName = extractRepoName(repoUrl);
995
- } catch {
1632
+ const cloneResult = await deps.executor("git", ["clone", repoUrl, wsPath.root], {
1633
+ timeout: GIT_CLONE_TIMEOUT
1634
+ });
1635
+ if (!cloneResult.ok) {
1636
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
996
1637
  return {
997
1638
  ok: false,
998
1639
  error: {
999
1640
  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.`
1641
+ message: `Git clone failed: ${cloneResult.stderr}`,
1642
+ suggestion: "Check the repository URL and your access permissions."
1015
1643
  }
1016
1644
  };
1017
1645
  }
1018
1646
  try {
1019
- await deps.workspaceFsDeps.mkdir(dirname2(wsPath.root), { recursive: true });
1647
+ await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
1020
1648
  } catch (err) {
1649
+ await safeRollback(wsPath.root, deps.rm, deps.logger);
1021
1650
  return {
1022
1651
  ok: false,
1023
1652
  error: {
1024
1653
  code: "WORKSPACE_ERROR",
1025
- message: `Failed to create workspace directory: ${err instanceof Error ? err.message : String(err)}`,
1026
- suggestion: "Check filesystem permissions for the ~/.agent-env directory."
1654
+ message: `Failed to create .agent-env directory: ${err instanceof Error ? err.message : String(err)}`,
1655
+ suggestion: "Check filesystem permissions in the cloned workspace directory."
1027
1656
  }
1028
1657
  };
1029
1658
  }
1030
- const cloneResult = await deps.executor("git", ["clone", repoUrl, wsPath.root], {
1031
- timeout: GIT_CLONE_TIMEOUT
1032
- });
1033
- if (!cloneResult.ok) {
1034
- await safeRollback(wsPath.root, deps.rm, deps.logger);
1659
+ return { ok: true };
1660
+ }
1661
+ async function discoverContainerName(containerName, containerId, deps) {
1662
+ if (containerId) {
1663
+ const discovered = await deps.container.getContainerNameById(containerId);
1664
+ if (discovered) {
1665
+ return discovered;
1666
+ }
1667
+ } else {
1668
+ deps.logger?.warn(
1669
+ `Warning: devcontainer started successfully but no containerId returned. Using derived name '${containerName}'.`
1670
+ );
1671
+ }
1672
+ return containerName;
1673
+ }
1674
+ async function createInstance(instanceName, repoUrl, deps, options) {
1675
+ const purposeText = options?.purpose ?? "";
1676
+ const purposeState = options?.purpose ?? null;
1677
+ const validationError = validateCreateInputs(instanceName, purposeText);
1678
+ if (validationError) return validationError;
1679
+ let repoName;
1680
+ try {
1681
+ repoName = deriveRepoSlug(repoUrl);
1682
+ } catch {
1035
1683
  return {
1036
1684
  ok: false,
1037
1685
  error: {
1038
1686
  code: "GIT_ERROR",
1039
- message: `Git clone failed: ${cloneResult.stderr}`,
1040
- suggestion: "Check the repository URL and your access permissions."
1687
+ message: `Invalid repository URL: ${repoUrl}`,
1688
+ suggestion: "Provide a valid HTTPS or SSH git URL."
1041
1689
  }
1042
1690
  };
1043
1691
  }
1044
- try {
1045
- await deps.workspaceFsDeps.mkdir(wsPath.agentEnvDir, { recursive: true });
1046
- } catch (err) {
1047
- await safeRollback(wsPath.root, deps.rm, deps.logger);
1692
+ const wsPath = getWorkspacePath(repoName, instanceName, deps.workspaceFsDeps);
1693
+ const containerName = deriveContainerName(wsPath.name);
1694
+ const exists = await workspaceExists(repoName, instanceName, deps.workspaceFsDeps);
1695
+ if (exists) {
1048
1696
  return {
1049
1697
  ok: false,
1050
1698
  error: {
1051
- code: "WORKSPACE_ERROR",
1052
- message: `Failed to create .agent-env directory: ${err instanceof Error ? err.message : String(err)}`,
1053
- suggestion: "Check filesystem permissions in the cloned workspace directory."
1699
+ code: "INSTANCE_EXISTS",
1700
+ message: `Instance '${instanceName}' already exists for repo '${repoName}'`,
1701
+ suggestion: `Choose a different instance name or remove the existing one first.`
1054
1702
  }
1055
1703
  };
1056
1704
  }
1057
- const configResult = await setupDevcontainerConfig(
1058
- wsPath,
1059
- containerName,
1060
- repoName,
1061
- purposeText,
1062
- deps
1063
- );
1705
+ const prepResult = await cloneAndPrepareWorkspace(repoUrl, wsPath, deps);
1706
+ if (!prepResult.ok) return prepResult;
1707
+ const configResult = await setupMergedConfig(wsPath, containerName, repoName, purposeText, deps);
1064
1708
  if (!configResult.ok) {
1065
1709
  return configResult;
1066
1710
  }
1067
- const { configSource } = configResult;
1711
+ const { repoConfigDetected } = configResult;
1068
1712
  const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
1069
1713
  if (existingContainer) {
1070
1714
  await safeRollback(wsPath.root, deps.rm, deps.logger);
@@ -1077,31 +1721,25 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1077
1721
  }
1078
1722
  };
1079
1723
  }
1080
- const baselineConfigPath = configSource === "baseline" ? join4(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1724
+ const configPath = join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
1081
1725
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1082
1726
  remoteEnv: {
1083
1727
  AGENT_INSTANCE: wsPath.name,
1084
1728
  AGENT_ENV_PURPOSE: purposeText
1085
1729
  },
1086
- configPath: baselineConfigPath
1730
+ configPath
1087
1731
  });
1088
1732
  if (!containerResult.ok) {
1089
1733
  return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
1090
1734
  }
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, {
1735
+ const actualContainerName = await discoverContainerName(
1736
+ containerName,
1737
+ containerResult.containerId ?? void 0,
1738
+ deps
1739
+ );
1740
+ const state = createInitialState(instanceName, repoName, repoUrl, {
1103
1741
  containerName: actualContainerName,
1104
- configSource,
1742
+ repoConfigDetected,
1105
1743
  purpose: purposeState
1106
1744
  });
1107
1745
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
@@ -1179,44 +1817,16 @@ function createAttachDefaultDeps() {
1179
1817
  executor,
1180
1818
  container: createContainerLifecycle(executor),
1181
1819
  workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1182
- stateFsDeps: { readFile: readFile5, writeFile: writeFile5, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1820
+ stateFsDeps: { readFile: readFile8, writeFile: writeFile7, rename: rename5, mkdir: mkdir6, appendFile: appendFile4 }
1183
1821
  };
1184
1822
  }
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);
1823
+ async function attachInstance(instanceName, deps, onContainerStarting, onAttaching, repoSlug) {
1824
+ const lookup = await resolveInstance(instanceName, repoSlug, {
1825
+ fsDeps: deps.workspaceFsDeps,
1826
+ readFile: deps.stateFsDeps.readFile
1827
+ });
1201
1828
  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
- };
1829
+ return { ok: false, error: lookup.error };
1220
1830
  }
1221
1831
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
1222
1832
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -1244,11 +1854,10 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1244
1854
  }
1245
1855
  if (statusResult.status === "stopped" || statusResult.status === "not-found") {
1246
1856
  onContainerStarting?.();
1247
- const configSource = state.configSource ?? "baseline";
1248
- const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1857
+ const configPath = join7(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
1249
1858
  const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1250
1859
  remoteEnv: { AGENT_INSTANCE: wsPath.name },
1251
- configPath: baselineConfigPath
1860
+ configPath
1252
1861
  });
1253
1862
  if (!startResult.ok) {
1254
1863
  return {
@@ -1274,9 +1883,28 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1274
1883
  return { ok: true };
1275
1884
  }
1276
1885
 
1886
+ // src/lib/command-helpers.ts
1887
+ async function resolveRepoOrExit(opts) {
1888
+ const executor = createExecutor();
1889
+ const repoResult = await resolveRepo(opts, executor);
1890
+ if (repoResult.resolved) {
1891
+ return repoResult.repoSlug;
1892
+ }
1893
+ if ("error" in repoResult && repoResult.error) {
1894
+ console.error(
1895
+ formatError(
1896
+ createError(repoResult.error.code, repoResult.error.message, repoResult.error.suggestion)
1897
+ )
1898
+ );
1899
+ process.exit(1);
1900
+ }
1901
+ return void 0;
1902
+ }
1903
+
1277
1904
  // 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) => {
1905
+ 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
1906
  const deps = createAttachDefaultDeps();
1907
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
1280
1908
  const result = await attachInstance(
1281
1909
  name,
1282
1910
  deps,
@@ -1286,7 +1914,8 @@ var attachCommand = new Command("attach").description("Attach to an instance's t
1286
1914
  () => {
1287
1915
  console.log();
1288
1916
  console.log("Attaching to tmux session...");
1289
- }
1917
+ },
1918
+ repoSlug
1290
1919
  );
1291
1920
  if (!result.ok) {
1292
1921
  const { code, message, suggestion } = result.error;
@@ -1474,21 +2103,122 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
1474
2103
 
1475
2104
  // src/commands/create.ts
1476
2105
  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) => {
2106
+
2107
+ // src/lib/list-repos.ts
2108
+ async function listRepos(deps) {
2109
+ try {
2110
+ const wsFsDeps = deps?.workspaceFsDeps;
2111
+ const stateFsDeps = deps?.stateFsDeps;
2112
+ const workspaceNames = (await scanWorkspaces(wsFsDeps)).sort();
2113
+ if (workspaceNames.length === 0) {
2114
+ return { ok: true, repos: [] };
2115
+ }
2116
+ const repoMap = /* @__PURE__ */ new Map();
2117
+ for (const wsName of workspaceNames) {
2118
+ const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
2119
+ const state = await readState(wsPath, stateFsDeps);
2120
+ if (state.repoSlug === "unknown") {
2121
+ continue;
2122
+ }
2123
+ const existing = repoMap.get(state.repoSlug);
2124
+ if (existing) {
2125
+ existing.count += 1;
2126
+ } else {
2127
+ repoMap.set(state.repoSlug, { url: state.repoUrl, count: 1 });
2128
+ }
2129
+ }
2130
+ const repos = Array.from(repoMap.entries()).map(([slug, { url, count }]) => ({
2131
+ slug,
2132
+ url,
2133
+ instanceCount: count
2134
+ })).sort((a, b) => a.slug.localeCompare(b.slug));
2135
+ return { ok: true, repos };
2136
+ } catch (err) {
2137
+ const message = err instanceof Error ? err.message : String(err);
2138
+ return {
2139
+ ok: false,
2140
+ repos: null,
2141
+ error: { code: "LIST_REPOS_ERROR", message: `Failed to list repos: ${message}` }
2142
+ };
2143
+ }
2144
+ }
2145
+
2146
+ // src/lib/resolve-repo-arg.ts
2147
+ function isRepoUrl(value) {
2148
+ return value.includes("://") || value.startsWith("git@");
2149
+ }
2150
+ async function resolveRepoArg(repoArg, deps) {
2151
+ if (repoArg === ".") {
2152
+ return { ok: true, url: ".", resolvedFromSlug: false };
2153
+ }
2154
+ if (isRepoUrl(repoArg)) {
2155
+ return { ok: true, url: repoArg, resolvedFromSlug: false };
2156
+ }
2157
+ const listFn = deps?.listRepos ?? listRepos;
2158
+ const result = await listFn();
2159
+ if (!result.ok) {
2160
+ return {
2161
+ ok: false,
2162
+ error: {
2163
+ code: "REPO_LOOKUP_ERROR",
2164
+ message: `Failed to look up repo registry: ${result.error.message}`,
2165
+ suggestion: "Check filesystem permissions for the ~/.agent-env directory."
2166
+ }
2167
+ };
2168
+ }
2169
+ const slugArg = repoArg.toLowerCase();
2170
+ const match = result.repos.find((r) => r.slug === slugArg);
2171
+ if (!match) {
2172
+ return {
2173
+ ok: false,
2174
+ error: {
2175
+ code: "REPO_NOT_FOUND",
2176
+ message: `Repository '${repoArg}' not found.`,
2177
+ suggestion: "Use a full URL or run `agent-env repos` to see tracked repos."
2178
+ }
2179
+ };
2180
+ }
2181
+ return { ok: true, url: match.url, resolvedFromSlug: true };
2182
+ }
2183
+
2184
+ // src/commands/create.ts
2185
+ 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", "[REMOVED] Config merge replaces this flag").option("--no-baseline", "[REMOVED] Config merge replaces this flag").action(async (name, options) => {
2186
+ if (options.baseline !== void 0) {
2187
+ console.error(
2188
+ formatError(
2189
+ createError(
2190
+ "REMOVED_OPTION",
2191
+ "The --baseline / --no-baseline flags have been removed.",
2192
+ "Agent-env now always merges managed config with repo config. No flag needed."
2193
+ )
2194
+ )
2195
+ );
2196
+ process.exit(1);
2197
+ }
1478
2198
  if (!options.repo) {
1479
2199
  console.error(
1480
2200
  formatError(
1481
2201
  createError(
1482
2202
  "MISSING_OPTION",
1483
2203
  "The --repo flag is required.",
1484
- "Usage: agent-env create <name> --repo <url>"
2204
+ "Usage: agent-env create <name> --repo <url|slug>"
1485
2205
  )
1486
2206
  )
1487
2207
  );
1488
2208
  process.exit(1);
1489
2209
  }
1490
2210
  const deps = createDefaultDeps();
1491
- const resolved = await resolveRepoUrl(options.repo, deps.executor);
2211
+ const slugResult = await resolveRepoArg(options.repo);
2212
+ if (!slugResult.ok) {
2213
+ const { code, message, suggestion } = slugResult.error;
2214
+ console.error(formatError(createError(code, message, suggestion)));
2215
+ process.exit(1);
2216
+ }
2217
+ const repoInput = slugResult.url;
2218
+ if (slugResult.resolvedFromSlug) {
2219
+ console.log(`Resolved repo '${options.repo}' \u2192 ${repoInput}`);
2220
+ }
2221
+ const resolved = await resolveRepoUrl(repoInput, deps.executor);
1492
2222
  if (!resolved.ok) {
1493
2223
  const { code, message, suggestion } = resolved.error;
1494
2224
  console.error(formatError(createError(code, message, suggestion)));
@@ -1496,7 +2226,9 @@ var createCommand = new Command3("create").description("Create a new isolated de
1496
2226
  }
1497
2227
  const repoUrl = resolved.url;
1498
2228
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
1499
- const result = await createInstance(name, repoUrl, deps, { purpose: options.purpose });
2229
+ const result = await createInstance(name, repoUrl, deps, {
2230
+ purpose: options.purpose
2231
+ });
1500
2232
  if (!result.ok) {
1501
2233
  const { code, message, suggestion } = result.error;
1502
2234
  console.error(formatError(createError(code, message, suggestion)));
@@ -1622,6 +2354,7 @@ function InstanceList({
1622
2354
  return { ...instance, indicators, indicatorText };
1623
2355
  });
1624
2356
  const nameWidth = Math.max(4, ...augmentedInstances.map((i) => i.name.length)) + 2;
2357
+ const repoWidth = Math.max(4, ...augmentedInstances.map((i) => i.repoSlug.length)) + 2;
1625
2358
  const statusWidth = Math.max(6, ...augmentedInstances.map((i) => statusLabel(i.status, dockerAvailable).length)) + 2;
1626
2359
  const gitWidth = Math.max(3, ...augmentedInstances.map((i) => i.indicatorText.length)) + 2;
1627
2360
  const lastAttachedWidth = Math.max(13, ...augmentedInstances.map((i) => formatLastAttached(i.lastAttached).length)) + 2;
@@ -1629,6 +2362,7 @@ function InstanceList({
1629
2362
  return /* @__PURE__ */ jsxs2(Box, { flexDirection: "column", children: [
1630
2363
  /* @__PURE__ */ jsxs2(Box, { children: [
1631
2364
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("NAME", nameWidth) }),
2365
+ /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("REPO", repoWidth) }),
1632
2366
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("STATUS", statusWidth) }),
1633
2367
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("GIT", gitWidth) }),
1634
2368
  /* @__PURE__ */ jsx2(Text2, { bold: true, children: pad("LAST ATTACHED", lastAttachedWidth) }),
@@ -1637,6 +2371,7 @@ function InstanceList({
1637
2371
  ] }),
1638
2372
  augmentedInstances.map((instance) => /* @__PURE__ */ jsxs2(Box, { children: [
1639
2373
  /* @__PURE__ */ jsx2(Text2, { children: pad(instance.name, nameWidth) }),
2374
+ /* @__PURE__ */ jsx2(Text2, { color: "blue", children: pad(instance.repoSlug, repoWidth) }),
1640
2375
  /* @__PURE__ */ jsx2(Text2, { color: statusColor(instance.status), children: pad(statusLabel(instance.status, dockerAvailable), statusWidth) }),
1641
2376
  /* @__PURE__ */ jsx2(Box, { width: gitWidth, children: instance.indicators.map((ind, idx) => /* @__PURE__ */ jsxs2(Text2, { color: ind.color, children: [
1642
2377
  idx > 0 ? " " : "",
@@ -1789,7 +2524,7 @@ function parseBranches(result) {
1789
2524
  }
1790
2525
 
1791
2526
  // src/lib/list-instances.ts
1792
- async function listInstances(deps) {
2527
+ async function listInstances(deps, opts) {
1793
2528
  try {
1794
2529
  const container = deps?.container ?? createContainerLifecycle();
1795
2530
  const gitDetector = deps?.gitDetector ?? createGitStateDetector();
@@ -1800,43 +2535,55 @@ async function listInstances(deps) {
1800
2535
  return { ok: true, instances: [], dockerAvailable: true };
1801
2536
  }
1802
2537
  const dockerAvailable = await container.isDockerAvailable();
1803
- const instancePromises = workspaceNames.map(async (wsName) => {
2538
+ const repoFilter = opts?.repoFilter?.toLowerCase();
2539
+ const filteredWorkspaces = [];
2540
+ for (const wsName of workspaceNames) {
1804
2541
  const wsPath = getWorkspacePathByName(wsName, wsFsDeps);
1805
2542
  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;
2543
+ if (repoFilter && state.repoSlug.toLowerCase() !== repoFilter) {
2544
+ continue;
1818
2545
  }
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})`;
2546
+ filteredWorkspaces.push({ wsName, wsPath, state });
2547
+ }
2548
+ const instancePromises = filteredWorkspaces.map(
2549
+ async ({ wsName, wsPath, state }) => {
2550
+ const containerPromise = dockerAvailable ? container.containerStatus(state.containerName) : Promise.resolve(null);
2551
+ const gitPromise = gitDetector.getGitState(wsPath.root);
2552
+ const [containerResult, gitState] = await Promise.all([containerPromise, gitPromise]);
2553
+ let status;
2554
+ if (!dockerAvailable || containerResult === null) {
2555
+ status = "unknown";
2556
+ } else if (!containerResult.ok) {
2557
+ status = "unknown";
2558
+ } else if (containerResult.status === "not-found") {
2559
+ status = "orphaned";
2560
+ } else {
2561
+ status = containerResult.status;
2562
+ }
2563
+ let sshConnection = null;
2564
+ if (status === "running" && containerResult && containerResult.ok) {
2565
+ if ("22/tcp" in containerResult.ports) {
2566
+ const orbDomains = containerResult.labels["dev.orbstack.domains"];
2567
+ const hostname = orbDomains?.split(",")[0]?.trim() || `${state.containerName}.orb.local`;
2568
+ sshConnection = `node@${hostname}`;
2569
+ const hostPort = containerResult.ports["22/tcp"];
2570
+ if (hostPort && hostPort !== "22") {
2571
+ sshConnection += ` (localhost:${hostPort})`;
2572
+ }
1828
2573
  }
1829
2574
  }
2575
+ return {
2576
+ name: wsName,
2577
+ repoSlug: state.repoSlug,
2578
+ repoUrl: state.repoUrl,
2579
+ status,
2580
+ lastAttached: state.lastAttached !== "unknown" ? state.lastAttached : null,
2581
+ purpose: state.purpose,
2582
+ gitState,
2583
+ sshConnection
2584
+ };
1830
2585
  }
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
- });
2586
+ );
1840
2587
  const instances = await Promise.all(instancePromises);
1841
2588
  return { ok: true, instances, dockerAvailable };
1842
2589
  } catch (err) {
@@ -1851,8 +2598,10 @@ async function listInstances(deps) {
1851
2598
  }
1852
2599
 
1853
2600
  // 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();
2601
+ 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) => {
2602
+ const result = await listInstances(void 0, {
2603
+ repoFilter: options.repo
2604
+ });
1856
2605
  if (!result.ok) {
1857
2606
  const error = createError(
1858
2607
  result.error.code,
@@ -1877,6 +2626,8 @@ var listCommand = new Command4("list").alias("ps").description("List all instanc
1877
2626
  ok: true,
1878
2627
  data: result.instances.map((i) => ({
1879
2628
  name: i.name,
2629
+ repoSlug: i.repoSlug,
2630
+ repoUrl: i.repoUrl,
1880
2631
  status: i.status,
1881
2632
  lastAttached: i.lastAttached,
1882
2633
  purpose: i.purpose,
@@ -1906,11 +2657,11 @@ var defaultPurposeCommandDeps = {
1906
2657
  function createPurposeCommand(deps = defaultPurposeCommandDeps) {
1907
2658
  return new Command5("purpose").description(
1908
2659
  "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) => {
2660
+ ).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
2661
  if (deps.isInsideContainer()) {
1911
2662
  await handleContainerMode(nameOrValue);
1912
2663
  } else {
1913
- await handleHostMode(nameOrValue, value);
2664
+ await handleHostMode(nameOrValue, value, options?.repo);
1914
2665
  }
1915
2666
  });
1916
2667
  }
@@ -1925,7 +2676,7 @@ async function handleContainerMode(purposeValue) {
1925
2676
  handleSetResult(result);
1926
2677
  }
1927
2678
  }
1928
- async function handleHostMode(name, value) {
2679
+ async function handleHostMode(name, value, repo) {
1929
2680
  if (!name) {
1930
2681
  console.error(
1931
2682
  formatError(
@@ -1937,13 +2688,15 @@ async function handleHostMode(name, value) {
1937
2688
  )
1938
2689
  );
1939
2690
  process.exit(1);
2691
+ return;
1940
2692
  }
2693
+ const repoSlug = await resolveRepoOrExit({ repo, cwd: process.cwd() });
1941
2694
  const deps = createPurposeDefaultDeps();
1942
2695
  if (value === void 0) {
1943
- const result = await getPurpose(name, deps);
2696
+ const result = await getPurpose(name, deps, repoSlug);
1944
2697
  handleGetResult(result);
1945
2698
  } else {
1946
- const result = await setPurpose(name, value, deps);
2699
+ const result = await setPurpose(name, value, deps, repoSlug);
1947
2700
  handleSetResult(result);
1948
2701
  }
1949
2702
  }
@@ -1970,6 +2723,9 @@ function handleSetResult(result) {
1970
2723
  } else {
1971
2724
  console.log("Purpose updated");
1972
2725
  }
2726
+ if (result.warning) {
2727
+ console.warn(`\x1B[33m\u26A0\x1B[0m ${result.warning}`);
2728
+ }
1973
2729
  }
1974
2730
 
1975
2731
  // src/commands/rebuild.ts
@@ -1979,102 +2735,80 @@ import { createInterface } from "readline";
1979
2735
 
1980
2736
  // src/lib/rebuild-instance.ts
1981
2737
  import {
2738
+ access as access4,
1982
2739
  cp as cp3,
1983
2740
  mkdir as mkdir7,
1984
2741
  readdir as readdir6,
1985
- readFile as readFile6,
1986
- rename as rename5,
2742
+ readFile as readFile9,
2743
+ rename as rename6,
1987
2744
  rm as rm3,
1988
2745
  stat as stat6,
1989
- writeFile as writeFile6,
2746
+ writeFile as writeFile8,
1990
2747
  appendFile as appendFile5
1991
2748
  } from "fs/promises";
1992
2749
  import { homedir as homedir5 } from "os";
1993
- import { join as join6 } from "path";
2750
+ import { join as join8 } from "path";
1994
2751
  function createRebuildDefaultDeps() {
1995
2752
  const executor = createExecutor();
1996
2753
  return {
1997
2754
  executor,
1998
2755
  container: createContainerLifecycle(executor),
1999
2756
  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 },
2757
+ stateFsDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, mkdir: mkdir7, appendFile: appendFile5 },
2758
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile9, stat: stat6, writeFile: writeFile8 },
2759
+ mergeDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, access: access4 },
2002
2760
  rm: rm3,
2003
- rename: rename5,
2761
+ rename: rename6,
2004
2762
  logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
2005
2763
  };
2006
2764
  }
2007
- async function refreshConfig(wsRoot, containerName, configSource, deps) {
2008
- if (configSource === "baseline") {
2009
- const agentEnvDir = join6(wsRoot, AGENT_ENV_DIR);
2010
- try {
2011
- await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
2012
- await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
2013
- recursive: true
2014
- });
2015
- await patchContainerName(wsRoot, containerName, deps.devcontainerFsDeps, AGENT_ENV_DIR);
2016
- } catch (err) {
2017
- return {
2018
- ok: false,
2019
- error: {
2020
- code: "CONFIG_REFRESH_FAILED",
2021
- message: `Failed to refresh baseline config: ${err instanceof Error ? err.message : String(err)}`,
2022
- suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
2023
- }
2024
- };
2025
- }
2026
- } else {
2027
- const configExists = await hasDevcontainerConfig(wsRoot, deps.devcontainerFsDeps);
2028
- if (!configExists) {
2765
+ async function refreshMergedConfig(wsRoot, containerName, wsName, repoSlug, purpose, repoConfigExpected, deps) {
2766
+ try {
2767
+ const defaults = await loadManagedDefaults(deps.mergeDeps);
2768
+ const managed = buildManagedConfig(defaults, {
2769
+ instanceName: wsName,
2770
+ containerName,
2771
+ repoSlug,
2772
+ purpose
2773
+ });
2774
+ const repoConfig = await readRepoConfig(wsRoot, deps.mergeDeps, deps.logger);
2775
+ if (repoConfigExpected && !repoConfig) {
2029
2776
  return {
2030
2777
  ok: false,
2031
2778
  error: {
2032
- code: "CONFIG_MISSING",
2033
- message: "Repo-provided devcontainer config is missing.",
2034
- suggestion: "Re-clone the repository or provide a devcontainer config manually."
2779
+ code: "REPO_CONFIG_MISSING",
2780
+ message: `Repo devcontainer config was present at creation but is now missing from ${wsRoot}`,
2781
+ suggestion: "Restore the repo config, or recreate the instance with `agent-env create` to generate a managed-only config."
2035
2782
  }
2036
2783
  };
2037
2784
  }
2038
- const devcontainerDir = join6(wsRoot, ".devcontainer");
2039
- const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
2040
- if (dirExists) {
2041
- const jsonExists = await deps.devcontainerFsDeps.stat(join6(devcontainerDir, "devcontainer.json")).catch(() => null);
2042
- if (!jsonExists) {
2043
- return {
2044
- ok: false,
2045
- error: {
2046
- code: "CONFIG_CORRUPT",
2047
- message: "Repo-provided devcontainer config is incomplete (missing devcontainer.json).",
2048
- suggestion: "Ensure .devcontainer/devcontainer.json exists."
2049
- }
2050
- };
2051
- }
2052
- }
2053
- }
2054
- return { ok: true };
2055
- }
2056
- async function lookupWorkspace(instanceName, deps) {
2057
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
2058
- 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
- };
2785
+ if (repoConfig) {
2786
+ validateRepoConfig(repoConfig, deps.logger);
2068
2787
  }
2788
+ const merged = mergeDevcontainerConfigs(managed, repoConfig);
2789
+ await copyManagedAssets(wsRoot, deps.devcontainerFsDeps);
2790
+ const configPath = join8(wsRoot, AGENT_ENV_DIR, "devcontainer.json");
2791
+ await writeGeneratedConfig(configPath, merged, deps.mergeDeps);
2792
+ return { ok: true, repoConfigDetected: repoConfig !== void 0 };
2793
+ } catch (err) {
2069
2794
  return {
2070
2795
  ok: false,
2071
2796
  error: {
2072
- code: "WORKSPACE_NOT_FOUND",
2073
- message: `Instance '${instanceName}' not found`,
2074
- suggestion: "Use `agent-env list` to see available instances."
2797
+ code: "CONFIG_REFRESH_FAILED",
2798
+ message: `Failed to refresh config: ${err instanceof Error ? err.message : String(err)}`,
2799
+ suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
2075
2800
  }
2076
2801
  };
2077
2802
  }
2803
+ }
2804
+ async function lookupWorkspace(instanceName, deps, repoSlug) {
2805
+ const lookup = await resolveInstance(instanceName, repoSlug, {
2806
+ fsDeps: deps.workspaceFsDeps,
2807
+ readFile: deps.stateFsDeps.readFile
2808
+ });
2809
+ if (!lookup.found) {
2810
+ return { ok: false, error: lookup.error };
2811
+ }
2078
2812
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2079
2813
  const state = await readState(wsPath, deps.stateFsDeps);
2080
2814
  return { ok: true, wsPath, state };
@@ -2152,14 +2886,28 @@ async function teardownContainer(containerName, container, statusResult) {
2152
2886
  }
2153
2887
  return { ok: true };
2154
2888
  }
2155
- async function rebuildInstance(instanceName, deps, options) {
2156
- const {
2157
- force = false,
2158
- configSource: overrideConfigSource,
2159
- pull = true,
2160
- noCache = true
2161
- } = options ?? {};
2162
- const wsLookup = await lookupWorkspace(instanceName, deps);
2889
+ async function startAndDiscoverContainer(wsPath, containerName, purpose, buildNoCache, container) {
2890
+ const configPath = join8(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
2891
+ const containerResult = await container.devcontainerUp(wsPath.root, containerName, {
2892
+ buildNoCache,
2893
+ remoteEnv: { AGENT_INSTANCE: wsPath.name, AGENT_ENV_PURPOSE: purpose },
2894
+ configPath
2895
+ });
2896
+ if (!containerResult.ok) {
2897
+ return { ok: false, error: containerResult.error };
2898
+ }
2899
+ let actualName = containerName;
2900
+ if (containerResult.containerId) {
2901
+ const discovered = await container.getContainerNameById(containerResult.containerId);
2902
+ if (discovered) {
2903
+ actualName = discovered;
2904
+ }
2905
+ }
2906
+ return { ok: true, containerName: actualName };
2907
+ }
2908
+ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2909
+ const { force = false, pull = true, noCache = true } = options ?? {};
2910
+ const wsLookup = await lookupWorkspace(instanceName, deps, repoSlug);
2163
2911
  if (!wsLookup.ok) {
2164
2912
  return { ok: false, error: wsLookup.error };
2165
2913
  }
@@ -2176,18 +2924,15 @@ async function rebuildInstance(instanceName, deps, options) {
2176
2924
  }
2177
2925
  };
2178
2926
  }
2179
- const configSource = overrideConfigSource ?? state.configSource;
2180
- if (!configSource) {
2181
- return {
2182
- ok: false,
2183
- error: {
2184
- code: "CONFIG_SOURCE_UNKNOWN",
2185
- message: `Instance '${instanceName}' was created before config tracking was added.`,
2186
- suggestion: 'Set configSource manually in .agent-env/state.json ("baseline" or "repo"), then retry.'
2187
- }
2188
- };
2189
- }
2190
- const configResult = await refreshConfig(wsPath.root, containerName, configSource, deps);
2927
+ const configResult = await refreshMergedConfig(
2928
+ wsPath.root,
2929
+ containerName,
2930
+ wsPath.name,
2931
+ state.repoSlug ?? "",
2932
+ state.purpose ?? "",
2933
+ state.repoConfigDetected,
2934
+ deps
2935
+ );
2191
2936
  if (!configResult.ok) {
2192
2937
  return { ok: false, error: configResult.error };
2193
2938
  }
@@ -2213,36 +2958,26 @@ async function rebuildInstance(instanceName, deps, options) {
2213
2958
  if (!teardownResult.ok) {
2214
2959
  return { ok: false, error: teardownResult.error, wasRunning };
2215
2960
  }
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
- }
2961
+ const startResult = await startAndDiscoverContainer(
2962
+ wsPath,
2963
+ containerName,
2964
+ state.purpose ?? "",
2965
+ noCache && hasDockerfile,
2966
+ deps.container
2967
+ );
2968
+ if (!startResult.ok) {
2969
+ return { ok: false, error: startResult.error, wasRunning };
2236
2970
  }
2237
2971
  const updatedState = {
2238
2972
  ...state,
2239
- containerName: actualContainerName,
2240
- lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
2973
+ containerName: startResult.containerName,
2974
+ lastRebuilt: (/* @__PURE__ */ new Date()).toISOString(),
2975
+ repoConfigDetected: configResult.repoConfigDetected
2241
2976
  };
2242
2977
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
2243
2978
  return {
2244
2979
  ok: true,
2245
- containerName: actualContainerName,
2980
+ containerName: startResult.containerName,
2246
2981
  wasRunning
2247
2982
  };
2248
2983
  }
@@ -2269,9 +3004,10 @@ Any active sessions will be lost. Continue? (y/N) `,
2269
3004
  });
2270
3005
  });
2271
3006
  }
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(
3007
+ 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
3008
  async (name, options) => {
2274
3009
  const deps = createRebuildDefaultDeps();
3010
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2275
3011
  let confirmed = false;
2276
3012
  if (!options.yes && !options.force && process.stdin.isTTY) {
2277
3013
  confirmed = await promptForConfirmation(name);
@@ -2291,7 +3027,7 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2291
3027
  } else {
2292
3028
  console.log(`Rebuilding instance '${name}'...`);
2293
3029
  }
2294
- const result = await rebuildInstance(name, deps, rebuildOptions);
3030
+ const result = await rebuildInstance(name, deps, rebuildOptions, repoSlug);
2295
3031
  if (!result.ok) {
2296
3032
  if (result.error.code === "CONTAINER_RUNNING") {
2297
3033
  console.error("");
@@ -2320,16 +3056,16 @@ import { createInterface as createInterface2 } from "readline";
2320
3056
  // src/lib/audit-log.ts
2321
3057
  import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
2322
3058
  import { homedir as homedir6 } from "os";
2323
- import { join as join7 } from "path";
3059
+ import { join as join9 } from "path";
2324
3060
  function createAuditLogDefaultDeps() {
2325
3061
  return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
2326
3062
  }
2327
3063
  function getAuditLogPath(deps) {
2328
- return join7(deps.homedir(), AGENT_ENV_DIR, "audit.log");
3064
+ return join9(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2329
3065
  }
2330
3066
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
2331
3067
  const logPath = getAuditLogPath(deps);
2332
- await deps.mkdir(join7(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
3068
+ await deps.mkdir(join9(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2333
3069
  const line = JSON.stringify(entry) + "\n";
2334
3070
  await deps.appendFile(logPath, line, "utf-8");
2335
3071
  }
@@ -2344,7 +3080,7 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
2344
3080
  }
2345
3081
 
2346
3082
  // 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";
3083
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile10, rm as rm4, stat as stat7 } from "fs/promises";
2348
3084
  import { homedir as homedir7 } from "os";
2349
3085
  function createRemoveDefaultDeps() {
2350
3086
  const executor = createExecutor();
@@ -2353,7 +3089,7 @@ function createRemoveDefaultDeps() {
2353
3089
  container: createContainerLifecycle(executor),
2354
3090
  gitDetector: createGitStateDetector(executor),
2355
3091
  workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
2356
- stateFsDeps: { readFile: readFile7 },
3092
+ stateFsDeps: { readFile: readFile10 },
2357
3093
  deleteFsDeps: { rm: rm4 }
2358
3094
  };
2359
3095
  }
@@ -2391,27 +3127,13 @@ function evaluateSafetyChecks(gitState) {
2391
3127
  }
2392
3128
  return blockers;
2393
3129
  }
2394
- async function removeInstance(instanceName, deps, force = false) {
2395
- const lookup = await findWorkspaceByName(instanceName, deps.workspaceFsDeps);
3130
+ async function removeInstance(instanceName, deps, force = false, repoSlug) {
3131
+ const lookup = await resolveInstance(instanceName, repoSlug, {
3132
+ fsDeps: deps.workspaceFsDeps,
3133
+ readFile: deps.stateFsDeps.readFile
3134
+ });
2396
3135
  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
- };
3136
+ return { ok: false, error: lookup.error };
2415
3137
  }
2416
3138
  const wsPath = getWorkspacePathByName(lookup.workspaceName, deps.workspaceFsDeps);
2417
3139
  const state = await readState(wsPath, deps.stateFsDeps);
@@ -2647,7 +3369,7 @@ async function resolveConfirmation(name, options) {
2647
3369
  }
2648
3370
  return "typed-name";
2649
3371
  }
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(
3372
+ 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
3373
  "--yes",
2652
3374
  "Skip confirmation prompt for --force (DANGEROUS: skips all safety prompts, for scripts only)"
2653
3375
  ).action(async (name, options) => {
@@ -2664,8 +3386,9 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2664
3386
  process.exit(1);
2665
3387
  return;
2666
3388
  }
3389
+ const repoSlug = await resolveRepoOrExit({ repo: options.repo, cwd: process.cwd() });
2667
3390
  const deps = createRemoveDefaultDeps();
2668
- const checkResult = await removeInstance(name, deps, false);
3391
+ const checkResult = await removeInstance(name, deps, false, repoSlug);
2669
3392
  if (checkResult.ok) {
2670
3393
  if (options.force) {
2671
3394
  console.log(`Instance '${name}' force-removed. Data permanently deleted.`);
@@ -2697,7 +3420,7 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2697
3420
  process.exit(1);
2698
3421
  return;
2699
3422
  }
2700
- const forceResult = await removeInstance(name, deps, true);
3423
+ const forceResult = await removeInstance(name, deps, true, repoSlug);
2701
3424
  if (!forceResult.ok) {
2702
3425
  const { code, message, suggestion } = forceResult.error;
2703
3426
  console.error(formatError(createError(code, message, suggestion)));
@@ -2708,6 +3431,111 @@ var removeCommand = new Command7("remove").description("Remove an instance with
2708
3431
  await writeAuditLog(name, gitState ?? null, confirmationMethod);
2709
3432
  });
2710
3433
 
3434
+ // src/commands/repos.ts
3435
+ import { Command as Command8 } from "commander";
3436
+ var reposCommand = new Command8("repos").description("List tracked repositories").option("--json", "Output in JSON format").action(async (options) => {
3437
+ const result = await listRepos();
3438
+ if (!result.ok) {
3439
+ const error = createError(
3440
+ result.error.code,
3441
+ result.error.message,
3442
+ "Check if ~/.agent-env/workspaces/ is accessible."
3443
+ );
3444
+ if (options.json) {
3445
+ const output = {
3446
+ ok: false,
3447
+ data: null,
3448
+ error: { code: error.code, message: error.message, suggestion: error.suggestion }
3449
+ };
3450
+ console.log(JSON.stringify(output, null, 2));
3451
+ } else {
3452
+ console.error(formatError(error));
3453
+ }
3454
+ process.exitCode = 1;
3455
+ return;
3456
+ }
3457
+ if (options.json) {
3458
+ const output = {
3459
+ ok: true,
3460
+ data: result.repos.map((r) => ({
3461
+ slug: r.slug,
3462
+ url: r.url,
3463
+ instanceCount: r.instanceCount
3464
+ })),
3465
+ error: null
3466
+ };
3467
+ console.log(JSON.stringify(output, null, 2));
3468
+ return;
3469
+ }
3470
+ if (result.repos.length === 0) {
3471
+ console.log(
3472
+ "No repositories tracked. Create an instance with: agent-env create <name> --repo <url|slug>"
3473
+ );
3474
+ return;
3475
+ }
3476
+ const slugWidth = Math.max(4, ...result.repos.map((r) => r.slug.length));
3477
+ const countWidth = 10;
3478
+ const header = `${"REPO".padEnd(slugWidth)} ${"INSTANCES".padEnd(countWidth)} URL`;
3479
+ console.log(header);
3480
+ for (const repo of result.repos) {
3481
+ const line = `${repo.slug.padEnd(slugWidth)} ${String(repo.instanceCount).padEnd(countWidth)} ${repo.url}`;
3482
+ console.log(line);
3483
+ }
3484
+ });
3485
+
3486
+ // src/commands/tmux-status.ts
3487
+ import { Command as Command9 } from "commander";
3488
+
3489
+ // src/lib/tmux-status.ts
3490
+ import { readFile as readFile11 } from "fs/promises";
3491
+ var MAX_PURPOSE_DISPLAY_LEN = 40;
3492
+ var defaultDeps2 = { readFile: readFile11 };
3493
+ function formatTmuxStatus(instance, purpose) {
3494
+ if (!instance) return "?";
3495
+ if (!purpose) return instance;
3496
+ if (purpose.length > MAX_PURPOSE_DISPLAY_LEN) {
3497
+ return `${instance} | ${purpose.slice(0, MAX_PURPOSE_DISPLAY_LEN)}\u2026`;
3498
+ }
3499
+ return `${instance} | ${purpose}`;
3500
+ }
3501
+ async function getTmuxStatus(statePath, deps = defaultDeps2) {
3502
+ let content;
3503
+ try {
3504
+ content = await deps.readFile(statePath, "utf-8");
3505
+ } catch {
3506
+ return "?";
3507
+ }
3508
+ let parsed;
3509
+ try {
3510
+ parsed = JSON.parse(content);
3511
+ } catch {
3512
+ return "?";
3513
+ }
3514
+ if (typeof parsed !== "object" || parsed === null) return "?";
3515
+ const obj = parsed;
3516
+ const instance = typeof obj.instance === "string" ? obj.instance : "";
3517
+ const purpose = typeof obj.purpose === "string" ? obj.purpose : null;
3518
+ return formatTmuxStatus(instance, purpose);
3519
+ }
3520
+
3521
+ // src/commands/tmux-status.ts
3522
+ var defaultDeps3 = {
3523
+ isInsideContainer,
3524
+ getTmuxStatus,
3525
+ statePath: CONTAINER_STATE_PATH
3526
+ };
3527
+ function createTmuxStatusCommand(deps = defaultDeps3) {
3528
+ return new Command9("tmux-status").description("Output formatted instance status for tmux status bar (container only)").action(async () => {
3529
+ if (!deps.isInsideContainer()) {
3530
+ console.log("?");
3531
+ return;
3532
+ }
3533
+ const display = await deps.getTmuxStatus(deps.statePath);
3534
+ console.log(display);
3535
+ });
3536
+ }
3537
+ var tmuxStatusCommand = createTmuxStatusCommand();
3538
+
2711
3539
  // src/components/InteractiveMenu.tsx
2712
3540
  import { Select } from "@inkjs/ui";
2713
3541
  import { Box as Box2, Text as Text3 } from "ink";
@@ -2890,6 +3718,8 @@ program.addCommand(attachCommand);
2890
3718
  program.addCommand(rebuildCommand);
2891
3719
  program.addCommand(removeCommand);
2892
3720
  program.addCommand(purposeCommand);
3721
+ program.addCommand(reposCommand);
3722
+ program.addCommand(tmuxStatusCommand);
2893
3723
  program.addCommand(completionCommand);
2894
3724
  program.action(async () => {
2895
3725
  if (!process.stdin.isTTY) {