@zookanalytics/agent-env 0.5.0 → 0.7.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.
Files changed (2) hide show
  1. package/dist/cli.js +785 -389
  2. package/package.json +1 -1
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.5.0",
45
+ version: "0.7.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 readFile7, rename as rename4, stat as stat5, writeFile as writeFile6 } 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 join6 } 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,28 +406,30 @@ 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 readFile6,
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 writeFile5
418
+ writeFile as writeFile6
418
419
  } from "fs/promises";
419
420
  import { homedir as homedir3 } from "os";
420
- import { dirname as dirname2, join as join5 } from "path";
421
+ import { dirname as dirname2, join as join6 } from "path";
421
422
 
422
- // src/lib/devcontainer.ts
423
- import { parse as parseJsonc } from "jsonc-parser";
424
- import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
425
- import { dirname, join } from "path";
426
- import { fileURLToPath } from "url";
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";
427
429
 
428
430
  // src/lib/container-env.ts
429
- var CONTAINER_STATE_PATH = "/etc/agent-env/state.json";
430
- var CONTAINER_AGENT_ENV_DIR = "/etc/agent-env";
431
+ var 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";
431
433
  var defaultContainerEnvDeps = {
432
434
  getEnv: (key) => process.env[key]
433
435
  };
@@ -435,6 +437,13 @@ function isInsideContainer(deps = defaultContainerEnvDeps) {
435
437
  return deps.getEnv("AGENT_ENV_CONTAINER") === "true";
436
438
  }
437
439
 
440
+ // src/lib/devcontainer.ts
441
+ import { parse as parseJsonc } from "jsonc-parser";
442
+ import { accessSync } from "fs";
443
+ import { access, cp, mkdir, readdir, readFile, stat, writeFile } from "fs/promises";
444
+ import { dirname, join } from "path";
445
+ import { fileURLToPath } from "url";
446
+
438
447
  // src/lib/types.ts
439
448
  var AGENT_ENV_DIR = ".agent-env";
440
449
  var WORKSPACES_DIR = "workspaces";
@@ -457,7 +466,8 @@ function createFallbackState(workspaceName) {
457
466
  createdAt: "unknown",
458
467
  lastAttached: "unknown",
459
468
  purpose: null,
460
- containerName: `${CONTAINER_PREFIX}${workspaceName}`
469
+ containerName: `${CONTAINER_PREFIX}${workspaceName}`,
470
+ repoConfigDetected: false
461
471
  };
462
472
  }
463
473
 
@@ -466,50 +476,34 @@ var defaultFsDeps = { access, cp, mkdir, readdir, readFile, stat, writeFile };
466
476
  var DEVCONTAINER_DIR = ".devcontainer";
467
477
  var DEVCONTAINER_JSON = "devcontainer.json";
468
478
  var DOT_DEVCONTAINER_JSON = ".devcontainer.json";
469
- function getBaselineConfigPath() {
470
- const currentFile = fileURLToPath(import.meta.url);
471
- const packageRoot = dirname(dirname(dirname(currentFile)));
472
- return join(packageRoot, "config", "baseline");
473
- }
474
- function getTemplatesPath() {
475
- const currentFile = fileURLToPath(import.meta.url);
476
- const packageRoot = dirname(dirname(dirname(currentFile)));
477
- return join(packageRoot, "config", "templates");
478
- }
479
- async function hasDevcontainerConfig(workspacePath, deps = defaultFsDeps) {
480
- try {
481
- const dirStats = await deps.stat(join(workspacePath, DEVCONTAINER_DIR));
482
- if (dirStats.isDirectory()) {
483
- return true;
484
- }
485
- } catch {
486
- }
487
- try {
488
- const fileStats = await deps.stat(join(workspacePath, DEVCONTAINER_JSON));
489
- if (fileStats.isFile()) {
490
- return true;
491
- }
492
- } catch {
493
- }
494
- try {
495
- const dotFileStats = await deps.stat(join(workspacePath, DOT_DEVCONTAINER_JSON));
496
- if (dotFileStats.isFile()) {
497
- 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;
498
499
  }
499
- } catch {
500
500
  }
501
- return false;
502
501
  }
