@pennixrv/trellis 0.7.1-beta.8 → 0.7.1-beta.9

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 (56) hide show
  1. package/README.md +10 -7
  2. package/dist/cli/index.d.ts.map +1 -1
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/index.js.map +1 -1
  5. package/dist/commands/ablate.d.ts.map +1 -1
  6. package/dist/commands/ablate.js +2 -0
  7. package/dist/commands/ablate.js.map +1 -1
  8. package/dist/commands/backup.d.ts +4 -0
  9. package/dist/commands/backup.d.ts.map +1 -0
  10. package/dist/commands/backup.js +75 -0
  11. package/dist/commands/backup.js.map +1 -0
  12. package/dist/commands/init.d.ts.map +1 -1
  13. package/dist/commands/init.js +675 -672
  14. package/dist/commands/init.js.map +1 -1
  15. package/dist/commands/mem.d.ts.map +1 -1
  16. package/dist/commands/mem.js +49 -7
  17. package/dist/commands/mem.js.map +1 -1
  18. package/dist/commands/uninstall.d.ts.map +1 -1
  19. package/dist/commands/uninstall.js +92 -84
  20. package/dist/commands/uninstall.js.map +1 -1
  21. package/dist/commands/update.d.ts.map +1 -1
  22. package/dist/commands/update.js +587 -606
  23. package/dist/commands/update.js.map +1 -1
  24. package/dist/commands/workflow.d.ts.map +1 -1
  25. package/dist/commands/workflow.js +94 -89
  26. package/dist/commands/workflow.js.map +1 -1
  27. package/dist/configurators/shared.js +2 -2
  28. package/dist/configurators/shared.js.map +1 -1
  29. package/dist/migrations/manifests/0.7.1-beta.9.json +191 -0
  30. package/dist/templates/common/bundled-skills/trellis-decision-space-construction-and-merging/workflow.md +2 -0
  31. package/dist/templates/common/bundled-skills/trellis-goal-exploration-and-requirements/workflow.md +2 -0
  32. package/dist/templates/common/bundled-skills/trellis-session-insight/references/cli-quick-reference.md +2 -1
  33. package/dist/templates/common/bundled-skills/trellis-session-insight/references/triggering-patterns.md +2 -2
  34. package/dist/templates/common/bundled-skills/trellis-solution-design-and-convergence/workflow.md +4 -0
  35. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/mcp-setup.md +4 -2
  36. package/dist/templates/common/bundled-skills/trellis-spec-bootstrap/references/spec-task-planning.md +2 -2
  37. package/dist/templates/common/bundled-skills/trellis-teamwork/SKILL.md +1 -1
  38. package/dist/templates/common/commands/start.md +2 -2
  39. package/dist/templates/common/skills/before-dev.md +1 -4
  40. package/dist/templates/common/skills/break-loop.md +7 -18
  41. package/dist/templates/common/skills/check.md +7 -11
  42. package/dist/templates/common/skills/{brainstorm.md → request-intake.md} +5 -3
  43. package/dist/templates/common/skills/update-spec.md +5 -7
  44. package/dist/utils/ablation-store.d.ts +1 -1
  45. package/dist/utils/ablation-store.d.ts.map +1 -1
  46. package/dist/utils/ablation-store.js +58 -24
  47. package/dist/utils/ablation-store.js.map +1 -1
  48. package/dist/utils/asset-backup.d.ts +138 -0
  49. package/dist/utils/asset-backup.d.ts.map +1 -0
  50. package/dist/utils/asset-backup.js +507 -0
  51. package/dist/utils/asset-backup.js.map +1 -0
  52. package/dist/utils/atomic-write.d.ts +1 -1
  53. package/dist/utils/atomic-write.d.ts.map +1 -1
  54. package/dist/utils/atomic-write.js +6 -3
  55. package/dist/utils/atomic-write.js.map +1 -1
  56. package/package.json +2 -2
@@ -6,6 +6,7 @@ import chalk from "chalk";
6
6
  import figlet from "figlet";
7
7
  import inquirer from "inquirer";
8
8
  import { createWorkflowStructure } from "../configurators/workflow.js";
9
+ import { withAssetMaintenance } from "../utils/asset-backup.js";
9
10
  import { getInitToolChoices, resolveCliFlag, configurePlatform, getConfiguredPlatforms, getPlatformsWithPythonHooks, } from "../configurators/index.js";
10
11
  import { getPythonCommandForPlatform, setResolvedPythonCommand, } from "../configurators/shared.js";
11
12
  import { AI_TOOLS } from "../types/ai-tools.js";
@@ -837,744 +838,746 @@ function writeMonorepoConfig(cwd, packages) {
837
838
  fs.writeFileSync(configPath, content.trimEnd() + "\n" + lines.join("\n") + "\n", "utf-8");
838
839
  }
839
840
  export async function init(options) {
840
- // Refuse to run in $HOME — running here would scoop platform runtime data
841
- // (Claude/Codex/OpenCode session histories etc.) into the trellis hash
842
- // manifest, and a subsequent `trellis uninstall` would wipe it.
843
- if (isCwdHomedir() && !homedirBypassEnabled()) {
844
- console.error(chalk.red(homedirGuardMessage("init")));
845
- process.exit(1);
846
- }
847
- // Deprecated alias: --windsurf → --devin (Windsurf was renamed to Devin).
848
- // Normalize here too so programmatic callers (not just the CLI action) map
849
- // correctly. The CLI action prints the deprecation notice.
850
- if (options.windsurf) {
851
- options.devin = true;
852
- delete options.windsurf;
853
- }
854
- const cwd = process.cwd();
855
- const isFirstInit = !fs.existsSync(path.join(cwd, DIR_NAMES.WORKFLOW));
856
- // Captured here (before createWorkflowStructure + init_developer run) so
857
- // the three-branch dispatch at the bottom can tell "fresh clone joiner"
858
- // (.trellis/ exists, .developer missing) apart from "creator first init".
859
- const hadDeveloperFileAtStart = fs.existsSync(path.join(cwd, DIR_NAMES.WORKFLOW, FILE_NAMES.DEVELOPER));
860
- // Generate ASCII art banner dynamically using FIGlet "Rebel" font
861
- const banner = figlet.textSync("Trellis", { font: "Rebel" });
862
- console.log(chalk.cyan(`\n${banner.trimEnd()}`));
863
- console.log(chalk.gray("\n All-in-one AI framework & toolkit for Claude Code & Cursor\n"));
864
- // Set up proxy before any network calls
865
- const proxyUrl = setupProxy();
866
- if (proxyUrl) {
867
- console.log(chalk.gray(` Using proxy: ${maskProxyUrl(proxyUrl)}\n`));
868
- }
869
- // Set write mode based on options
870
- let writeMode = "ask";
871
- if (options.force) {
872
- writeMode = "force";
873
- console.log(chalk.gray("Mode: Force overwrite existing files\n"));
874
- }
875
- else if (options.skipExisting) {
876
- writeMode = "skip";
877
- console.log(chalk.gray("Mode: Skip existing files\n"));
878
- }
879
- else if (options.yes) {
880
- // -y implies non-interactive: never prompt on conflicts. Default to skip
881
- // (preserve user files) — explicit --force is required to overwrite.
882
- writeMode = "skip";
883
- console.log(chalk.gray("Mode: Non-interactive (skip existing files)\n"));
884
- }
885
- setWriteMode(writeMode);
886
- // Detect developer name from git config or options
887
- let developerName = options.user;
888
- if (!developerName) {
889
- // Only detect from git if current directory is a git repo
890
- const isGitRepo = fs.existsSync(path.join(cwd, ".git"));
891
- if (isGitRepo) {
892
- try {
893
- developerName = execSync("git config user.name", {
894
- cwd,
895
- encoding: "utf-8",
896
- }).trim();
897
- }
898
- catch {
899
- // Git not available or no user.name configured
841
+ return withAssetMaintenance(process.cwd(), async () => {
842
+ // Refuse to run in $HOME — running here would scoop platform runtime data
843
+ // (Claude/Codex/OpenCode session histories etc.) into the trellis hash
844
+ // manifest, and a subsequent `trellis uninstall` would wipe it.
845
+ if (isCwdHomedir() && !homedirBypassEnabled()) {
846
+ console.error(chalk.red(homedirGuardMessage("init")));
847
+ process.exit(1);
848
+ }
849
+ // Deprecated alias: --windsurf → --devin (Windsurf was renamed to Devin).
850
+ // Normalize here too so programmatic callers (not just the CLI action) map
851
+ // correctly. The CLI action prints the deprecation notice.
852
+ if (options.windsurf) {
853
+ options.devin = true;
854
+ delete options.windsurf;
855
+ }
856
+ const cwd = process.cwd();
857
+ const isFirstInit = !fs.existsSync(path.join(cwd, DIR_NAMES.WORKFLOW));
858
+ // Captured here (before createWorkflowStructure + init_developer run) so
859
+ // the three-branch dispatch at the bottom can tell "fresh clone joiner"
860
+ // (.trellis/ exists, .developer missing) apart from "creator first init".
861
+ const hadDeveloperFileAtStart = fs.existsSync(path.join(cwd, DIR_NAMES.WORKFLOW, FILE_NAMES.DEVELOPER));
862
+ // Generate ASCII art banner dynamically using FIGlet "Rebel" font
863
+ const banner = figlet.textSync("Trellis", { font: "Rebel" });
864
+ console.log(chalk.cyan(`\n${banner.trimEnd()}`));
865
+ console.log(chalk.gray("\n All-in-one AI framework & toolkit for Claude Code & Cursor\n"));
866
+ // Set up proxy before any network calls
867
+ const proxyUrl = setupProxy();
868
+ if (proxyUrl) {
869
+ console.log(chalk.gray(` Using proxy: ${maskProxyUrl(proxyUrl)}\n`));
870
+ }
871
+ // Set write mode based on options
872
+ let writeMode = "ask";
873
+ if (options.force) {
874
+ writeMode = "force";
875
+ console.log(chalk.gray("Mode: Force overwrite existing files\n"));
876
+ }
877
+ else if (options.skipExisting) {
878
+ writeMode = "skip";
879
+ console.log(chalk.gray("Mode: Skip existing files\n"));
880
+ }
881
+ else if (options.yes) {
882
+ // -y implies non-interactive: never prompt on conflicts. Default to skip
883
+ // (preserve user files) — explicit --force is required to overwrite.
884
+ writeMode = "skip";
885
+ console.log(chalk.gray("Mode: Non-interactive (skip existing files)\n"));
886
+ }
887
+ setWriteMode(writeMode);
888
+ // Detect developer name from git config or options
889
+ let developerName = options.user;
890
+ if (!developerName) {
891
+ // Only detect from git if current directory is a git repo
892
+ const isGitRepo = fs.existsSync(path.join(cwd, ".git"));
893
+ if (isGitRepo) {
894
+ try {
895
+ developerName = execSync("git config user.name", {
896
+ cwd,
897
+ encoding: "utf-8",
898
+ }).trim();
899
+ }
900
+ catch {
901
+ // Git not available or no user.name configured
902
+ }
900
903
  }
901
904
  }
902
- }
903
- if (developerName) {
904
- console.log(chalk.blue("👤 Developer:"), chalk.gray(developerName));
905
- }
906
- const { command: pythonCmd } = resolveSupportedPython();
907
- // ==========================================================================
908
- // Re-init fast path: skip full flow when .trellis/ already exists
909
- // ==========================================================================
910
- // Aborted-init recovery (issue #204): if .trellis/ exists but tasks/ is
911
- // empty, the previous init never reached bootstrap creation. Fall through
912
- // to the full flow so the main-dispatch tasksEmpty fallback fires —
913
- // handleReinit's joiner branch would otherwise mis-route the recovery.
914
- const tasksEmptyEarly = tasksAreEmpty(cwd);
915
- const hasTemplateRequest = !!options.template || !!options.registry;
916
- if (!isFirstInit &&
917
- !options.force &&
918
- !options.skipExisting &&
919
- !tasksEmptyEarly &&
920
- !hasTemplateRequest) {
921
- const reinitDone = await handleReinit(cwd, options, developerName, pythonCmd);
922
- if (reinitDone)
923
- return;
924
- // reinitDone === false means user chose "full re-initialize" → fall through
925
- }
926
- if (!developerName && !options.yes) {
927
- // Ask for developer name if not detected and not in yes mode
928
- console.log(chalk.gray("\nTrellis supports team collaboration - each developer has their own\n" +
929
- `workspace directory (${PATHS.WORKSPACE}/{name}/) to track AI sessions.\n` +
930
- "Tip: Usually this is your git username (git config user.name).\n"));
931
- developerName = await askInput("Your name: ");
932
- while (!developerName) {
933
- console.log(chalk.yellow("Name is required"));
905
+ if (developerName) {
906
+ console.log(chalk.blue("👤 Developer:"), chalk.gray(developerName));
907
+ }
908
+ const { command: pythonCmd } = resolveSupportedPython();
909
+ // ==========================================================================
910
+ // Re-init fast path: skip full flow when .trellis/ already exists
911
+ // ==========================================================================
912
+ // Aborted-init recovery (issue #204): if .trellis/ exists but tasks/ is
913
+ // empty, the previous init never reached bootstrap creation. Fall through
914
+ // to the full flow so the main-dispatch tasksEmpty fallback fires —
915
+ // handleReinit's joiner branch would otherwise mis-route the recovery.
916
+ const tasksEmptyEarly = tasksAreEmpty(cwd);
917
+ const hasTemplateRequest = !!options.template || !!options.registry;
918
+ if (!isFirstInit &&
919
+ !options.force &&
920
+ !options.skipExisting &&
921
+ !tasksEmptyEarly &&
922
+ !hasTemplateRequest) {
923
+ const reinitDone = await handleReinit(cwd, options, developerName, pythonCmd);
924
+ if (reinitDone)
925
+ return;
926
+ // reinitDone === false means user chose "full re-initialize" → fall through
927
+ }
928
+ if (!developerName && !options.yes) {
929
+ // Ask for developer name if not detected and not in yes mode
930
+ console.log(chalk.gray("\nTrellis supports team collaboration - each developer has their own\n" +
931
+ `workspace directory (${PATHS.WORKSPACE}/{name}/) to track AI sessions.\n` +
932
+ "Tip: Usually this is your git username (git config user.name).\n"));
934
933
  developerName = await askInput("Your name: ");
934
+ while (!developerName) {
935
+ console.log(chalk.yellow("Name is required"));
936
+ developerName = await askInput("Your name: ");
937
+ }
938
+ console.log(chalk.blue("👤 Developer:"), chalk.gray(developerName));
935
939
  }
936
- console.log(chalk.blue("👤 Developer:"), chalk.gray(developerName));
937
- }
938
- // Detect project type (silent - no output)
939
- const detectedType = detectProjectType(cwd);
940
- // Parse custom registry source early (needed by both monorepo + single-repo flows)
941
- let registry;
942
- let registrySourceForConfig;
943
- if (options.registry) {
944
- try {
945
- registry = parseRegistrySource(options.registry);
946
- registrySourceForConfig = options.registry;
940
+ // Detect project type (silent - no output)
941
+ const detectedType = detectProjectType(cwd);
942
+ // Parse custom registry source early (needed by both monorepo + single-repo flows)
943
+ let registry;
944
+ let registrySourceForConfig;
945
+ if (options.registry) {
946
+ try {
947
+ registry = parseRegistrySource(options.registry);
948
+ registrySourceForConfig = options.registry;
949
+ }
950
+ catch (error) {
951
+ console.log(chalk.red(error instanceof Error ? error.message : "Invalid registry source"));
952
+ return;
953
+ }
947
954
  }
948
- catch (error) {
949
- console.log(chalk.red(error instanceof Error ? error.message : "Invalid registry source"));
950
- return;
955
+ // Determine template strategy from flags (needed before monorepo template downloads)
956
+ let templateStrategy = "skip";
957
+ if (options.overwrite) {
958
+ templateStrategy = "overwrite";
951
959
  }
952
- }
953
- // Determine template strategy from flags (needed before monorepo template downloads)
954
- let templateStrategy = "skip";
955
- if (options.overwrite) {
956
- templateStrategy = "overwrite";
957
- }
958
- else if (options.append) {
959
- templateStrategy = "append";
960
- }
961
- // ==========================================================================
962
- // Monorepo Detection
963
- // ==========================================================================
964
- let monorepoPackages;
965
- let remoteSpecPackages;
966
- if (options.monorepo !== false) {
967
- // options.monorepo: true = --monorepo, false = --no-monorepo, undefined = auto
968
- const detected = detectMonorepo(cwd);
969
- if (options.monorepo === true && !detected) {
970
- console.log(chalk.red("Error: --monorepo specified but no multi-package layout detected."));
971
- console.log("");
972
- console.log(chalk.gray("Checked:"));
973
- console.log(chalk.gray(" ✗ pnpm-workspace.yaml"));
974
- console.log(chalk.gray(" ✗ package.json workspaces"));
975
- console.log(chalk.gray(" ✗ Cargo.toml [workspace]"));
976
- console.log(chalk.gray(" ✗ go.work"));
977
- console.log(chalk.gray(" ✗ pyproject.toml [tool.uv.workspace]"));
978
- console.log(chalk.gray(" ✗ .gitmodules"));
979
- console.log(chalk.gray(" ✗ sibling .git directories (need ≥ 2)"));
980
- console.log("");
981
- console.log("To configure manually, add to .trellis/config.yaml:");
982
- console.log("");
983
- console.log(chalk.cyan(" packages:"));
984
- console.log(chalk.cyan(" frontend:"));
985
- console.log(chalk.cyan(" path: ./frontend"));
986
- console.log(chalk.cyan(" git: true # if it has its own .git"));
987
- console.log(chalk.cyan(" backend:"));
988
- console.log(chalk.cyan(" path: ./backend"));
989
- console.log(chalk.cyan(" git: true"));
990
- return;
960
+ else if (options.append) {
961
+ templateStrategy = "append";
991
962
  }
992
- if (detected && detected.length > 0) {
993
- let enableMonorepo = false;
994
- if (options.monorepo === true || options.yes) {
995
- enableMonorepo = true;
996
- }
997
- else {
998
- // Show detected packages and ask
999
- console.log(chalk.blue("\n🔍 Detected monorepo packages:"));
1000
- for (const pkg of detected) {
1001
- const tag = pkg.isSubmodule
1002
- ? chalk.gray(" (submodule)")
1003
- : pkg.isGitRepo
1004
- ? chalk.gray(" (git repo)")
1005
- : "";
1006
- console.log(chalk.gray(` - ${pkg.name}`) +
1007
- chalk.gray(` (${pkg.path})`) +
1008
- chalk.gray(` [${pkg.type}]`) +
1009
- tag);
1010
- }
963
+ // ==========================================================================
964
+ // Monorepo Detection
965
+ // ==========================================================================
966
+ let monorepoPackages;
967
+ let remoteSpecPackages;
968
+ if (options.monorepo !== false) {
969
+ // options.monorepo: true = --monorepo, false = --no-monorepo, undefined = auto
970
+ const detected = detectMonorepo(cwd);
971
+ if (options.monorepo === true && !detected) {
972
+ console.log(chalk.red("Error: --monorepo specified but no multi-package layout detected."));
1011
973
  console.log("");
1012
- const { useMonorepo } = await inquirer.prompt([
1013
- {
1014
- type: "confirm",
1015
- name: "useMonorepo",
1016
- message: "Enable monorepo mode?",
1017
- default: true,
1018
- },
1019
- ]);
1020
- enableMonorepo = useMonorepo;
974
+ console.log(chalk.gray("Checked:"));
975
+ console.log(chalk.gray(" ✗ pnpm-workspace.yaml"));
976
+ console.log(chalk.gray(" ✗ package.json workspaces"));
977
+ console.log(chalk.gray(" ✗ Cargo.toml [workspace]"));
978
+ console.log(chalk.gray(" ✗ go.work"));
979
+ console.log(chalk.gray(" ✗ pyproject.toml [tool.uv.workspace]"));
980
+ console.log(chalk.gray(" ✗ .gitmodules"));
981
+ console.log(chalk.gray(" ✗ sibling .git directories (need ≥ 2)"));
982
+ console.log("");
983
+ console.log("To configure manually, add to .trellis/config.yaml:");
984
+ console.log("");
985
+ console.log(chalk.cyan(" packages:"));
986
+ console.log(chalk.cyan(" frontend:"));
987
+ console.log(chalk.cyan(" path: ./frontend"));
988
+ console.log(chalk.cyan(" git: true # if it has its own .git"));
989
+ console.log(chalk.cyan(" backend:"));
990
+ console.log(chalk.cyan(" path: ./backend"));
991
+ console.log(chalk.cyan(" git: true"));
992
+ return;
1021
993
  }
1022
- if (enableMonorepo) {
1023
- monorepoPackages = detected;
1024
- remoteSpecPackages = new Set();
1025
- // Per-package template selection (unless -y mode: all use blank spec)
1026
- if (!options.yes && !options.template) {
994
+ if (detected && detected.length > 0) {
995
+ let enableMonorepo = false;
996
+ if (options.monorepo === true || options.yes) {
997
+ enableMonorepo = true;
998
+ }
999
+ else {
1000
+ // Show detected packages and ask
1001
+ console.log(chalk.blue("\n🔍 Detected monorepo packages:"));
1027
1002
  for (const pkg of detected) {
1028
- const { specSource } = await inquirer.prompt([
1029
- {
1030
- type: "list",
1031
- name: "specSource",
1032
- message: `Spec source for ${pkg.name} (${pkg.path}):`,
1033
- choices: [
1034
- { name: "From scratch (Trellis default)", value: "blank" },
1035
- { name: "Download remote template", value: "remote" },
1036
- ],
1037
- default: "blank",
1038
- },
1039
- ]);
1040
- if (specSource === "remote") {
1041
- // Use existing template download flow, targeting spec/<name>/
1042
- const destDir = path.join(cwd, PATHS.SPEC, sanitizePkgName(pkg.name));
1043
- console.log(chalk.blue(`📦 Select template for ${pkg.name}...`));
1044
- // Fetch templates if not already done
1045
- const templates = await fetchTemplateIndex();
1046
- const specTemplates = templates
1047
- .filter((t) => t.type === "spec")
1048
- .map((t) => ({
1049
- name: `${t.id} (${t.name})`,
1050
- value: t.id,
1051
- }));
1052
- if (specTemplates.length > 0) {
1053
- const { templateId } = await inquirer.prompt([
1054
- {
1055
- type: "list",
1056
- name: "templateId",
1057
- message: `Select template for ${pkg.name}:`,
1058
- choices: specTemplates,
1059
- },
1060
- ]);
1061
- const result = await downloadTemplateById(cwd, templateId, templateStrategy, templates.find((t) => t.id === templateId), undefined, destDir);
1062
- if (result.success) {
1063
- console.log(chalk.green(` ${result.message}`));
1064
- remoteSpecPackages.add(sanitizePkgName(pkg.name));
1003
+ const tag = pkg.isSubmodule
1004
+ ? chalk.gray(" (submodule)")
1005
+ : pkg.isGitRepo
1006
+ ? chalk.gray(" (git repo)")
1007
+ : "";
1008
+ console.log(chalk.gray(` - ${pkg.name}`) +
1009
+ chalk.gray(` (${pkg.path})`) +
1010
+ chalk.gray(` [${pkg.type}]`) +
1011
+ tag);
1012
+ }
1013
+ console.log("");
1014
+ const { useMonorepo } = await inquirer.prompt([
1015
+ {
1016
+ type: "confirm",
1017
+ name: "useMonorepo",
1018
+ message: "Enable monorepo mode?",
1019
+ default: true,
1020
+ },
1021
+ ]);
1022
+ enableMonorepo = useMonorepo;
1023
+ }
1024
+ if (enableMonorepo) {
1025
+ monorepoPackages = detected;
1026
+ remoteSpecPackages = new Set();
1027
+ // Per-package template selection (unless -y mode: all use blank spec)
1028
+ if (!options.yes && !options.template) {
1029
+ for (const pkg of detected) {
1030
+ const { specSource } = await inquirer.prompt([
1031
+ {
1032
+ type: "list",
1033
+ name: "specSource",
1034
+ message: `Spec source for ${pkg.name} (${pkg.path}):`,
1035
+ choices: [
1036
+ { name: "From scratch (Trellis default)", value: "blank" },
1037
+ { name: "Download remote template", value: "remote" },
1038
+ ],
1039
+ default: "blank",
1040
+ },
1041
+ ]);
1042
+ if (specSource === "remote") {
1043
+ // Use existing template download flow, targeting spec/<name>/
1044
+ const destDir = path.join(cwd, PATHS.SPEC, sanitizePkgName(pkg.name));
1045
+ console.log(chalk.blue(`📦 Select template for ${pkg.name}...`));
1046
+ // Fetch templates if not already done
1047
+ const templates = await fetchTemplateIndex();
1048
+ const specTemplates = templates
1049
+ .filter((t) => t.type === "spec")
1050
+ .map((t) => ({
1051
+ name: `${t.id} (${t.name})`,
1052
+ value: t.id,
1053
+ }));
1054
+ if (specTemplates.length > 0) {
1055
+ const { templateId } = await inquirer.prompt([
1056
+ {
1057
+ type: "list",
1058
+ name: "templateId",
1059
+ message: `Select template for ${pkg.name}:`,
1060
+ choices: specTemplates,
1061
+ },
1062
+ ]);
1063
+ const result = await downloadTemplateById(cwd, templateId, templateStrategy, templates.find((t) => t.id === templateId), undefined, destDir);
1064
+ if (result.success) {
1065
+ console.log(chalk.green(` ${result.message}`));
1066
+ remoteSpecPackages.add(sanitizePkgName(pkg.name));
1067
+ }
1068
+ else {
1069
+ console.log(chalk.yellow(` ${result.message}`));
1070
+ console.log(chalk.gray(" Falling back to blank spec..."));
1071
+ }
1065
1072
  }
1066
1073
  else {
1067
- console.log(chalk.yellow(` ${result.message}`));
1068
- console.log(chalk.gray(" Falling back to blank spec..."));
1074
+ console.log(chalk.gray(" No templates available. Using blank spec."));
1069
1075
  }
1070
1076
  }
1071
- else {
1072
- console.log(chalk.gray(" No templates available. Using blank spec."));
1073
- }
1074
1077
  }
1075
1078
  }
1076
- }
1077
- else if (options.template) {
1078
- // --template as default for all packages
1079
- for (const pkg of detected) {
1080
- const destDir = path.join(cwd, PATHS.SPEC, sanitizePkgName(pkg.name));
1081
- const result = await downloadTemplateById(cwd, options.template, templateStrategy, undefined, registry, destDir);
1082
- if (result.success && !result.skipped) {
1083
- remoteSpecPackages.add(sanitizePkgName(pkg.name));
1079
+ else if (options.template) {
1080
+ // --template as default for all packages
1081
+ for (const pkg of detected) {
1082
+ const destDir = path.join(cwd, PATHS.SPEC, sanitizePkgName(pkg.name));
1083
+ const result = await downloadTemplateById(cwd, options.template, templateStrategy, undefined, registry, destDir);
1084
+ if (result.success && !result.skipped) {
1085
+ remoteSpecPackages.add(sanitizePkgName(pkg.name));
1086
+ }
1084
1087
  }
1085
1088
  }
1086
1089
  }
1087
1090
  }
1088
1091
  }
1089
- }
1090
- // Tool definitions derived from platform registry
1091
- const TOOLS = getInitToolChoices();
1092
- // Build tools from explicit flags
1093
- const explicitTools = TOOLS.filter((t) => options[t.key]).map((t) => t.key);
1094
- let tools;
1095
- if (explicitTools.length > 0) {
1096
- // Explicit flags take precedence (works with or without -y)
1097
- tools = explicitTools;
1098
- }
1099
- else if (options.yes) {
1100
- // No explicit tools + -y: default to Cursor and Claude
1101
- tools = TOOLS.filter((t) => t.defaultChecked).map((t) => t.key);
1102
- }
1103
- else {
1104
- // Interactive mode
1105
- const answers = await inquirer.prompt([
1106
- {
1107
- type: "checkbox",
1108
- name: "tools",
1109
- message: "Select AI tools to configure:",
1110
- choices: TOOLS.map((t) => ({
1111
- name: t.name,
1112
- value: t.key,
1113
- checked: t.defaultChecked,
1114
- })),
1115
- },
1116
- ]);
1117
- tools = answers.tools;
1118
- }
1119
- // Treat unknown project type as fullstack
1120
- const projectType = detectedType === "unknown" ? "fullstack" : detectedType;
1121
- if (tools.length === 0) {
1122
- console.log(chalk.yellow("No tools selected. At least one tool is required."));
1123
- return;
1124
- }
1125
- // Opt-in Claude Code statusLine: confirm interactively when the flag wasn't passed
1126
- await maybePromptStatuslineOptIn(options, tools);
1127
- // ==========================================================================
1128
- // Template Selection (single-repo only; monorepo handles templates above)
1129
- // ==========================================================================
1130
- let selectedTemplate = null;
1131
- // Pre-fetched templates list (used to pass selected SpecTemplate to downloadTemplateById)
1132
- let fetchedTemplates = [];
1133
- let registryBackend;
1134
- // Determine the index URL based on registry
1135
- const indexUrl = registry
1136
- ? `${registry.rawBaseUrl}/index.json`
1137
- : TEMPLATE_INDEX_URL;
1138
- if (monorepoPackages) {
1139
- // Monorepo: template selection already handled above
1140
- }
1141
- else if (options.template) {
1142
- // Template specified via --template flag
1143
- selectedTemplate = options.template;
1144
- if (registry) {
1145
- const probeResult = await probeRegistryIndex(indexUrl, registry);
1146
- registryBackend = probeResult.backend;
1147
- if (probeResult.error) {
1148
- console.log(chalk.red(`Error: ${probeResult.error.message}`));
1149
- return;
1150
- }
1151
- if (probeResult.isNotFound) {
1152
- console.log(chalk.red("Error: Registry has no index.json. Remove --template to use direct download mode."));
1153
- return;
1154
- }
1155
- fetchedTemplates = probeResult.templates;
1092
+ // Tool definitions derived from platform registry
1093
+ const TOOLS = getInitToolChoices();
1094
+ // Build tools from explicit flags
1095
+ const explicitTools = TOOLS.filter((t) => options[t.key]).map((t) => t.key);
1096
+ let tools;
1097
+ if (explicitTools.length > 0) {
1098
+ // Explicit flags take precedence (works with or without -y)
1099
+ tools = explicitTools;
1156
1100
  }
1157
- }
1158
- else if (!options.yes) {
1159
- // Interactive mode: show template selection
1160
- const timeoutSec = TIMEOUTS.INDEX_FETCH_MS / 1000;
1161
- const sourceLabel = registry ? registry.gigetSource : TEMPLATE_INDEX_URL;
1162
- console.log(chalk.gray(` Fetching available templates from ${sourceLabel}`));
1163
- let elapsed = 0;
1164
- const ticker = setInterval(() => {
1165
- elapsed++;
1166
- process.stdout.write(`\r${chalk.gray(` Loading... ${elapsed}s/${timeoutSec}s`)}`);
1167
- }, 1000);
1168
- process.stdout.write(chalk.gray(` Loading... 0s/${timeoutSec}s`));
1169
- let templates;
1170
- let registryProbeNotFound = false;
1171
- let registryProbeError;
1172
- if (registry) {
1173
- const probeResult = await probeRegistryIndex(indexUrl, registry);
1174
- templates = probeResult.templates;
1175
- registryProbeNotFound = probeResult.isNotFound;
1176
- registryProbeError = probeResult.error;
1177
- registryBackend = probeResult.backend;
1101
+ else if (options.yes) {
1102
+ // No explicit tools + -y: default to Cursor and Claude
1103
+ tools = TOOLS.filter((t) => t.defaultChecked).map((t) => t.key);
1178
1104
  }
1179
1105
  else {
1180
- templates = await fetchTemplateIndex(indexUrl);
1106
+ // Interactive mode
1107
+ const answers = await inquirer.prompt([
1108
+ {
1109
+ type: "checkbox",
1110
+ name: "tools",
1111
+ message: "Select AI tools to configure:",
1112
+ choices: TOOLS.map((t) => ({
1113
+ name: t.name,
1114
+ value: t.key,
1115
+ checked: t.defaultChecked,
1116
+ })),
1117
+ },
1118
+ ]);
1119
+ tools = answers.tools;
1181
1120
  }
1182
- clearInterval(ticker);
1183
- // Clear the loading line
1184
- process.stdout.write("\r\x1b[2K");
1185
- fetchedTemplates = templates;
1186
- if (templates.length === 0 && registry && registryProbeNotFound) {
1187
- // Custom registry: confirmed no index.json — will try direct download later
1188
- console.log(chalk.gray(" No index.json found at registry. Will download as direct spec template."));
1189
- }
1190
- else if (templates.length === 0 && registry) {
1191
- // Custom registry: transient error (not a 404) — abort, don't misclassify
1192
- console.log(chalk.red(` ${registryProbeError?.message ?? "Could not reach registry. Check your connection and try again."}`));
1121
+ // Treat unknown project type as fullstack
1122
+ const projectType = detectedType === "unknown" ? "fullstack" : detectedType;
1123
+ if (tools.length === 0) {
1124
+ console.log(chalk.yellow("No tools selected. At least one tool is required."));
1193
1125
  return;
1194
1126
  }
1195
- else if (templates.length === 0) {
1196
- console.log(chalk.gray(" Could not fetch templates (offline or server unavailable)."));
1197
- console.log(chalk.gray(" Using blank templates.\n"));
1127
+ // Opt-in Claude Code statusLine: confirm interactively when the flag wasn't passed
1128
+ await maybePromptStatuslineOptIn(options, tools);
1129
+ // ==========================================================================
1130
+ // Template Selection (single-repo only; monorepo handles templates above)
1131
+ // ==========================================================================
1132
+ let selectedTemplate = null;
1133
+ // Pre-fetched templates list (used to pass selected SpecTemplate to downloadTemplateById)
1134
+ let fetchedTemplates = [];
1135
+ let registryBackend;
1136
+ // Determine the index URL based on registry
1137
+ const indexUrl = registry
1138
+ ? `${registry.rawBaseUrl}/index.json`
1139
+ : TEMPLATE_INDEX_URL;
1140
+ if (monorepoPackages) {
1141
+ // Monorepo: template selection already handled above
1198
1142
  }
1199
- if (templates.length > 0) {
1200
- // Build template choices
1201
- const specTemplates = templates
1202
- .filter((t) => t.type === "spec")
1203
- .map((t) => ({
1204
- name: `${t.id} (${t.name})`,
1205
- value: t.id,
1206
- }));
1207
- const templateChoices = registry
1208
- ? specTemplates
1209
- : [
1210
- {
1211
- name: "from scratch (default)",
1212
- value: "blank",
1213
- },
1214
- ...specTemplates,
1215
- {
1216
- name: "custom (enter a registry source)",
1217
- value: "__custom__",
1218
- },
1219
- ];
1220
- // Loop to allow returning from custom source input back to the picker
1221
- let templatePicked = false;
1222
- while (templateChoices.length > 0 && !templatePicked) {
1223
- const templateAnswer = await inquirer.prompt([
1224
- {
1225
- type: "list",
1226
- name: "template",
1227
- message: "Select a spec template:",
1228
- choices: templateChoices,
1229
- default: registry ? undefined : "blank",
1230
- },
1231
- ]);
1232
- if (templateAnswer.template === "__custom__") {
1233
- // Prompt for custom registry source (empty → back to picker)
1234
- const customSource = await askInput("Enter registry source (e.g., gh:myorg/myrepo/specs), or press Enter to go back: ");
1235
- if (!customSource) {
1236
- continue; // Back to picker
1237
- }
1238
- try {
1239
- registry = parseRegistrySource(customSource);
1240
- registrySourceForConfig = customSource;
1241
- fetchedTemplates = []; // Reset so direct-download guard works correctly
1242
- // Probe index.json to detect marketplace vs direct download
1243
- const customIndexUrl = `${registry.rawBaseUrl}/index.json`;
1244
- console.log(chalk.gray(` Checking for templates at ${registry.gigetSource}...`));
1245
- const customProbe = await probeRegistryIndex(customIndexUrl, registry);
1246
- const customTemplates = customProbe.templates;
1247
- registryBackend = customProbe.backend;
1248
- if (customTemplates.length > 0) {
1249
- // Marketplace mode: show picker with custom templates
1250
- fetchedTemplates = customTemplates;
1251
- const customChoices = customTemplates
1252
- .filter((t) => t.type === "spec")
1253
- .map((t) => ({
1254
- name: `${t.id} (${t.name})`,
1255
- value: t.id,
1256
- }));
1257
- if (customChoices.length > 0) {
1258
- const customAnswer = await inquirer.prompt([
1259
- {
1260
- type: "list",
1261
- name: "template",
1262
- message: "Select a spec template:",
1263
- choices: customChoices,
1264
- },
1265
- ]);
1266
- selectedTemplate = customAnswer.template;
1267
- // Check if spec directory already exists and ask what to do
1268
- const specDir = path.join(cwd, PATHS.SPEC);
1269
- if (fs.existsSync(specDir) &&
1270
- !options.overwrite &&
1271
- !options.append) {
1272
- const actionAnswer = await inquirer.prompt([
1143
+ else if (options.template) {
1144
+ // Template specified via --template flag
1145
+ selectedTemplate = options.template;
1146
+ if (registry) {
1147
+ const probeResult = await probeRegistryIndex(indexUrl, registry);
1148
+ registryBackend = probeResult.backend;
1149
+ if (probeResult.error) {
1150
+ console.log(chalk.red(`Error: ${probeResult.error.message}`));
1151
+ return;
1152
+ }
1153
+ if (probeResult.isNotFound) {
1154
+ console.log(chalk.red("Error: Registry has no index.json. Remove --template to use direct download mode."));
1155
+ return;
1156
+ }
1157
+ fetchedTemplates = probeResult.templates;
1158
+ }
1159
+ }
1160
+ else if (!options.yes) {
1161
+ // Interactive mode: show template selection
1162
+ const timeoutSec = TIMEOUTS.INDEX_FETCH_MS / 1000;
1163
+ const sourceLabel = registry ? registry.gigetSource : TEMPLATE_INDEX_URL;
1164
+ console.log(chalk.gray(` Fetching available templates from ${sourceLabel}`));
1165
+ let elapsed = 0;
1166
+ const ticker = setInterval(() => {
1167
+ elapsed++;
1168
+ process.stdout.write(`\r${chalk.gray(` Loading... ${elapsed}s/${timeoutSec}s`)}`);
1169
+ }, 1000);
1170
+ process.stdout.write(chalk.gray(` Loading... 0s/${timeoutSec}s`));
1171
+ let templates;
1172
+ let registryProbeNotFound = false;
1173
+ let registryProbeError;
1174
+ if (registry) {
1175
+ const probeResult = await probeRegistryIndex(indexUrl, registry);
1176
+ templates = probeResult.templates;
1177
+ registryProbeNotFound = probeResult.isNotFound;
1178
+ registryProbeError = probeResult.error;
1179
+ registryBackend = probeResult.backend;
1180
+ }
1181
+ else {
1182
+ templates = await fetchTemplateIndex(indexUrl);
1183
+ }
1184
+ clearInterval(ticker);
1185
+ // Clear the loading line
1186
+ process.stdout.write("\r\x1b[2K");
1187
+ fetchedTemplates = templates;
1188
+ if (templates.length === 0 && registry && registryProbeNotFound) {
1189
+ // Custom registry: confirmed no index.json — will try direct download later
1190
+ console.log(chalk.gray(" No index.json found at registry. Will download as direct spec template."));
1191
+ }
1192
+ else if (templates.length === 0 && registry) {
1193
+ // Custom registry: transient error (not a 404) — abort, don't misclassify
1194
+ console.log(chalk.red(` ${registryProbeError?.message ?? "Could not reach registry. Check your connection and try again."}`));
1195
+ return;
1196
+ }
1197
+ else if (templates.length === 0) {
1198
+ console.log(chalk.gray(" Could not fetch templates (offline or server unavailable)."));
1199
+ console.log(chalk.gray(" Using blank templates.\n"));
1200
+ }
1201
+ if (templates.length > 0) {
1202
+ // Build template choices
1203
+ const specTemplates = templates
1204
+ .filter((t) => t.type === "spec")
1205
+ .map((t) => ({
1206
+ name: `${t.id} (${t.name})`,
1207
+ value: t.id,
1208
+ }));
1209
+ const templateChoices = registry
1210
+ ? specTemplates
1211
+ : [
1212
+ {
1213
+ name: "from scratch (default)",
1214
+ value: "blank",
1215
+ },
1216
+ ...specTemplates,
1217
+ {
1218
+ name: "custom (enter a registry source)",
1219
+ value: "__custom__",
1220
+ },
1221
+ ];
1222
+ // Loop to allow returning from custom source input back to the picker
1223
+ let templatePicked = false;
1224
+ while (templateChoices.length > 0 && !templatePicked) {
1225
+ const templateAnswer = await inquirer.prompt([
1226
+ {
1227
+ type: "list",
1228
+ name: "template",
1229
+ message: "Select a spec template:",
1230
+ choices: templateChoices,
1231
+ default: registry ? undefined : "blank",
1232
+ },
1233
+ ]);
1234
+ if (templateAnswer.template === "__custom__") {
1235
+ // Prompt for custom registry source (empty → back to picker)
1236
+ const customSource = await askInput("Enter registry source (e.g., gh:myorg/myrepo/specs), or press Enter to go back: ");
1237
+ if (!customSource) {
1238
+ continue; // Back to picker
1239
+ }
1240
+ try {
1241
+ registry = parseRegistrySource(customSource);
1242
+ registrySourceForConfig = customSource;
1243
+ fetchedTemplates = []; // Reset so direct-download guard works correctly
1244
+ // Probe index.json to detect marketplace vs direct download
1245
+ const customIndexUrl = `${registry.rawBaseUrl}/index.json`;
1246
+ console.log(chalk.gray(` Checking for templates at ${registry.gigetSource}...`));
1247
+ const customProbe = await probeRegistryIndex(customIndexUrl, registry);
1248
+ const customTemplates = customProbe.templates;
1249
+ registryBackend = customProbe.backend;
1250
+ if (customTemplates.length > 0) {
1251
+ // Marketplace mode: show picker with custom templates
1252
+ fetchedTemplates = customTemplates;
1253
+ const customChoices = customTemplates
1254
+ .filter((t) => t.type === "spec")
1255
+ .map((t) => ({
1256
+ name: `${t.id} (${t.name})`,
1257
+ value: t.id,
1258
+ }));
1259
+ if (customChoices.length > 0) {
1260
+ const customAnswer = await inquirer.prompt([
1273
1261
  {
1274
1262
  type: "list",
1275
- name: "action",
1276
- message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1277
- choices: [
1278
- { name: "Skip (keep existing)", value: "skip" },
1279
- {
1280
- name: "Overwrite (replace all)",
1281
- value: "overwrite",
1282
- },
1283
- {
1284
- name: "Append (add missing files only)",
1285
- value: "append",
1286
- },
1287
- ],
1288
- default: "skip",
1263
+ name: "template",
1264
+ message: "Select a spec template:",
1265
+ choices: customChoices,
1289
1266
  },
1290
1267
  ]);
1291
- templateStrategy = actionAnswer.action;
1268
+ selectedTemplate = customAnswer.template;
1269
+ // Check if spec directory already exists and ask what to do
1270
+ const specDir = path.join(cwd, PATHS.SPEC);
1271
+ if (fs.existsSync(specDir) &&
1272
+ !options.overwrite &&
1273
+ !options.append) {
1274
+ const actionAnswer = await inquirer.prompt([
1275
+ {
1276
+ type: "list",
1277
+ name: "action",
1278
+ message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1279
+ choices: [
1280
+ { name: "Skip (keep existing)", value: "skip" },
1281
+ {
1282
+ name: "Overwrite (replace all)",
1283
+ value: "overwrite",
1284
+ },
1285
+ {
1286
+ name: "Append (add missing files only)",
1287
+ value: "append",
1288
+ },
1289
+ ],
1290
+ default: "skip",
1291
+ },
1292
+ ]);
1293
+ templateStrategy = actionAnswer.action;
1294
+ }
1292
1295
  }
1296
+ templatePicked = true;
1297
+ }
1298
+ else if (customProbe.isNotFound) {
1299
+ // No index.json → direct download mode
1300
+ templatePicked = true;
1301
+ }
1302
+ else {
1303
+ // Transient error (not 404) — loop back, don't misclassify
1304
+ console.log(chalk.yellow(` ${customProbe.error?.message ?? "Could not reach registry. Try again or enter a different source."}`));
1305
+ registry = undefined; // Reset so we don't fall through to direct download
1306
+ registrySourceForConfig = undefined;
1293
1307
  }
1294
- templatePicked = true;
1295
- }
1296
- else if (customProbe.isNotFound) {
1297
- // No index.json → direct download mode
1298
- templatePicked = true;
1299
1308
  }
1300
- else {
1301
- // Transient error (not 404) — loop back, don't misclassify
1302
- console.log(chalk.yellow(` ${customProbe.error?.message ?? "Could not reach registry. Try again or enter a different source."}`));
1303
- registry = undefined; // Reset so we don't fall through to direct download
1304
- registrySourceForConfig = undefined;
1309
+ catch (error) {
1310
+ console.log(chalk.red(error instanceof Error
1311
+ ? error.message
1312
+ : "Invalid registry source"));
1313
+ // Loop back to picker
1305
1314
  }
1306
1315
  }
1307
- catch (error) {
1308
- console.log(chalk.red(error instanceof Error
1309
- ? error.message
1310
- : "Invalid registry source"));
1311
- // Loop back to picker
1312
- }
1313
- }
1314
- else {
1315
- templatePicked = true;
1316
- if (templateAnswer.template !== "blank") {
1317
- selectedTemplate = templateAnswer.template;
1318
- // Check if spec directory already exists and ask what to do
1319
- const specDir = path.join(cwd, PATHS.SPEC);
1320
- if (fs.existsSync(specDir) &&
1321
- !options.overwrite &&
1322
- !options.append) {
1323
- const actionAnswer = await inquirer.prompt([
1324
- {
1325
- type: "list",
1326
- name: "action",
1327
- message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1328
- choices: [
1329
- { name: "Skip (keep existing)", value: "skip" },
1330
- { name: "Overwrite (replace all)", value: "overwrite" },
1331
- {
1332
- name: "Append (add missing files only)",
1333
- value: "append",
1334
- },
1335
- ],
1336
- default: "skip",
1337
- },
1338
- ]);
1339
- templateStrategy = actionAnswer.action;
1316
+ else {
1317
+ templatePicked = true;
1318
+ if (templateAnswer.template !== "blank") {
1319
+ selectedTemplate = templateAnswer.template;
1320
+ // Check if spec directory already exists and ask what to do
1321
+ const specDir = path.join(cwd, PATHS.SPEC);
1322
+ if (fs.existsSync(specDir) &&
1323
+ !options.overwrite &&
1324
+ !options.append) {
1325
+ const actionAnswer = await inquirer.prompt([
1326
+ {
1327
+ type: "list",
1328
+ name: "action",
1329
+ message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1330
+ choices: [
1331
+ { name: "Skip (keep existing)", value: "skip" },
1332
+ { name: "Overwrite (replace all)", value: "overwrite" },
1333
+ {
1334
+ name: "Append (add missing files only)",
1335
+ value: "append",
1336
+ },
1337
+ ],
1338
+ default: "skip",
1339
+ },
1340
+ ]);
1341
+ templateStrategy = actionAnswer.action;
1342
+ }
1340
1343
  }
1341
1344
  }
1342
1345
  }
1343
1346
  }
1344
1347
  }
1345
- }
1346
- // -y mode with --registry (no --template): probe index.json to detect mode
1347
- // Skip when monorepo mode already handled templates above
1348
- if (options.yes && registry && !selectedTemplate && !monorepoPackages) {
1349
- const probeResult = await probeRegistryIndex(`${registry.rawBaseUrl}/index.json`, registry);
1350
- registryBackend = probeResult.backend;
1351
- if (probeResult.templates.length > 0) {
1352
- // Marketplace mode requires interactive selection — can't auto-select
1353
- console.log(chalk.red("Error: Registry is a marketplace with multiple templates. " +
1354
- "Use --template <id> to specify which one, or remove -y for interactive selection."));
1355
- return;
1356
- }
1357
- if (!probeResult.isNotFound) {
1358
- // Transient error (not 404) — abort, don't misclassify as direct-download
1359
- console.log(chalk.red(`Error: ${probeResult.error?.message ?? "Could not reach registry. Check your connection and try again."}`));
1360
- return;
1348
+ // -y mode with --registry (no --template): probe index.json to detect mode
1349
+ // Skip when monorepo mode already handled templates above
1350
+ if (options.yes && registry && !selectedTemplate && !monorepoPackages) {
1351
+ const probeResult = await probeRegistryIndex(`${registry.rawBaseUrl}/index.json`, registry);
1352
+ registryBackend = probeResult.backend;
1353
+ if (probeResult.templates.length > 0) {
1354
+ // Marketplace mode requires interactive selection — can't auto-select
1355
+ console.log(chalk.red("Error: Registry is a marketplace with multiple templates. " +
1356
+ "Use --template <id> to specify which one, or remove -y for interactive selection."));
1357
+ return;
1358
+ }
1359
+ if (!probeResult.isNotFound) {
1360
+ // Transient error (not 404) — abort, don't misclassify as direct-download
1361
+ console.log(chalk.red(`Error: ${probeResult.error?.message ?? "Could not reach registry. Check your connection and try again."}`));
1362
+ return;
1363
+ }
1364
+ // isNotFound=true → no index.json, proceed with direct download (fetchedTemplates stays empty)
1361
1365
  }
1362
- // isNotFound=true → no index.json, proceed with direct download (fetchedTemplates stays empty)
1363
- }
1364
- // ==========================================================================
1365
- // Download Remote Template (if selected or direct registry download)
1366
- // ==========================================================================
1367
- let useRemoteTemplate = false;
1368
- let registrySpecConfigToPersist = null;
1369
- if (selectedTemplate) {
1370
- // Marketplace mode: download specific template by ID
1371
- console.log(chalk.blue(`📦 Downloading template "${selectedTemplate}"...`));
1372
- console.log(chalk.gray(" This may take a moment on slow connections."));
1373
- // Find pre-fetched SpecTemplate to avoid double-fetch
1374
- const prefetched = fetchedTemplates.find((t) => t.id === selectedTemplate);
1375
- const result = await downloadTemplateById(cwd, selectedTemplate, templateStrategy, prefetched, registry, undefined, registryBackend);
1376
- if (result.success) {
1377
- if (result.skipped) {
1378
- console.log(chalk.gray(` ${result.message}`));
1366
+ // ==========================================================================
1367
+ // Download Remote Template (if selected or direct registry download)
1368
+ // ==========================================================================
1369
+ let useRemoteTemplate = false;
1370
+ let registrySpecConfigToPersist = null;
1371
+ if (selectedTemplate) {
1372
+ // Marketplace mode: download specific template by ID
1373
+ console.log(chalk.blue(`📦 Downloading template "${selectedTemplate}"...`));
1374
+ console.log(chalk.gray(" This may take a moment on slow connections."));
1375
+ // Find pre-fetched SpecTemplate to avoid double-fetch
1376
+ const prefetched = fetchedTemplates.find((t) => t.id === selectedTemplate);
1377
+ const result = await downloadTemplateById(cwd, selectedTemplate, templateStrategy, prefetched, registry, undefined, registryBackend);
1378
+ if (result.success) {
1379
+ if (result.skipped) {
1380
+ console.log(chalk.gray(` ${result.message}`));
1381
+ }
1382
+ else {
1383
+ console.log(chalk.green(` ${result.message}`));
1384
+ useRemoteTemplate = true;
1385
+ if (registry) {
1386
+ registrySpecConfigToPersist = {
1387
+ source: registrySourceForConfig ?? registry.gigetSource,
1388
+ template: selectedTemplate,
1389
+ };
1390
+ }
1391
+ }
1379
1392
  }
1380
1393
  else {
1381
- console.log(chalk.green(` ${result.message}`));
1382
- useRemoteTemplate = true;
1383
- if (registry) {
1394
+ console.log(chalk.yellow(` ${result.message}`));
1395
+ console.log(chalk.gray(" Falling back to blank templates..."));
1396
+ const retryCmd = registry
1397
+ ? `trellis init --registry ${registry.gigetSource} --template ${selectedTemplate}`
1398
+ : `trellis init --template ${selectedTemplate}`;
1399
+ console.log(chalk.gray(` You can retry later: ${retryCmd}`));
1400
+ }
1401
+ }
1402
+ else if (registry && fetchedTemplates.length === 0) {
1403
+ // Direct download mode: registry has no index.json, download directory directly
1404
+ console.log(chalk.blue(`📦 Downloading spec from ${registry.gigetSource}...`));
1405
+ console.log(chalk.gray(" This may take a moment on slow connections."));
1406
+ // Ask about existing spec dir in interactive mode
1407
+ if (!options.yes && !options.overwrite && !options.append) {
1408
+ const specDir = path.join(cwd, PATHS.SPEC);
1409
+ if (fs.existsSync(specDir)) {
1410
+ const actionAnswer = await inquirer.prompt([
1411
+ {
1412
+ type: "list",
1413
+ name: "action",
1414
+ message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1415
+ choices: [
1416
+ { name: "Skip (keep existing)", value: "skip" },
1417
+ { name: "Overwrite (replace all)", value: "overwrite" },
1418
+ { name: "Append (add missing files only)", value: "append" },
1419
+ ],
1420
+ default: "skip",
1421
+ },
1422
+ ]);
1423
+ templateStrategy = actionAnswer.action;
1424
+ }
1425
+ }
1426
+ const result = await downloadRegistryDirect(cwd, registry, templateStrategy, undefined, registryBackend);
1427
+ if (result.success) {
1428
+ if (result.skipped) {
1429
+ console.log(chalk.gray(` ${result.message}`));
1430
+ }
1431
+ else {
1432
+ console.log(chalk.green(` ${result.message}`));
1433
+ useRemoteTemplate = true;
1384
1434
  registrySpecConfigToPersist = {
1385
1435
  source: registrySourceForConfig ?? registry.gigetSource,
1386
- template: selectedTemplate,
1387
1436
  };
1388
1437
  }
1389
1438
  }
1390
- }
1391
- else {
1392
- console.log(chalk.yellow(` ${result.message}`));
1393
- console.log(chalk.gray(" Falling back to blank templates..."));
1394
- const retryCmd = registry
1395
- ? `trellis init --registry ${registry.gigetSource} --template ${selectedTemplate}`
1396
- : `trellis init --template ${selectedTemplate}`;
1397
- console.log(chalk.gray(` You can retry later: ${retryCmd}`));
1398
- }
1399
- }
1400
- else if (registry && fetchedTemplates.length === 0) {
1401
- // Direct download mode: registry has no index.json, download directory directly
1402
- console.log(chalk.blue(`📦 Downloading spec from ${registry.gigetSource}...`));
1403
- console.log(chalk.gray(" This may take a moment on slow connections."));
1404
- // Ask about existing spec dir in interactive mode
1405
- if (!options.yes && !options.overwrite && !options.append) {
1406
- const specDir = path.join(cwd, PATHS.SPEC);
1407
- if (fs.existsSync(specDir)) {
1408
- const actionAnswer = await inquirer.prompt([
1409
- {
1410
- type: "list",
1411
- name: "action",
1412
- message: `Directory ${PATHS.SPEC} already exists. What do you want to do?`,
1413
- choices: [
1414
- { name: "Skip (keep existing)", value: "skip" },
1415
- { name: "Overwrite (replace all)", value: "overwrite" },
1416
- { name: "Append (add missing files only)", value: "append" },
1417
- ],
1418
- default: "skip",
1419
- },
1420
- ]);
1421
- templateStrategy = actionAnswer.action;
1422
- }
1423
- }
1424
- const result = await downloadRegistryDirect(cwd, registry, templateStrategy, undefined, registryBackend);
1425
- if (result.success) {
1426
- if (result.skipped) {
1427
- console.log(chalk.gray(` ${result.message}`));
1428
- }
1429
1439
  else {
1430
- console.log(chalk.green(` ${result.message}`));
1431
- useRemoteTemplate = true;
1432
- registrySpecConfigToPersist = {
1433
- source: registrySourceForConfig ?? registry.gigetSource,
1434
- };
1440
+ console.log(chalk.yellow(` ${result.message}`));
1441
+ console.log(chalk.gray(" Falling back to blank templates..."));
1442
+ console.log(chalk.gray(` You can retry later: trellis init --registry ${registry.gigetSource}`));
1435
1443
  }
1436
1444
  }
1437
- else {
1438
- console.log(chalk.yellow(` ${result.message}`));
1439
- console.log(chalk.gray(" Falling back to blank templates..."));
1440
- console.log(chalk.gray(` You can retry later: trellis init --registry ${registry.gigetSource}`));
1441
- }
1442
- }
1443
- // ==========================================================================
1444
- // Resolve workflow template (default: native bundled)
1445
- // ==========================================================================
1446
- const workflowIdInput = options.workflow?.trim();
1447
- const workflowId = workflowIdInput && workflowIdInput.length > 0
1448
- ? workflowIdInput
1449
- : NATIVE_WORKFLOW_ID;
1450
- let workflowMdOverride;
1451
- if (workflowId !== NATIVE_WORKFLOW_ID || options.workflowSource) {
1452
- const resolved = await resolveWorkflowTemplate(workflowId, {
1453
- source: options.workflowSource,
1454
- });
1455
- if (resolved.id !== NATIVE_WORKFLOW_ID) {
1456
- workflowMdOverride = resolved.content;
1457
- console.log(chalk.blue(`🧭 Using workflow template: ${chalk.cyan(resolved.id)}`));
1458
- }
1459
- }
1460
- // ==========================================================================
1461
- // Create Workflow Structure
1462
- // ==========================================================================
1463
- // Record every successful write from here through createRootFiles. The
1464
- // captured set is the source of truth for `.template-hashes.json`'s
1465
- // platform/root entries — replacing the previous "walk every managed dir"
1466
- // approach that swept user-owned runtime files into the manifest
1467
- // (.codex/sessions/, .claude/projects/, pre-existing AGENTS.md).
1468
- const writtenPaths = startRecordingWrites(cwd);
1469
- try {
1470
- // Create workflow structure with project type
1471
- console.log(chalk.blue("📁 Creating workflow structure..."));
1472
- await createWorkflowStructure(cwd, {
1473
- projectType,
1474
- skipSpecTemplates: useRemoteTemplate,
1475
- packages: monorepoPackages,
1476
- remoteSpecPackages,
1477
- workflowMdOverride,
1478
- });
1479
- // Write monorepo packages to config.yaml (non-destructive patch)
1480
- if (monorepoPackages) {
1481
- writeMonorepoConfig(cwd, monorepoPackages);
1482
- console.log(chalk.blue("📦 Monorepo packages written to config.yaml"));
1445
+ // ==========================================================================
1446
+ // Resolve workflow template (default: native bundled)
1447
+ // ==========================================================================
1448
+ const workflowIdInput = options.workflow?.trim();
1449
+ const workflowId = workflowIdInput && workflowIdInput.length > 0
1450
+ ? workflowIdInput
1451
+ : NATIVE_WORKFLOW_ID;
1452
+ let workflowMdOverride;
1453
+ if (workflowId !== NATIVE_WORKFLOW_ID || options.workflowSource) {
1454
+ const resolved = await resolveWorkflowTemplate(workflowId, {
1455
+ source: options.workflowSource,
1456
+ });
1457
+ if (resolved.id !== NATIVE_WORKFLOW_ID) {
1458
+ workflowMdOverride = resolved.content;
1459
+ console.log(chalk.blue(`🧭 Using workflow template: ${chalk.cyan(resolved.id)}`));
1460
+ }
1483
1461
  }
1484
- // Write version file for update tracking
1485
- const versionPath = path.join(cwd, DIR_NAMES.WORKFLOW, ".version");
1486
- fs.writeFileSync(versionPath, VERSION);
1487
- // Configure selected tools by copying entire directories (dogfooding)
1488
- for (const tool of tools) {
1489
- const platformId = resolveCliFlag(tool);
1490
- if (platformId) {
1491
- console.log(chalk.blue(`📝 Configuring ${AI_TOOLS[platformId].name}...`));
1492
- await configurePlatform(platformId, cwd, {
1493
- withStatusline: options.withStatusline,
1494
- });
1495
- if (platformId === "claude-code" && options.withStatusline) {
1496
- console.log(chalk.gray(" ↳ Trellis statusLine installed (--with-statusline)"));
1462
+ // ==========================================================================
1463
+ // Create Workflow Structure
1464
+ // ==========================================================================
1465
+ // Record every successful write from here through createRootFiles. The
1466
+ // captured set is the source of truth for `.template-hashes.json`'s
1467
+ // platform/root entries — replacing the previous "walk every managed dir"
1468
+ // approach that swept user-owned runtime files into the manifest
1469
+ // (.codex/sessions/, .claude/projects/, pre-existing AGENTS.md).
1470
+ const writtenPaths = startRecordingWrites(cwd);
1471
+ try {
1472
+ // Create workflow structure with project type
1473
+ console.log(chalk.blue("📁 Creating workflow structure..."));
1474
+ await createWorkflowStructure(cwd, {
1475
+ projectType,
1476
+ skipSpecTemplates: useRemoteTemplate,
1477
+ packages: monorepoPackages,
1478
+ remoteSpecPackages,
1479
+ workflowMdOverride,
1480
+ });
1481
+ // Write monorepo packages to config.yaml (non-destructive patch)
1482
+ if (monorepoPackages) {
1483
+ writeMonorepoConfig(cwd, monorepoPackages);
1484
+ console.log(chalk.blue("📦 Monorepo packages written to config.yaml"));
1485
+ }
1486
+ // Write version file for update tracking
1487
+ const versionPath = path.join(cwd, DIR_NAMES.WORKFLOW, ".version");
1488
+ fs.writeFileSync(versionPath, VERSION);
1489
+ // Configure selected tools by copying entire directories (dogfooding)
1490
+ for (const tool of tools) {
1491
+ const platformId = resolveCliFlag(tool);
1492
+ if (platformId) {
1493
+ console.log(chalk.blue(`📝 Configuring ${AI_TOOLS[platformId].name}...`));
1494
+ await configurePlatform(platformId, cwd, {
1495
+ withStatusline: options.withStatusline,
1496
+ });
1497
+ if (platformId === "claude-code" && options.withStatusline) {
1498
+ console.log(chalk.gray(" ↳ Trellis statusLine installed (--with-statusline)"));
1499
+ }
1497
1500
  }
1498
1501
  }
1502
+ const pythonPlatforms = getPlatformsWithPythonHooks();
1503
+ const hasSelectedPythonPlatform = pythonPlatforms.some((id) => tools.includes(AI_TOOLS[id].cliFlag));
1504
+ if (hasSelectedPythonPlatform) {
1505
+ logPythonAdaptationNotice(pythonCmd);
1506
+ }
1507
+ // Create root files (skip if exists)
1508
+ await createRootFiles(cwd);
1499
1509
  }
1500
- const pythonPlatforms = getPlatformsWithPythonHooks();
1501
- const hasSelectedPythonPlatform = pythonPlatforms.some((id) => tools.includes(AI_TOOLS[id].cliFlag));
1502
- if (hasSelectedPythonPlatform) {
1503
- logPythonAdaptationNotice(pythonCmd);
1504
- }
1505
- // Create root files (skip if exists)
1506
- await createRootFiles(cwd);
1507
- }
1508
- finally {
1509
- stopRecordingWrites();
1510
- }
1511
- if (registrySpecConfigToPersist) {
1512
- writeSpecRegistryConfig(cwd, registrySpecConfigToPersist);
1513
- }
1514
- // Initialize template hashes for modification tracking
1515
- const hashedCount = initializeHashes(cwd, { trackedPaths: writtenPaths });
1516
- if (useRemoteTemplate) {
1517
- const specFilesToHash = new Map();
1518
- for (const relativePath of collectSpecPaths(cwd)) {
1519
- const content = fs.readFileSync(path.join(cwd, relativePath), "utf-8");
1520
- specFilesToHash.set(relativePath, content);
1510
+ finally {
1511
+ stopRecordingWrites();
1521
1512
  }
1522
- if (specFilesToHash.size > 0) {
1523
- updateHashes(cwd, specFilesToHash);
1513
+ if (registrySpecConfigToPersist) {
1514
+ writeSpecRegistryConfig(cwd, registrySpecConfigToPersist);
1524
1515
  }
1525
- }
1526
- if (hashedCount > 0) {
1527
- console.log(chalk.gray(`📋 Tracking ${hashedCount} template files for updates`));
1528
- }
1529
- // Non-native workflow is user-managed local content. Drop the
1530
- // `.trellis/workflow.md` hash entry so `trellis update` classifies it as
1531
- // modified and does not silently restore native bytes. See design.md
1532
- // "Durable-state contract".
1533
- if (workflowMdOverride !== undefined && workflowId !== NATIVE_WORKFLOW_ID) {
1534
- removeHash(cwd, PATHS.WORKFLOW_GUIDE_FILE);
1535
- }
1536
- // Initialize developer identity (silent - no output)
1537
- if (developerName) {
1538
- try {
1539
- const scriptPath = path.join(cwd, PATHS.SCRIPTS, "init_developer.py");
1540
- execSync(`${pythonCmd} "${scriptPath}" "${developerName}"`, {
1541
- cwd,
1542
- stdio: "pipe", // Silent
1543
- });
1516
+ // Initialize template hashes for modification tracking
1517
+ const hashedCount = initializeHashes(cwd, { trackedPaths: writtenPaths });
1518
+ if (useRemoteTemplate) {
1519
+ const specFilesToHash = new Map();
1520
+ for (const relativePath of collectSpecPaths(cwd)) {
1521
+ const content = fs.readFileSync(path.join(cwd, relativePath), "utf-8");
1522
+ specFilesToHash.set(relativePath, content);
1523
+ }
1524
+ if (specFilesToHash.size > 0) {
1525
+ updateHashes(cwd, specFilesToHash);
1526
+ }
1544
1527
  }
1545
- catch {
1546
- // Silent failure - user can run init_developer.py manually
1528
+ if (hashedCount > 0) {
1529
+ console.log(chalk.gray(`📋 Tracking ${hashedCount} template files for updates`));
1547
1530
  }
1548
- // Three-branch dispatch using flags captured at init() start (before
1549
- // createWorkflowStructure/init_developer ran, so they reflect the disk
1550
- // state of the user's checkout, not the state this init just produced):
1551
- // isFirstInit=true → creator bootstrap (new project)
1552
- // isFirstInit=false + no .developer file → joiner onboarding (fresh clone)
1553
- // isFirstInit=false + .developer exists → same-dev re-init, no task
1554
- //
1555
- // Tasks-empty fallback (issue #204): if .trellis/ exists but tasks dir is
1556
- // empty, the previous init aborted before creating the bootstrap task. Run
1557
- // bootstrap creation regardless of isFirstInit. writeTaskSkeleton is
1558
- // idempotent so repeated triggers are safe.
1559
- //
1560
- // Runs OUTSIDE the init_developer try/catch (which uses stdio: "pipe")
1561
- // so joiner failures surface as warnings instead of being silently
1562
- // swallowed.
1563
- const tasksEmpty = tasksAreEmpty(cwd);
1564
- if (isFirstInit || tasksEmpty) {
1565
- createBootstrapTask(cwd, developerName, pythonCmd, projectType, monorepoPackages);
1531
+ // Non-native workflow is user-managed local content. Drop the
1532
+ // `.trellis/workflow.md` hash entry so `trellis update` classifies it as
1533
+ // modified and does not silently restore native bytes. See design.md
1534
+ // "Durable-state contract".
1535
+ if (workflowMdOverride !== undefined && workflowId !== NATIVE_WORKFLOW_ID) {
1536
+ removeHash(cwd, PATHS.WORKFLOW_GUIDE_FILE);
1566
1537
  }
1567
- else if (!hadDeveloperFileAtStart) {
1538
+ // Initialize developer identity (silent - no output)
1539
+ if (developerName) {
1568
1540
  try {
1569
- if (!createJoinerOnboardingTask(cwd, developerName, pythonCmd)) {
1570
- console.warn(chalk.yellow("⚠ Failed to create joiner onboarding task"));
1571
- }
1541
+ const scriptPath = path.join(cwd, PATHS.SCRIPTS, "init_developer.py");
1542
+ execSync(`${pythonCmd} "${scriptPath}" "${developerName}"`, {
1543
+ cwd,
1544
+ stdio: "pipe", // Silent
1545
+ });
1572
1546
  }
1573
- catch (err) {
1574
- console.warn(chalk.yellow(`⚠ Joiner onboarding setup failed: ${err instanceof Error ? err.message : String(err)}`));
1547
+ catch {
1548
+ // Silent failure - user can run init_developer.py manually
1549
+ }
1550
+ // Three-branch dispatch using flags captured at init() start (before
1551
+ // createWorkflowStructure/init_developer ran, so they reflect the disk
1552
+ // state of the user's checkout, not the state this init just produced):
1553
+ // isFirstInit=true → creator bootstrap (new project)
1554
+ // isFirstInit=false + no .developer file → joiner onboarding (fresh clone)
1555
+ // isFirstInit=false + .developer exists → same-dev re-init, no task
1556
+ //
1557
+ // Tasks-empty fallback (issue #204): if .trellis/ exists but tasks dir is
1558
+ // empty, the previous init aborted before creating the bootstrap task. Run
1559
+ // bootstrap creation regardless of isFirstInit. writeTaskSkeleton is
1560
+ // idempotent so repeated triggers are safe.
1561
+ //
1562
+ // Runs OUTSIDE the init_developer try/catch (which uses stdio: "pipe")
1563
+ // so joiner failures surface as warnings instead of being silently
1564
+ // swallowed.
1565
+ const tasksEmpty = tasksAreEmpty(cwd);
1566
+ if (isFirstInit || tasksEmpty) {
1567
+ createBootstrapTask(cwd, developerName, pythonCmd, projectType, monorepoPackages);
1568
+ }
1569
+ else if (!hadDeveloperFileAtStart) {
1570
+ try {
1571
+ if (!createJoinerOnboardingTask(cwd, developerName, pythonCmd)) {
1572
+ console.warn(chalk.yellow("⚠ Failed to create joiner onboarding task"));
1573
+ }
1574
+ }
1575
+ catch (err) {
1576
+ console.warn(chalk.yellow(`⚠ Joiner onboarding setup failed: ${err instanceof Error ? err.message : String(err)}`));
1577
+ }
1575
1578
  }
1576
1579
  }
1577
- }
1580
+ });
1578
1581
  }
1579
1582
  /**
1580
1583
  * Simple readline-based input (no flickering like inquirer)