503
- async function copyBaselineConfig(workspacePath, deps = defaultFsDeps) {
504
- const baselinePath = getBaselineConfigPath();
505
- try {
506
- await deps.stat(baselinePath);
507
- } catch {
508
- throw new Error(`Baseline config not found at ${baselinePath}. Package may be corrupted.`);
509
- }
510
- const targetDir = join(workspacePath, AGENT_ENV_DIR);
511
- await deps.mkdir(targetDir, { recursive: true });
512
- await deps.cp(baselinePath, targetDir, { recursive: true });
502
+ function getBaselineConfigPath() {
503
+ return join(getPackageRoot(), "config", "baseline");
504
+ }
505
+ function getTemplatesPath() {
506
+ return join(getPackageRoot(), "config", "templates");
513
507
  }
514
508
  async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
515
509
  const templatesPath = getTemplatesPath();
@@ -524,58 +518,15 @@ async function copyStatusBarTemplate(workspacePath, deps = defaultFsDeps) {
524
518
  await deps.mkdir(targetDir, { recursive: true });
525
519
  await deps.cp(srcFile, join(targetDir, "statusBar.template.json"));
526
520
  }
527
- var STATUS_BAR_JSON_FILENAME = "statusBar.json";
528
- function applyContainerNamePatch(config, containerName) {
529
- const existing = Array.isArray(config.runArgs) ? config.runArgs : [];
530
- const filtered = existing.filter((arg) => !arg.startsWith("--name="));
531
- config.runArgs = [...filtered, `--name=${containerName}`];
532
- return config;
533
- }
534
- function applyContainerEnvPatch(config, envVars) {
535
- const existing = typeof config.containerEnv === "object" && config.containerEnv !== null ? config.containerEnv : {};
536
- config.containerEnv = { ...existing, ...envVars };
537
- return config;
538
- }
539
- function applyVscodeSettingsPatch(config) {
540
- if (typeof config.customizations !== "object" || config.customizations === null) {
541
- config.customizations = {};
542
- }
543
- const customizations = config.customizations;
544
- if (typeof customizations.vscode !== "object" || customizations.vscode === null) {
545
- customizations.vscode = {};
546
- }
547
- const vscode = customizations.vscode;
548
- if (typeof vscode.settings !== "object" || vscode.settings === null) {
549
- vscode.settings = {};
550
- }
551
- const settings = vscode.settings;
552
- const existingFilewatcherCommands = Array.isArray(settings["filewatcher.commands"]) ? settings["filewatcher.commands"] : [];
553
- const statusBarWatcher = {
554
- match: `${STATUS_BAR_JSON_FILENAME}$`,
555
- event: "onFolderChange",
556
- vscodeTask: "betterStatusBar.refreshButtons"
557
- };
558
- const hasStatusBarWatcher = existingFilewatcherCommands.some((cmd) => {
559
- if (typeof cmd !== "object" || cmd === null) return false;
560
- const c = cmd;
561
- return c.match === statusBarWatcher.match && c.event === statusBarWatcher.event && c.vscodeTask === statusBarWatcher.vscodeTask;
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")
562
528
  });
563
- const mergedFilewatcherCommands = hasStatusBarWatcher ? existingFilewatcherCommands : [...existingFilewatcherCommands, statusBarWatcher];
564
- vscode.settings = {
565
- ...settings,
566
- "betterStatusBar.configurationFile": `${CONTAINER_AGENT_ENV_DIR}/${STATUS_BAR_JSON_FILENAME}`,
567
- "filewatcher.commands": mergedFilewatcherCommands
568
- };
569
- return config;
570
- }
571
- async function applyBaselinePatches(workspacePath, containerName, envVars, deps, configDir) {
572
- const configPath = join(workspacePath, configDir, "devcontainer.json");
573
- const content = await deps.readFile(configPath, "utf-8");
574
- let config = JSON.parse(content);
575
- config = applyContainerNamePatch(config, containerName);
576
- config = applyContainerEnvPatch(config, envVars);
577
- config = applyVscodeSettingsPatch(config);
578
- await deps.writeFile(configPath, JSON.stringify(config, null, 2) + "\n");
529
+ await copyStatusBarTemplate(workspacePath, deps);
579
530
  }
580
531
  async function resolveDockerfilePath(workspacePath, deps) {
581
532
  const candidates = [
@@ -647,22 +598,399 @@ function parseDockerfileImages(content, logger) {
647
598
  return [...images];
648
599
  }
649
600
 
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"
607
+ };
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;
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
+
650
980
  // src/lib/purpose-instance.ts
651
- import { appendFile as appendFile2, mkdir as mkdir4, readdir as readdir3, readFile as readFile5, rename as rename2, stat as stat3, writeFile as writeFile4 } from "fs/promises";
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";
652
982
  import { homedir as homedir2 } from "os";
653
983
 
654
984
  // src/lib/state.ts
655
- import { appendFile, mkdir as mkdir2, readFile as readFile2, rename, writeFile as writeFile2 } from "fs/promises";
656
- import { join as join2 } from "path";
657
- 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 };
658
988
  async function readState(wsPath, deps = defaultStateFsDeps) {
659
989
  try {
660
990
  const content = await deps.readFile(wsPath.stateFile, "utf-8");
661
991
  const parsed = JSON.parse(content);
662
- if (!isValidState(parsed)) {
663
- return migrateOldState(parsed, wsPath.name) ?? createFallbackState(wsPath.name);
664
- }
665
- return parsed;
992
+ const state = isValidState(parsed) ? parsed : migrateOldState(parsed, wsPath.name) ?? createFallbackState(wsPath.name);
993
+ return migrateConfigSource(state);
666
994
  } catch (err) {
667
995
  if (err instanceof SyntaxError || err.code === "ENOENT") {
668
996
  return createFallbackState(wsPath.name);
@@ -671,14 +999,16 @@ async function readState(wsPath, deps = defaultStateFsDeps) {
671
999
  }
672
1000
  }
673
1001
  async function writeStateAtomic(wsPath, state, deps = defaultStateFsDeps) {
674
- const tmpPath = join2(wsPath.agentEnvDir, STATE_FILE_TMP);
1002
+ const tmpPath = join3(wsPath.agentEnvDir, STATE_FILE_TMP);
675
1003
  await deps.mkdir(wsPath.agentEnvDir, { recursive: true });
676
1004
  const content = JSON.stringify(state, null, 2) + "\n";
677
1005
  await deps.writeFile(tmpPath, content, "utf-8");
678
1006
  await deps.rename(tmpPath, wsPath.stateFile);
679
1007
  }
680
1008
  function createInitialState(instance, repoSlug, repoUrl, options) {
681
- const { containerName, configSource, purpose } = options ?? {};
1009
+ const { containerName, repoConfigDetected, purpose } = options ?? {
1010
+ repoConfigDetected: false
1011
+ };
682
1012
  const now = (/* @__PURE__ */ new Date()).toISOString();
683
1013
  const workspaceName = `${repoSlug}-${instance}`;
684
1014
  return {
@@ -689,7 +1019,7 @@ function createInitialState(instance, repoSlug, repoUrl, options) {
689
1019
  lastAttached: now,
690
1020
  purpose: purpose ?? null,
691
1021
  containerName: containerName ?? `${CONTAINER_PREFIX}${workspaceName}`,
692
- configSource: configSource ?? "baseline"
1022
+ repoConfigDetected
693
1023
  };
694
1024
  }
695
1025
  function extractRepoName(url) {
@@ -726,9 +1056,17 @@ function isValidState(value) {
726
1056
  const obj = value;
727
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";
728
1058
  }
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
+ }
729
1067
  var GIT_EXCLUDE_PATTERNS = [`${AGENT_ENV_DIR}/`];
730
1068
  async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
731
- const excludePath = join2(workspaceRoot, ".git", "info", "exclude");
1069
+ const excludePath = join3(workspaceRoot, ".git", "info", "exclude");
732
1070
  try {
733
1071
  const content = await deps.readFile(excludePath, "utf-8");
734
1072
  const lines = content.split("\n");
@@ -751,15 +1089,16 @@ async function ensureGitExclude(workspaceRoot, deps = defaultStateFsDeps) {
751
1089
  }
752
1090
 
753
1091
  // src/lib/status-bar.ts
754
- import { readFile as readFile3, writeFile as writeFile3 } from "fs/promises";
755
- import { join as join3 } from "path";
1092
+ import { readFile as readFile4, writeFile as writeFile4 } from "fs/promises";
1093
+ import { join as join4 } from "path";
756
1094
  var STATUS_BAR_TEMPLATE_JSON = "statusBar.template.json";
757
1095
  var STATUS_BAR_JSON = "statusBar.json";
1096
+ var TEMPLATE_NOT_FOUND = "TEMPLATE_NOT_FOUND";
758
1097
  var PURPOSE_PLACEHOLDER = "{{PURPOSE}}";
759
1098
  var NO_PURPOSE_TEXT = "(no purpose set)";
760
- var defaultDeps = { readFile: readFile3, writeFile: writeFile3 };
1099
+ var defaultDeps = { readFile: readFile4, writeFile: writeFile4 };
761
1100
  async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = defaultDeps) {
762
- const vscodeTemplatePath = join3(workspaceRoot, ".vscode", STATUS_BAR_TEMPLATE_JSON);
1101
+ const vscodeTemplatePath = join4(workspaceRoot, ".vscode", STATUS_BAR_TEMPLATE_JSON);
763
1102
  let templateContent = null;
764
1103
  try {
765
1104
  templateContent = await deps.readFile(vscodeTemplatePath, "utf-8");
@@ -768,7 +1107,7 @@ async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = d
768
1107
  throw err;
769
1108
  }
770
1109
  }
771
- const agentEnvTemplatePath = join3(agentEnvDir, STATUS_BAR_TEMPLATE_JSON);
1110
+ const agentEnvTemplatePath = join4(agentEnvDir, STATUS_BAR_TEMPLATE_JSON);
772
1111
  if (templateContent === null) {
773
1112
  try {
774
1113
  templateContent = await deps.readFile(agentEnvTemplatePath, "utf-8");
@@ -783,21 +1122,21 @@ async function regenerateStatusBar(workspaceRoot, agentEnvDir, purpose, deps = d
783
1122
  new Error(
784
1123
  `No status bar template found. Checked ${vscodeTemplatePath} and ${agentEnvTemplatePath}. Create a template manually or use \`agent-env init-template\` when available.`
785
1124
  ),
786
- { code: "TEMPLATE_NOT_FOUND" }
1125
+ { code: TEMPLATE_NOT_FOUND }
787
1126
  );
788
1127
  }
789
1128
  const rawText = purpose ?? NO_PURPOSE_TEXT;
790
1129
  const replacementText = JSON.stringify(rawText).slice(1, -1);
791
1130
  const output = templateContent.replaceAll(PURPOSE_PLACEHOLDER, replacementText);
792
- const outputPath = join3(agentEnvDir, STATUS_BAR_JSON);
1131
+ const outputPath = join4(agentEnvDir, STATUS_BAR_JSON);
793
1132
  await deps.writeFile(outputPath, output, "utf-8");
794
1133
  }
795
1134
 
796
1135
  // src/lib/workspace.ts
797
1136
  import { createHash } from "crypto";
798
- import { mkdir as mkdir3, readdir as readdir2, readFile as readFile4, rm, stat as stat2 } from "fs/promises";
1137
+ import { mkdir as mkdir3, readdir as readdir2, readFile as readFile5, rm, stat as stat2 } from "fs/promises";
799
1138
  import { homedir } from "os";
800
- import { join as join4 } from "path";
1139
+ import { join as join5 } from "path";
801
1140
  var defaultFsDeps2 = { mkdir: mkdir3, readdir: readdir2, stat: stat2, homedir };
802
1141
  var VALID_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
803
1142
  function validateNameSegment(value, label) {
@@ -841,7 +1180,7 @@ function compressSlug(slug, maxLength = MAX_REPO_SLUG_LENGTH) {
841
1180
  return `${prefix}_${hash}_${suffix}`;
842
1181
  }
843
1182
  function getWorkspacesBaseDir(deps = defaultFsDeps2) {
844
- return join4(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
1183
+ return join5(deps.homedir(), AGENT_ENV_DIR, WORKSPACES_DIR);
845
1184
  }
846
1185
  function deriveWorkspaceName(repo, instance) {
847
1186
  validateNameSegment(repo, "repo");
@@ -853,15 +1192,15 @@ function deriveContainerName(workspaceName) {
853
1192
  }
854
1193
  function getWorkspacePath(repo, instance, deps = defaultFsDeps2) {
855
1194
  const name = deriveWorkspaceName(repo, instance);
856
- const root = join4(getWorkspacesBaseDir(deps), name);
857
- const agentEnvDir = join4(root, AGENT_ENV_DIR);
858
- const stateFile = join4(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);
859
1198
  return { root, name, agentEnvDir, stateFile };
860
1199
  }
861
1200
  function getWorkspacePathByName(workspaceName, deps = defaultFsDeps2) {
862
- const root = join4(getWorkspacesBaseDir(deps), workspaceName);
863
- const agentEnvDir = join4(root, AGENT_ENV_DIR);
864
- const stateFile = join4(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);
865
1204
  return { root, name: workspaceName, agentEnvDir, stateFile };
866
1205
  }
867
1206
  async function workspaceExists(repo, instance, deps = defaultFsDeps2) {
@@ -938,7 +1277,7 @@ async function resolveRepo(opts, executor) {
938
1277
  }
939
1278
  var defaultResolveInstanceDeps = {
940
1279
  fsDeps: defaultFsDeps2,
941
- readFile: readFile4
1280
+ readFile: readFile5
942
1281
  };
943
1282
  async function resolveInstance(instanceName, repoSlug, deps = defaultResolveInstanceDeps) {
944
1283
  const workspaces = await scanWorkspaces(deps.fsDeps);
@@ -1000,10 +1339,21 @@ var MAX_PURPOSE_LENGTH = 200;
1000
1339
  function createPurposeDefaultDeps() {
1001
1340
  return {
1002
1341
  workspaceFsDeps: { mkdir: mkdir4, readdir: readdir3, stat: stat3, homedir: homedir2 },
1003
- stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1004
- statusBarDeps: { readFile: readFile5, writeFile: writeFile4 }
1342
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir4, appendFile: appendFile2 },
1343
+ statusBarDeps: { readFile: readFile6, writeFile: writeFile5 }
1005
1344
  };
1006
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
+ }
1007
1357
  function validatePurposeLength(value) {
1008
1358
  if (value.length > MAX_PURPOSE_LENGTH) {
1009
1359
  return {
@@ -1047,28 +1397,19 @@ async function setPurpose(instanceName, value, deps, repoSlug) {
1047
1397
  purpose: newPurpose
1048
1398
  };
1049
1399
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1050
- try {
1051
- await regenerateStatusBar(wsPath.root, wsPath.agentEnvDir, newPurpose, deps.statusBarDeps);
1052
- } catch (err) {
1053
- if (err.code === "TEMPLATE_NOT_FOUND") {
1054
- return {
1055
- ok: false,
1056
- error: {
1057
- code: "TEMPLATE_NOT_FOUND",
1058
- message: err.message,
1059
- suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1060
- }
1061
- };
1062
- }
1063
- throw err;
1064
- }
1065
- 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 };
1066
1407
  }
1067
1408
  function createContainerPurposeDefaultDeps() {
1068
1409
  return {
1069
- stateFsDeps: { readFile: readFile5, writeFile: writeFile4, rename: rename2, mkdir: mkdir4, appendFile: appendFile2 },
1410
+ stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir4, appendFile: appendFile2 },
1070
1411
  containerEnvDeps: { getEnv: (key) => process.env[key] },
1071
- statusBarDeps: { readFile: readFile5, writeFile: writeFile4 },
1412
+ statusBarDeps: { readFile: readFile6, writeFile: writeFile5 },
1072
1413
  statePath: CONTAINER_STATE_PATH,
1073
1414
  agentEnvDir: CONTAINER_AGENT_ENV_DIR,
1074
1415
  workspaceRoot: process.cwd()
@@ -1087,7 +1428,7 @@ async function readContainerState(deps) {
1087
1428
  }
1088
1429
  };
1089
1430
  }
1090
- return { ok: true, state: parsed };
1431
+ return { ok: true, state: migrateConfigSource(parsed) };
1091
1432
  } catch (err) {
1092
1433
  if (err.code === "ENOENT") {
1093
1434
  return {
@@ -1134,22 +1475,13 @@ async function setContainerPurpose(value, deps) {
1134
1475
  stateFile: deps.statePath
1135
1476
  };
1136
1477
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
1137
- try {
1138
- await regenerateStatusBar(deps.workspaceRoot, deps.agentEnvDir, newPurpose, deps.statusBarDeps);
1139
- } catch (err) {
1140
- if (err.code === "TEMPLATE_NOT_FOUND") {
1141
- return {
1142
- ok: false,
1143
- error: {
1144
- code: "TEMPLATE_NOT_FOUND",
1145
- message: err.message,
1146
- suggestion: "Create a status bar template at .vscode/statusBar.template.json or .agent-env/statusBar.template.json."
1147
- }
1148
- };
1149
- }
1150
- throw err;
1151
- }
1152
- 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 };
1153
1485
  }
1154
1486
 
1155
1487
  // src/lib/create-instance.ts
@@ -1245,8 +1577,9 @@ function createDefaultDeps() {
1245
1577
  executor,
1246
1578
  container: createContainerLifecycle(executor),
1247
1579
  workspaceFsDeps: { mkdir: mkdir5, readdir: readdir4, stat: stat4, homedir: homedir3 },
1248
- stateFsDeps: { readFile: readFile6, writeFile: writeFile5, rename: rename3, mkdir: mkdir5, appendFile: appendFile3 },
1249
- devcontainerFsDeps: { cp: cp2, mkdir: mkdir5, readFile: readFile6, stat: stat4, writeFile: writeFile5 },
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 },
1250
1583
  rm: rm2,
1251
1584
  logger: {
1252
1585
  warn: (msg) => console.warn(msg),
@@ -1254,68 +1587,34 @@ function createDefaultDeps() {
1254
1587
  }
1255
1588
  };
1256
1589
  }
1257
- async function resolveConfigChoice(hasConfig, baselineChoice, askUser) {
1258
- if (!hasConfig) {
1259
- return "baseline";
1260
- }
1261
- if (baselineChoice === "force-baseline") {
1262
- return "baseline";
1263
- }
1264
- if (baselineChoice === "force-repo-config") {
1265
- return "repo";
1266
- }
1267
- if (askUser) {
1268
- return askUser();
1269
- }
1270
- return "repo";
1271
- }
1272
- function deriveBaselineChoice(baseline) {
1273
- if (baseline === true) return "force-baseline";
1274
- if (baseline === false) return "force-repo-config";
1275
- return "ask-user";
1276
- }
1277
- async function setupDevcontainerConfig(wsPath, containerName, repoName, purposeText, deps, baselineChoice = "ask-user", askUser) {
1278
- const hasConfig = await hasDevcontainerConfig(wsPath.root, deps.devcontainerFsDeps);
1279
- const choice = await resolveConfigChoice(hasConfig, baselineChoice, askUser);
1280
- if (choice === "repo") {
1281
- return { ok: true, configSource: "repo" };
1282
- }
1590
+ async function setupMergedConfig(wsPath, containerName, repoName, purposeText, deps) {
1283
1591
  try {
1284
- await copyBaselineConfig(wsPath.root, deps.devcontainerFsDeps);
1285
- await copyStatusBarTemplate(wsPath.root, deps.devcontainerFsDeps);
1286
- } catch (err) {
1287
- await safeRollback(wsPath.root, deps.rm, deps.logger);
1288
- return {
1289
- ok: false,
1290
- error: {
1291
- code: "CONTAINER_ERROR",
1292
- message: `Failed to copy baseline devcontainer config: ${err instanceof Error ? err.message : String(err)}`
1293
- }
1294
- };
1295
- }
1296
- try {
1297
- await applyBaselinePatches(
1298
- wsPath.root,
1592
+ const defaults = await loadManagedDefaults(deps.mergeDeps);
1593
+ const managed = buildManagedConfig(defaults, {
1594
+ instanceName: wsPath.name,
1299
1595
  containerName,
1300
- {
1301
- AGENT_ENV_INSTANCE: wsPath.name,
1302
- AGENT_ENV_REPO: repoName,
1303
- AGENT_ENV_PURPOSE: purposeText
1304
- },
1305
- deps.devcontainerFsDeps,
1306
- AGENT_ENV_DIR
1307
- );
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 };
1308
1608
  } catch (err) {
1309
1609
  await safeRollback(wsPath.root, deps.rm, deps.logger);
1310
1610
  return {
1311
1611
  ok: false,
1312
1612
  error: {
1313
1613
  code: "CONTAINER_ERROR",
1314
- message: `Failed to patch baseline devcontainer.json: ${err instanceof Error ? err.message : String(err)}`
1614
+ message: `Failed to set up devcontainer config: ${err instanceof Error ? err.message : String(err)}`
1315
1615
  }
1316
1616
  };
1317
1617
  }
1318
- return { ok: true, configSource: "baseline" };
1319
1618
  }
1320
1619
  async function cloneAndPrepareWorkspace(repoUrl, wsPath, deps) {
1321
1620
  try {
@@ -1405,20 +1704,11 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1405
1704
  }
1406
1705
  const prepResult = await cloneAndPrepareWorkspace(repoUrl, wsPath, deps);
1407
1706
  if (!prepResult.ok) return prepResult;
1408
- const baselineChoice = deriveBaselineChoice(options?.baseline);
1409
- const configResult = await setupDevcontainerConfig(
1410
- wsPath,
1411
- containerName,
1412
- repoName,
1413
- purposeText,
1414
- deps,
1415
- baselineChoice,
1416
- options?.askUser
1417
- );
1707
+ const configResult = await setupMergedConfig(wsPath, containerName, repoName, purposeText, deps);
1418
1708
  if (!configResult.ok) {
1419
1709
  return configResult;
1420
1710
  }
1421
- const { configSource } = configResult;
1711
+ const { repoConfigDetected } = configResult;
1422
1712
  const existingContainer = await deps.container.findContainerByWorkspaceLabel(wsPath.root);
1423
1713
  if (existingContainer) {
1424
1714
  await safeRollback(wsPath.root, deps.rm, deps.logger);
@@ -1431,13 +1721,13 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1431
1721
  }
1432
1722
  };
1433
1723
  }
1434
- const baselineConfigPath = configSource === "baseline" ? join5(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1724
+ const configPath = join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
1435
1725
  const containerResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1436
1726
  remoteEnv: {
1437
1727
  AGENT_INSTANCE: wsPath.name,
1438
1728
  AGENT_ENV_PURPOSE: purposeText
1439
1729
  },
1440
- configPath: baselineConfigPath
1730
+ configPath
1441
1731
  });
1442
1732
  if (!containerResult.ok) {
1443
1733
  return rollbackContainerFailure(containerName, wsPath, containerResult, deps);
@@ -1449,7 +1739,7 @@ async function createInstance(instanceName, repoUrl, deps, options) {
1449
1739
  );
1450
1740
  const state = createInitialState(instanceName, repoName, repoUrl, {
1451
1741
  containerName: actualContainerName,
1452
- configSource,
1742
+ repoConfigDetected,
1453
1743
  purpose: purposeState
1454
1744
  });
1455
1745
  await writeStateAtomic(wsPath, state, deps.stateFsDeps);
@@ -1527,7 +1817,7 @@ function createAttachDefaultDeps() {
1527
1817
  executor,
1528
1818
  container: createContainerLifecycle(executor),
1529
1819
  workspaceFsDeps: { mkdir: mkdir6, readdir: readdir5, stat: stat5, homedir: homedir4 },
1530
- stateFsDeps: { readFile: readFile7, writeFile: writeFile6, rename: rename4, mkdir: mkdir6, appendFile: appendFile4 }
1820
+ stateFsDeps: { readFile: readFile8, writeFile: writeFile7, rename: rename5, mkdir: mkdir6, appendFile: appendFile4 }
1531
1821
  };
1532
1822
  }
1533
1823
  async function attachInstance(instanceName, deps, onContainerStarting, onAttaching, repoSlug) {
@@ -1564,11 +1854,10 @@ async function attachInstance(instanceName, deps, onContainerStarting, onAttachi
1564
1854
  }
1565
1855
  if (statusResult.status === "stopped" || statusResult.status === "not-found") {
1566
1856
  onContainerStarting?.();
1567
- const configSource = state.configSource ?? "baseline";
1568
- const baselineConfigPath = configSource === "baseline" ? join6(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
1857
+ const configPath = join7(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
1569
1858
  const startResult = await deps.container.devcontainerUp(wsPath.root, containerName, {
1570
1859
  remoteEnv: { AGENT_INSTANCE: wsPath.name },
1571
- configPath: baselineConfigPath
1860
+ configPath
1572
1861
  });
1573
1862
  if (!startResult.ok) {
1574
1863
  return {
@@ -1639,8 +1928,18 @@ var attachCommand = new Command("attach").description("Attach to an instance's t
1639
1928
  import { Command as Command2 } from "commander";
1640
1929
 
1641
1930
  // src/lib/completion.ts
1642
- var COMMANDS = ["create", "list", "ps", "attach", "remove", "purpose", "completion"];
1643
- var INSTANCE_COMMANDS = ["attach", "purpose"];
1931
+ var COMMANDS = [
1932
+ "create",
1933
+ "list",
1934
+ "ps",
1935
+ "attach",
1936
+ "rebuild",
1937
+ "remove",
1938
+ "repos",
1939
+ "purpose",
1940
+ "tmux-status",
1941
+ "completion"
1942
+ ];
1644
1943
  function generateCompletionScript(shell) {
1645
1944
  switch (shell) {
1646
1945
  case "bash":
@@ -1671,15 +1970,35 @@ function getInstallInstructions() {
1671
1970
  }
1672
1971
  function generateBashCompletion() {
1673
1972
  const commandList = COMMANDS.join(" ");
1674
- const instanceCommandList = INSTANCE_COMMANDS.join("|");
1675
1973
  return `#!/usr/bin/env bash
1676
1974
  # agent-env bash completion script
1677
1975
  # Install: eval "$(agent-env completion bash)"
1678
1976
 
1977
+ _agent_env_repos() {
1978
+ local ws_dir=~/.agent-env/workspaces
1979
+ local entry base repo
1980
+ if [[ -d "\${ws_dir}" ]]; then
1981
+ for entry in "\${ws_dir}"/*/; do
1982
+ [[ -d "\${entry}" ]] || continue
1983
+ base="\${entry%/}"
1984
+ base="\${base##*/}"
1985
+ repo="\${base%-*}"
1986
+ [[ "\${repo}" != "\${base}" ]] && echo "\${repo}"
1987
+ done | sort -u
1988
+ fi
1989
+ }
1990
+
1679
1991
  _agent_env_instances() {
1680
1992
  local ws_dir=~/.agent-env/workspaces
1993
+ local entry base instance
1681
1994
  if [[ -d "\${ws_dir}" ]]; then
1682
- ls "\${ws_dir}" 2>/dev/null
1995
+ for entry in "\${ws_dir}"/*/; do
1996
+ [[ -d "\${entry}" ]] || continue
1997
+ base="\${entry%/}"
1998
+ base="\${base##*/}"
1999
+ instance="\${base##*-}"
2000
+ [[ "\${instance}" != "\${base}" ]] && echo "\${instance}"
2001
+ done | sort -u
1683
2002
  fi
1684
2003
  }
1685
2004
 
@@ -1697,28 +2016,48 @@ _agent_env_completions() {
1697
2016
 
1698
2017
  # Complete based on command
1699
2018
  case "\${prev}" in
1700
- ${instanceCommandList})
1701
- COMPREPLY=($(compgen -W "$(_agent_env_instances)" -- "\${cur}"))
2019
+ attach|purpose)
2020
+ local instances
2021
+ instances="$(_agent_env_instances)"
2022
+ COMPREPLY=($(compgen -W "--repo \${instances}" -- "\${cur}"))
1702
2023
  return 0
1703
2024
  ;;
1704
2025
  create)
1705
- COMPREPLY=($(compgen -W "--repo --attach" -- "\${cur}"))
2026
+ COMPREPLY=($(compgen -W "--repo --purpose --attach" -- "\${cur}"))
1706
2027
  return 0
1707
2028
  ;;
1708
2029
  list|ps)
1709
- COMPREPLY=($(compgen -W "--json" -- "\${cur}"))
2030
+ COMPREPLY=($(compgen -W "--json --repo" -- "\${cur}"))
2031
+ return 0
2032
+ ;;
2033
+ rebuild)
2034
+ local instances
2035
+ instances="$(_agent_env_instances)"
2036
+ COMPREPLY=($(compgen -W "--force --yes --no-pull --use-cache --repo \${instances}" -- "\${cur}"))
1710
2037
  return 0
1711
2038
  ;;
1712
2039
  remove)
1713
2040
  local instances
1714
2041
  instances="$(_agent_env_instances)"
1715
- COMPREPLY=($(compgen -W "--force \${instances}" -- "\${cur}"))
2042
+ COMPREPLY=($(compgen -W "--force --repo \${instances}" -- "\${cur}"))
2043
+ return 0
2044
+ ;;
2045
+ repos)
2046
+ COMPREPLY=($(compgen -W "--json" -- "\${cur}"))
2047
+ return 0
2048
+ ;;
2049
+ tmux-status)
2050
+ # no arguments or options
1716
2051
  return 0
1717
2052
  ;;
1718
2053
  completion)
1719
2054
  COMPREPLY=($(compgen -W "bash zsh" -- "\${cur}"))
1720
2055
  return 0
1721
2056
  ;;
2057
+ --repo)
2058
+ COMPREPLY=($(compgen -W "$(_agent_env_repos)" -- "\${cur}"))
2059
+ return 0
2060
+ ;;
1722
2061
  esac
1723
2062
 
1724
2063
  return 0
@@ -1732,20 +2071,48 @@ function generateZshCompletion() {
1732
2071
  "list:List all instances",
1733
2072
  "ps:List all instances (alias)",
1734
2073
  "attach:Attach to an instance tmux session",
2074
+ "rebuild:Rebuild an instance container",
1735
2075
  "remove:Remove an instance",
2076
+ "repos:List tracked repositories",
1736
2077
  "purpose:Get or set instance purpose",
2078
+ "tmux-status:Show tmux status bar info",
1737
2079
  "completion:Generate shell completion script"
1738
2080
  ];
1739
2081
  return `#compdef agent-env
1740
2082
  # agent-env zsh completion script
1741
2083
  # Install: eval "$(agent-env completion zsh)"
1742
2084
 
2085
+ _agent_env_repos() {
2086
+ local ws_dir=~/.agent-env/workspaces
2087
+ local -a repos
2088
+ local entry base repo
2089
+ if [[ -d "\${ws_dir}" ]]; then
2090
+ for entry in "\${ws_dir}"/*/; do
2091
+ [[ -d "\${entry}" ]] || continue
2092
+ base="\${entry%/}"
2093
+ base="\${base##*/}"
2094
+ repo="\${base%-*}"
2095
+ [[ "\${repo}" != "\${base}" ]] && repos+=("\${repo}")
2096
+ done
2097
+ fi
2098
+ repos=(\${(u)repos})
2099
+ _describe 'repo' repos
2100
+ }
2101
+
1743
2102
  _agent_env_instances() {
1744
2103
  local ws_dir=~/.agent-env/workspaces
1745
2104
  local -a instances
2105
+ local entry base instance
1746
2106
  if [[ -d "\${ws_dir}" ]]; then
1747
- instances=(\${(f)"$(ls "\${ws_dir}" 2>/dev/null)"})
2107
+ for entry in "\${ws_dir}"/*/; do
2108
+ [[ -d "\${entry}" ]] || continue
2109
+ base="\${entry%/}"
2110
+ base="\${base##*/}"
2111
+ instance="\${base##*-}"
2112
+ [[ "\${instance}" != "\${base}" ]] && instances+=("\${instance}")
2113
+ done
1748
2114
  fi
2115
+ instances=(\${(u)instances})
1749
2116
  _describe 'instance' instances
1750
2117
  }
1751
2118
 
@@ -1768,22 +2135,42 @@ ${commandDescriptions.map((desc) => ` '${desc}'`).join("\n")}
1768
2135
  args)
1769
2136
  case $words[1] in
1770
2137
  attach|purpose)
1771
- _agent_env_instances
2138
+ _arguments \\
2139
+ '--repo[Repo slug to scope lookup]:slug:_agent_env_repos' \\
2140
+ '1:instance:_agent_env_instances'
1772
2141
  ;;
1773
2142
  create)
1774
2143
  _arguments \\
1775
2144
  '--repo[Repository URL]:url:' \\
2145
+ '--purpose[Set instance purpose]:text:' \\
1776
2146
  '--attach[Attach after creation]'
1777
2147
  ;;
1778
2148
  list|ps)
1779
2149
  _arguments \\
1780
- '--json[Output as JSON]'
2150
+ '--json[Output as JSON]' \\
2151
+ '--repo[Filter by repo slug]:slug:_agent_env_repos'
2152
+ ;;
2153
+ rebuild)
2154
+ _arguments \\
2155
+ '--force[Rebuild running container]' \\
2156
+ '--yes[Skip confirmation prompt]' \\
2157
+ '--no-pull[Skip pulling fresh images]' \\
2158
+ '--use-cache[Allow Docker layer cache]' \\
2159
+ '--repo[Repo slug to scope lookup]:slug:_agent_env_repos' \\
2160
+ '1:instance:_agent_env_instances'
1781
2161
  ;;
1782
2162
  remove)
1783
2163
  _arguments \\
1784
2164
  '--force[Force removal]' \\
2165
+ '--repo[Repo slug to scope lookup]:slug:_agent_env_repos' \\
1785
2166
  '1:instance:_agent_env_instances'
1786
2167
  ;;
2168
+ repos)
2169
+ _arguments \\
2170
+ '--json[Output as JSON]'
2171
+ ;;
2172
+ tmux-status)
2173
+ ;;
1787
2174
  completion)
1788
2175
  _describe 'shell' '(bash zsh)'
1789
2176
  ;;
@@ -1792,7 +2179,7 @@ ${commandDescriptions.map((desc) => ` '${desc}'`).join("\n")}
1792
2179
  esac
1793
2180
  }
1794
2181
 
1795
- _agent_env`;
2182
+ compdef _agent_env agent-env`;
1796
2183
  }
1797
2184
 
1798
2185
  // src/commands/completion.ts
@@ -1814,7 +2201,6 @@ ${getInstallInstructions()}`).argument("<shell>", "Shell type (bash or zsh)").ac
1814
2201
 
1815
2202
  // src/commands/create.ts
1816
2203
  import { Command as Command3 } from "commander";
1817
- import { createInterface } from "readline";
1818
2204
 
1819
2205
  // src/lib/list-repos.ts
1820
2206
  async function listRepos(deps) {
@@ -1894,47 +2280,26 @@ async function resolveRepoArg(repoArg, deps) {
1894
2280
  }
1895
2281
 
1896
2282
  // src/commands/create.ts
1897
- function createBaselinePrompt() {
1898
- return async () => {
1899
- if (!process.stdin.isTTY) {
1900
- return "repo";
1901
- }
1902
- const rl = createInterface({ input: process.stdin, output: process.stdout });
1903
- return new Promise((resolve2) => {
1904
- console.log();
1905
- console.log("This repo has a .devcontainer/ config.");
1906
- console.log(" [1] Use repo config (default)");
1907
- console.log(" [2] Use agent-env baseline");
1908
- rl.question("Choose [1/2]: ", (answer) => {
1909
- rl.close();
1910
- resolve2(answer.trim() === "2" ? "baseline" : "repo");
1911
- });
1912
- });
1913
- };
1914
- }
1915
- var createCommand = new Command3("create").description("Create a new isolated development environment").argument("<name>", "Name for the new instance").option("--repo <url|slug>", 'Git repo URL, registered slug, or "." for current directory').option("--purpose <text>", "Set the instance purpose/label at creation time").option("--attach", "Attach immediately after creation").option("--baseline", "Force agent-env baseline config (ignore repo .devcontainer/)").option("--no-baseline", "Force repo config (skip baseline prompt)").action(async (name, options) => {
1916
- if (!options.repo) {
2283
+ 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) => {
2284
+ if (options.baseline !== void 0) {
1917
2285
  console.error(
1918
2286
  formatError(
1919
2287
  createError(
1920
- "MISSING_OPTION",
1921
- "The --repo flag is required.",
1922
- "Usage: agent-env create <name> --repo <url|slug>"
2288
+ "REMOVED_OPTION",
2289
+ "The --baseline / --no-baseline flags have been removed.",
2290
+ "Agent-env now always merges managed config with repo config. No flag needed."
1923
2291
  )
1924
2292
  )
1925
2293
  );
1926
2294
  process.exit(1);
1927
2295
  }
1928
- const argv = process.argv;
1929
- const hasBaselineFlag = argv.includes("--baseline");
1930
- const hasNoBaselineFlag = argv.includes("--no-baseline");
1931
- if (hasBaselineFlag && hasNoBaselineFlag) {
2296
+ if (!options.repo) {
1932
2297
  console.error(
1933
2298
  formatError(
1934
2299
  createError(
1935
- "INVALID_OPTIONS",
1936
- "Cannot specify both --baseline and --no-baseline",
1937
- "Use --baseline to force agent-env baseline, or --no-baseline to use repo config."
2300
+ "MISSING_OPTION",
2301
+ "The --repo flag is required.",
2302
+ "Usage: agent-env create <name> --repo <url|slug>"
1938
2303
  )
1939
2304
  )
1940
2305
  );
@@ -1959,11 +2324,8 @@ var createCommand = new Command3("create").description("Create a new isolated de
1959
2324
  }
1960
2325
  const repoUrl = resolved.url;
1961
2326
  console.log(`Creating instance '${name}' from ${repoUrl}...`);
1962
- const baselineOption = hasBaselineFlag ? true : hasNoBaselineFlag ? false : void 0;
1963
2327
  const result = await createInstance(name, repoUrl, deps, {
1964
- purpose: options.purpose,
1965
- baseline: baselineOption,
1966
- askUser: createBaselinePrompt()
2328
+ purpose: options.purpose
1967
2329
  });
1968
2330
  if (!result.ok) {
1969
2331
  const { code, message, suggestion } = result.error;
@@ -2459,101 +2821,83 @@ function handleSetResult(result) {
2459
2821
  } else {
2460
2822
  console.log("Purpose updated");
2461
2823
  }
2824
+ if (result.warning) {
2825
+ console.warn(`\x1B[33m\u26A0\x1B[0m ${result.warning}`);
2826
+ }
2462
2827
  }
2463
2828
 
2464
2829
  // src/commands/rebuild.ts
2465
2830
  import chalk from "chalk";
2466
2831
  import { Command as Command6 } from "commander";
2467
- import { createInterface as createInterface2 } from "readline";
2832
+ import { createInterface } from "readline";
2468
2833
 
2469
2834
  // src/lib/rebuild-instance.ts
2470
2835
  import {
2836
+ access as access4,
2471
2837
  cp as cp3,
2472
2838
  mkdir as mkdir7,
2473
2839
  readdir as readdir6,
2474
- readFile as readFile8,
2475
- rename as rename5,
2840
+ readFile as readFile9,
2841
+ rename as rename6,
2476
2842
  rm as rm3,
2477
2843
  stat as stat6,
2478
- writeFile as writeFile7,
2844
+ writeFile as writeFile8,
2479
2845
  appendFile as appendFile5
2480
2846
  } from "fs/promises";
2481
2847
  import { homedir as homedir5 } from "os";
2482
- import { join as join7 } from "path";
2848
+ import { join as join8 } from "path";
2483
2849
  function createRebuildDefaultDeps() {
2484
2850
  const executor = createExecutor();
2485
2851
  return {
2486
2852
  executor,
2487
2853
  container: createContainerLifecycle(executor),
2488
2854
  workspaceFsDeps: { mkdir: mkdir7, readdir: readdir6, stat: stat6, homedir: homedir5 },
2489
- stateFsDeps: { readFile: readFile8, writeFile: writeFile7, rename: rename5, mkdir: mkdir7, appendFile: appendFile5 },
2490
- devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile8, stat: stat6, writeFile: writeFile7 },
2855
+ stateFsDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, mkdir: mkdir7, appendFile: appendFile5 },
2856
+ devcontainerFsDeps: { cp: cp3, mkdir: mkdir7, readdir: readdir6, readFile: readFile9, stat: stat6, writeFile: writeFile8 },
2857
+ mergeDeps: { readFile: readFile9, writeFile: writeFile8, rename: rename6, access: access4 },
2491
2858
  rm: rm3,
2492
- rename: rename5,
2859
+ rename: rename6,
2493
2860
  logger: { warn: (msg) => console.warn(msg), info: (msg) => console.info(msg) }
2494
2861
  };
2495
2862
  }
2496
- async function refreshConfig(wsRoot, containerName, configSource, envVars, deps) {
2497
- if (configSource === "baseline") {
2498
- const agentEnvDir = join7(wsRoot, AGENT_ENV_DIR);
2499
- try {
2500
- await deps.devcontainerFsDeps.mkdir(agentEnvDir, { recursive: true });
2501
- await deps.devcontainerFsDeps.cp(getBaselineConfigPath(), agentEnvDir, {
2502
- recursive: true
2503
- });
2504
- const templatePath = join7(agentEnvDir, "statusBar.template.json");
2505
- try {
2506
- await deps.devcontainerFsDeps.stat(templatePath);
2507
- } catch (err) {
2508
- if (err.code !== "ENOENT") throw err;
2509
- await copyStatusBarTemplate(wsRoot, deps.devcontainerFsDeps);
2510
- }
2511
- await applyBaselinePatches(
2512
- wsRoot,
2513
- containerName,
2514
- envVars,
2515
- deps.devcontainerFsDeps,
2516
- AGENT_ENV_DIR
2517
- );
2518
- } catch (err) {
2863
+ async function refreshMergedConfig(wsRoot, containerName, wsName, repoSlug, purpose, repoConfigExpected, deps) {
2864
+ try {
2865
+ const defaults = await loadManagedDefaults(deps.mergeDeps);
2866
+ const managed = buildManagedConfig(defaults, {
2867
+ instanceName: wsName,
2868
+ containerName,
2869
+ repoSlug,
2870
+ purpose
2871
+ });
2872
+ const repoConfig = await readRepoConfig(wsRoot, deps.mergeDeps, deps.logger);
2873
+ if (repoConfigExpected && !repoConfig) {
2519
2874
  return {
2520
2875
  ok: false,
2521
2876
  error: {
2522
- code: "CONFIG_REFRESH_FAILED",
2523
- message: `Failed to refresh baseline config: ${err instanceof Error ? err.message : String(err)}`,
2524
- suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
2877
+ code: "REPO_CONFIG_MISSING",
2878
+ message: `Repo devcontainer config was present at creation but is now missing from ${wsRoot}`,
2879
+ suggestion: "Restore the repo config, or recreate the instance with `agent-env create` to generate a managed-only config."
2525
2880
  }
2526
2881
  };
2527
2882
  }
2528
- } else {
2529
- const configExists = await hasDevcontainerConfig(wsRoot, deps.devcontainerFsDeps);
2530
- if (!configExists) {
2531
- return {
2532
- ok: false,
2533
- error: {
2534
- code: "CONFIG_MISSING",
2535
- message: "Repo-provided devcontainer config is missing.",
2536
- suggestion: "Re-clone the repository or provide a devcontainer config manually."
2537
- }
2538
- };
2883
+ if (repoConfig) {
2884
+ validateRepoConfig(repoConfig, deps.logger);
2539
2885
  }
2540
- const devcontainerDir = join7(wsRoot, ".devcontainer");
2541
- const dirExists = await deps.devcontainerFsDeps.stat(devcontainerDir).catch(() => null);
2542
- if (dirExists) {
2543
- const jsonExists = await deps.devcontainerFsDeps.stat(join7(devcontainerDir, "devcontainer.json")).catch(() => null);
2544
- if (!jsonExists) {
2545
- return {
2546
- ok: false,
2547
- error: {
2548
- code: "CONFIG_CORRUPT",
2549
- message: "Repo-provided devcontainer config is incomplete (missing devcontainer.json).",
2550
- suggestion: "Ensure .devcontainer/devcontainer.json exists."
2551
- }
2552
- };
2886
+ const merged = mergeDevcontainerConfigs(managed, repoConfig);
2887
+ await copyManagedAssets(wsRoot, deps.devcontainerFsDeps);
2888
+ const configPath = join8(wsRoot, AGENT_ENV_DIR, "devcontainer.json");
2889
+ await writeGeneratedConfig(configPath, merged, deps.mergeDeps);
2890
+ return { ok: true, repoConfigDetected: repoConfig !== void 0 };
2891
+ } catch (err) {
2892
+ return {
2893
+ ok: false,
2894
+ error: {
2895
+ code: "CONFIG_REFRESH_FAILED",
2896
+ message: `Failed to refresh config: ${err instanceof Error ? err.message : String(err)}`,
2897
+ suggestion: "The existing container is still intact. Check that the baseline config files exist in the package."
2553
2898
  }
2554
- }
2899
+ };
2555
2900
  }
2556
- return { ok: true };
2557
2901
  }
2558
2902
  async function lookupWorkspace(instanceName, deps, repoSlug) {
2559
2903
  const lookup = await resolveInstance(instanceName, repoSlug, {
@@ -2640,12 +2984,12 @@ async function teardownContainer(containerName, container, statusResult) {
2640
2984
  }
2641
2985
  return { ok: true };
2642
2986
  }
2643
- async function startAndDiscoverContainer(wsPath, containerName, configSource, purpose, buildNoCache, container) {
2644
- const baselineConfigPath = configSource === "baseline" ? join7(wsPath.root, AGENT_ENV_DIR, "devcontainer.json") : void 0;
2987
+ async function startAndDiscoverContainer(wsPath, containerName, purpose, buildNoCache, container) {
2988
+ const configPath = join8(wsPath.root, AGENT_ENV_DIR, "devcontainer.json");
2645
2989
  const containerResult = await container.devcontainerUp(wsPath.root, containerName, {
2646
2990
  buildNoCache,
2647
2991
  remoteEnv: { AGENT_INSTANCE: wsPath.name, AGENT_ENV_PURPOSE: purpose },
2648
- configPath: baselineConfigPath
2992
+ configPath
2649
2993
  });
2650
2994
  if (!containerResult.ok) {
2651
2995
  return { ok: false, error: containerResult.error };
@@ -2660,12 +3004,7 @@ async function startAndDiscoverContainer(wsPath, containerName, configSource, pu
2660
3004
  return { ok: true, containerName: actualName };
2661
3005
  }
2662
3006
  async function rebuildInstance(instanceName, deps, options, repoSlug) {
2663
- const {
2664
- force = false,
2665
- configSource: overrideConfigSource,
2666
- pull = true,
2667
- noCache = true
2668
- } = options ?? {};
3007
+ const { force = false, pull = true, noCache = true } = options ?? {};
2669
3008
  const wsLookup = await lookupWorkspace(instanceName, deps, repoSlug);
2670
3009
  if (!wsLookup.ok) {
2671
3010
  return { ok: false, error: wsLookup.error };
@@ -2683,23 +3022,15 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2683
3022
  }
2684
3023
  };
2685
3024
  }
2686
- const configSource = overrideConfigSource ?? state.configSource;
2687
- if (!configSource) {
2688
- return {
2689
- ok: false,
2690
- error: {
2691
- code: "CONFIG_SOURCE_UNKNOWN",
2692
- message: `Instance '${instanceName}' was created before config tracking was added.`,
2693
- suggestion: 'Set configSource manually in .agent-env/state.json ("baseline" or "repo"), then retry.'
2694
- }
2695
- };
2696
- }
2697
- const envVars = {
2698
- AGENT_ENV_INSTANCE: wsPath.name,
2699
- AGENT_ENV_REPO: state.repoSlug ?? "",
2700
- AGENT_ENV_PURPOSE: state.purpose ?? ""
2701
- };
2702
- const configResult = await refreshConfig(wsPath.root, containerName, configSource, envVars, deps);
3025
+ const configResult = await refreshMergedConfig(
3026
+ wsPath.root,
3027
+ containerName,
3028
+ wsPath.name,
3029
+ state.repoSlug ?? "",
3030
+ state.purpose ?? "",
3031
+ state.repoConfigDetected,
3032
+ deps
3033
+ );
2703
3034
  if (!configResult.ok) {
2704
3035
  return { ok: false, error: configResult.error };
2705
3036
  }
@@ -2728,7 +3059,6 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2728
3059
  const startResult = await startAndDiscoverContainer(
2729
3060
  wsPath,
2730
3061
  containerName,
2731
- configSource,
2732
3062
  state.purpose ?? "",
2733
3063
  noCache && hasDockerfile,
2734
3064
  deps.container
@@ -2739,7 +3069,8 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2739
3069
  const updatedState = {
2740
3070
  ...state,
2741
3071
  containerName: startResult.containerName,
2742
- lastRebuilt: (/* @__PURE__ */ new Date()).toISOString()
3072
+ lastRebuilt: (/* @__PURE__ */ new Date()).toISOString(),
3073
+ repoConfigDetected: configResult.repoConfigDetected
2743
3074
  };
2744
3075
  await writeStateAtomic(wsPath, updatedState, deps.stateFsDeps);
2745
3076
  return {
@@ -2752,7 +3083,7 @@ async function rebuildInstance(instanceName, deps, options, repoSlug) {
2752
3083
  // src/commands/rebuild.ts
2753
3084
  function promptForConfirmation(instanceName) {
2754
3085
  return new Promise((resolve2) => {
2755
- const rl = createInterface2({
3086
+ const rl = createInterface({
2756
3087
  input: process.stdin,
2757
3088
  output: process.stderr
2758
3089
  });
@@ -2818,21 +3149,21 @@ var rebuildCommand = new Command6("rebuild").description("Rebuild an instance by
2818
3149
  // src/commands/remove.ts
2819
3150
  import chalk3 from "chalk";
2820
3151
  import { Command as Command7 } from "commander";
2821
- import { createInterface as createInterface3 } from "readline";
3152
+ import { createInterface as createInterface2 } from "readline";
2822
3153
 
2823
3154
  // src/lib/audit-log.ts
2824
3155
  import { appendFile as appendFile6, mkdir as mkdir8 } from "fs/promises";
2825
3156
  import { homedir as homedir6 } from "os";
2826
- import { join as join8 } from "path";
3157
+ import { join as join9 } from "path";
2827
3158
  function createAuditLogDefaultDeps() {
2828
3159
  return { appendFile: appendFile6, mkdir: mkdir8, homedir: homedir6 };
2829
3160
  }
2830
3161
  function getAuditLogPath(deps) {
2831
- return join8(deps.homedir(), AGENT_ENV_DIR, "audit.log");
3162
+ return join9(deps.homedir(), AGENT_ENV_DIR, "audit.log");
2832
3163
  }
2833
3164
  async function writeAuditLogEntry(entry, deps = createAuditLogDefaultDeps()) {
2834
3165
  const logPath = getAuditLogPath(deps);
2835
- await deps.mkdir(join8(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
3166
+ await deps.mkdir(join9(deps.homedir(), AGENT_ENV_DIR), { recursive: true });
2836
3167
  const line = JSON.stringify(entry) + "\n";
2837
3168
  await deps.appendFile(logPath, line, "utf-8");
2838
3169
  }
@@ -2847,7 +3178,7 @@ function createAuditEntry(instanceName, gitState, confirmationMethod) {
2847
3178
  }
2848
3179
 
2849
3180
  // src/lib/remove-instance.ts
2850
- import { mkdir as mkdir9, readdir as readdir7, readFile as readFile9, rm as rm4, stat as stat7 } from "fs/promises";
3181
+ import { mkdir as mkdir9, readdir as readdir7, readFile as readFile10, rm as rm4, stat as stat7 } from "fs/promises";
2851
3182
  import { homedir as homedir7 } from "os";
2852
3183
  function createRemoveDefaultDeps() {
2853
3184
  const executor = createExecutor();
@@ -2856,7 +3187,7 @@ function createRemoveDefaultDeps() {
2856
3187
  container: createContainerLifecycle(executor),
2857
3188
  gitDetector: createGitStateDetector(executor),
2858
3189
  workspaceFsDeps: { mkdir: mkdir9, readdir: readdir7, stat: stat7, homedir: homedir7 },
2859
- stateFsDeps: { readFile: readFile9 },
3190
+ stateFsDeps: { readFile: readFile10 },
2860
3191
  deleteFsDeps: { rm: rm4 }
2861
3192
  };
2862
3193
  }
@@ -3076,7 +3407,7 @@ function formatSafetyReport(instanceName, blockers, gitState) {
3076
3407
  function promptForConfirmation2(instanceName) {
3077
3408
  return new Promise((resolve2) => {
3078
3409
  let resolved = false;
3079
- const rl = createInterface3({
3410
+ const rl = createInterface2({
3080
3411
  input: process.stdin,
3081
3412
  output: process.stderr
3082
3413
  });
@@ -3250,6 +3581,59 @@ var reposCommand = new Command8("repos").description("List tracked repositories"
3250
3581
  }
3251
3582
  });
3252
3583
 
3584
+ // src/commands/tmux-status.ts
3585
+ import { Command as Command9 } from "commander";
3586
+
3587
+ // src/lib/tmux-status.ts
3588
+ import { readFile as readFile11 } from "fs/promises";
3589
+ var MAX_PURPOSE_DISPLAY_LEN = 40;
3590
+ var defaultDeps2 = { readFile: readFile11 };
3591
+ function formatTmuxStatus(instance, purpose) {
3592
+ if (!instance) return "?";
3593
+ if (!purpose) return instance;
3594
+ if (purpose.length > MAX_PURPOSE_DISPLAY_LEN) {
3595
+ return `${instance} | ${purpose.slice(0, MAX_PURPOSE_DISPLAY_LEN)}\u2026`;
3596
+ }
3597
+ return `${instance} | ${purpose}`;
3598
+ }
3599
+ async function getTmuxStatus(statePath, deps = defaultDeps2) {
3600
+ let content;
3601
+ try {
3602
+ content = await deps.readFile(statePath, "utf-8");
3603
+ } catch {
3604
+ return "?";
3605
+ }
3606
+ let parsed;
3607
+ try {
3608
+ parsed = JSON.parse(content);
3609
+ } catch {
3610
+ return "?";
3611
+ }
3612
+ if (typeof parsed !== "object" || parsed === null) return "?";
3613
+ const obj = parsed;
3614
+ const instance = typeof obj.instance === "string" ? obj.instance : "";
3615
+ const purpose = typeof obj.purpose === "string" ? obj.purpose : null;
3616
+ return formatTmuxStatus(instance, purpose);
3617
+ }
3618
+
3619
+ // src/commands/tmux-status.ts
3620
+ var defaultDeps3 = {
3621
+ isInsideContainer,
3622
+ getTmuxStatus,
3623
+ statePath: CONTAINER_STATE_PATH
3624
+ };
3625
+ function createTmuxStatusCommand(deps = defaultDeps3) {
3626
+ return new Command9("tmux-status").description("Output formatted instance status for tmux status bar (container only)").action(async () => {
3627
+ if (!deps.isInsideContainer()) {
3628
+ console.log("?");
3629
+ return;
3630
+ }
3631
+ const display = await deps.getTmuxStatus(deps.statePath);
3632
+ console.log(display);
3633
+ });
3634
+ }
3635
+ var tmuxStatusCommand = createTmuxStatusCommand();
3636
+
3253
3637
  // src/components/InteractiveMenu.tsx
3254
3638
  import { Select } from "@inkjs/ui";
3255
3639
  import { Box as Box2, Text as Text3 } from "ink";
@@ -3425,7 +3809,7 @@ Purpose for ${name}:`);
3425
3809
  var __dirname = dirname3(fileURLToPath2(import.meta.url));
3426
3810
  var isLinked = existsSync(resolve(__dirname, "..", "..", "..", "pnpm-workspace.yaml"));
3427
3811
  var version = package_default.version + (isLinked ? "+local" : "");
3428
- program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version);
3812
+ program.name("agent-env").description("CLI for creating isolated, AI-ready development environments").version(version).allowExcessArguments(true);
3429
3813
  program.addCommand(createCommand);
3430
3814
  program.addCommand(listCommand);
3431
3815
  program.addCommand(attachCommand);
@@ -3433,8 +3817,20 @@ program.addCommand(rebuildCommand);
3433
3817
  program.addCommand(removeCommand);
3434
3818
  program.addCommand(purposeCommand);
3435
3819
  program.addCommand(reposCommand);
3820
+ program.addCommand(tmuxStatusCommand);
3436
3821
  program.addCommand(completionCommand);
3437
3822
  program.action(async () => {
3823
+ if (program.args.length > 0) {
3824
+ const unknown = program.args[0];
3825
+ const available = program.commands.map((c) => c.name());
3826
+ const matches = available.filter((c) => c.startsWith(unknown));
3827
+ const suggestion = matches.length > 0 ? `Did you mean ${matches.map((m) => `"${m}"`).join(" or ")}?` : `Available commands: ${available.join(", ")}`;
3828
+ console.error(
3829
+ formatError(createError("UNKNOWN_COMMAND", `Unknown command "${unknown}".`, suggestion))
3830
+ );
3831
+ process.exitCode = 1;
3832
+ return;
3833
+ }
3438
3834
  if (!process.stdin.isTTY) {
3439
3835
  program.help();
3440
3836
  return;