@el-j/magic-agent-helix 4.0.0-beta.3 โ 4.0.0-beta.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.mjs +34 -34
- package/dist/cli.mjs.map +1 -1
- package/package.json +1 -1
package/dist/cli.mjs
CHANGED
|
@@ -6,7 +6,7 @@ import { resolve as ne, dirname as se, join as ie } from "node:path";
|
|
|
6
6
|
import { fileURLToPath as U } from "node:url";
|
|
7
7
|
import { Command as re } from "commander";
|
|
8
8
|
import t from "picocolors";
|
|
9
|
-
import { loadUserConfig as
|
|
9
|
+
import { loadUserConfig as O, mergeConfigs as L, PluginRegistry as C, getFormatter as Y, validateInstructions as ae } from "@el-j/magic-helix-core";
|
|
10
10
|
import W from "inquirer";
|
|
11
11
|
import j from "ora";
|
|
12
12
|
import q from "gradient-string";
|
|
@@ -14,7 +14,7 @@ import { glob as ce } from "glob";
|
|
|
14
14
|
async function le() {
|
|
15
15
|
console.log(t.cyan(`๐งน Cleaning generated instruction files...
|
|
16
16
|
`));
|
|
17
|
-
const e = j("Loading configuration...").start(), n =
|
|
17
|
+
const e = j("Loading configuration...").start(), n = O(), s = L(n);
|
|
18
18
|
e.succeed("Configuration loaded.");
|
|
19
19
|
const r = d.resolve(
|
|
20
20
|
process.cwd(),
|
|
@@ -72,9 +72,9 @@ async function le() {
|
|
|
72
72
|
)
|
|
73
73
|
);
|
|
74
74
|
}
|
|
75
|
-
const _ = "magic-helix.config.json",
|
|
75
|
+
const _ = "magic-helix.config.json", I = "ai_templates", ge = {
|
|
76
76
|
target: "github-copilot",
|
|
77
|
-
templateDirectory:
|
|
77
|
+
templateDirectory: I,
|
|
78
78
|
outputDirectory: ".github/instructions",
|
|
79
79
|
dependencyTagMap: {
|
|
80
80
|
// "my-internal-package": "domain-my-rules"
|
|
@@ -94,7 +94,7 @@ const _ = "magic-helix.config.json", O = "ai_templates", ge = {
|
|
|
94
94
|
async function ue() {
|
|
95
95
|
const e = j(
|
|
96
96
|
t.bold("Initializing Magic Helix for custom rules...")
|
|
97
|
-
).start(), n = d.resolve(process.cwd(), _), s = d.resolve(process.cwd(),
|
|
97
|
+
).start(), n = d.resolve(process.cwd(), _), s = d.resolve(process.cwd(), I);
|
|
98
98
|
if (p.existsSync(n)) {
|
|
99
99
|
e.stop();
|
|
100
100
|
const { overwrite: a } = await W.prompt([
|
|
@@ -127,7 +127,7 @@ async function ue() {
|
|
|
127
127
|
const r = d.resolve(s, "my-custom-rule.md");
|
|
128
128
|
p.existsSync(r) ? e.succeed(
|
|
129
129
|
t.green(
|
|
130
|
-
`Templates directory ${t.bold(
|
|
130
|
+
`Templates directory ${t.bold(I)} already exists.`
|
|
131
131
|
)
|
|
132
132
|
) : (p.writeFileSync(
|
|
133
133
|
r,
|
|
@@ -138,7 +138,7 @@ async function ue() {
|
|
|
138
138
|
"utf-8"
|
|
139
139
|
), e.succeed(
|
|
140
140
|
t.green(
|
|
141
|
-
`Created templates directory and example file: ${t.bold(
|
|
141
|
+
`Created templates directory and example file: ${t.bold(I)}`
|
|
142
142
|
)
|
|
143
143
|
)), console.log(
|
|
144
144
|
q.pastel.multiline(
|
|
@@ -149,7 +149,7 @@ async function ue() {
|
|
|
149
149
|
Next steps:`)), console.log(
|
|
150
150
|
` 1. Edit ${t.bold(_)} to define your team's "tags".`
|
|
151
151
|
), console.log(
|
|
152
|
-
` 2. Add your custom .md instruction files to ${t.bold(
|
|
152
|
+
` 2. Add your custom .md instruction files to ${t.bold(I)}.`
|
|
153
153
|
), console.log(
|
|
154
154
|
` 3. Run ${t.bold("npx @el-j/magic-agent-helix run")} to generate your files.`
|
|
155
155
|
);
|
|
@@ -157,7 +157,7 @@ Next steps:`)), console.log(
|
|
|
157
157
|
async function de() {
|
|
158
158
|
console.log(t.cyan(`๐ Listing project information...
|
|
159
159
|
`));
|
|
160
|
-
const e = j("Loading configuration...").start(), n =
|
|
160
|
+
const e = j("Loading configuration...").start(), n = O(), s = L(n);
|
|
161
161
|
e.succeed("Configuration loaded.");
|
|
162
162
|
const { dependencyTagMap: r, configFileTagMap: a, fileGlobTagMap: o, tagTemplateMap: c } = s, i = j("Scanning for projects...").start(), l = await fe();
|
|
163
163
|
if (l.length === 0) {
|
|
@@ -458,7 +458,7 @@ function $(e, n) {
|
|
|
458
458
|
}
|
|
459
459
|
async function we(e = {}) {
|
|
460
460
|
Q(e);
|
|
461
|
-
const n = j("Loading configurations...").start(), s =
|
|
461
|
+
const n = j("Loading configurations...").start(), s = O(e.config), r = L(s);
|
|
462
462
|
e.target && (r.target = e.target), n.succeed("Configuration loaded.");
|
|
463
463
|
const { dependencyTagMap: a, configFileTagMap: o, fileGlobTagMap: c, tagTemplateMap: i } = r, l = d.resolve(
|
|
464
464
|
process.cwd(),
|
|
@@ -500,10 +500,10 @@ async function we(e = {}) {
|
|
|
500
500
|
t.cyan(`
|
|
501
501
|
Refreshing instruction files in ${r.outputDirectory}...`)
|
|
502
502
|
);
|
|
503
|
-
let D = 0,
|
|
503
|
+
let D = 0, N = 0;
|
|
504
504
|
for (const y of w) {
|
|
505
505
|
if (y.tags.size === 0) {
|
|
506
|
-
console.log(t.gray(` Skipping: ${y.name} (No matching tags)`)),
|
|
506
|
+
console.log(t.gray(` Skipping: ${y.name} (No matching tags)`)), N++;
|
|
507
507
|
continue;
|
|
508
508
|
}
|
|
509
509
|
console.log(t.bold(` Processing: ${y.name}`)), console.log(t.gray(` Tags: ${[...y.tags].join(", ")}`));
|
|
@@ -539,7 +539,7 @@ ${k}`;
|
|
|
539
539
|
}
|
|
540
540
|
}
|
|
541
541
|
console.log(`
|
|
542
|
-
โจ Refresh complete!`), console.log(t.green(` Updated: ${D} files`)), console.log(t.gray(` Skipped: ${
|
|
542
|
+
โจ Refresh complete!`), console.log(t.green(` Updated: ${D} files`)), console.log(t.gray(` Skipped: ${N} projects`));
|
|
543
543
|
}
|
|
544
544
|
async function $e() {
|
|
545
545
|
const e = [], n = process.cwd(), s = C.getInstance();
|
|
@@ -682,7 +682,7 @@ async function J(e = {}) {
|
|
|
682
682
|
q.pastel.multiline("๐ค Running AI Convention Aligner...")
|
|
683
683
|
), n.dryRun && $("normal", s) && console.log(t.yellow(`๐ DRY RUN MODE - No files will be written
|
|
684
684
|
`));
|
|
685
|
-
const r = j("Loading configurations...").start(), a =
|
|
685
|
+
const r = j("Loading configurations...").start(), a = O(n.config), o = L(a);
|
|
686
686
|
n.outputDir && (o.outputDirectory = n.outputDir), n.target && (o.target = n.target), r.succeed("Configuration loaded.");
|
|
687
687
|
const { dependencyTagMap: c, configFileTagMap: i, fileGlobTagMap: l, tagTemplateMap: g } = o, u = d.resolve(
|
|
688
688
|
process.cwd(),
|
|
@@ -714,7 +714,7 @@ Supported project types: Node.js, Python, Go, Rust, Java, Ruby, PHP, C#, Swift,
|
|
|
714
714
|
}
|
|
715
715
|
m.succeed(`Found ${v.length} projects.`);
|
|
716
716
|
const D = j("Analyzing project tags...").start();
|
|
717
|
-
let
|
|
717
|
+
let N = 0;
|
|
718
718
|
for (const f of v) {
|
|
719
719
|
if (n.project && f.name !== n.project) {
|
|
720
720
|
$("verbose", s) && console.log(t.gray(`Skipping ${f.name} (not target project)`));
|
|
@@ -725,9 +725,9 @@ Supported project types: Node.js, Python, Go, Rust, Java, Ruby, PHP, C#, Swift,
|
|
|
725
725
|
c,
|
|
726
726
|
i,
|
|
727
727
|
l
|
|
728
|
-
),
|
|
728
|
+
), N += f.tags.size;
|
|
729
729
|
}
|
|
730
|
-
D.succeed(`Project analysis complete. Found ${
|
|
730
|
+
D.succeed(`Project analysis complete. Found ${N} tags.`), n.dryRun ? $("verbose", s) && console.log(t.gray(`Would ensure directory: ${h}`)) : be(h);
|
|
731
731
|
let y = g;
|
|
732
732
|
if (n.template) {
|
|
733
733
|
const f = n.template.split(",").map((x) => x.trim());
|
|
@@ -735,8 +735,8 @@ Supported project types: Node.js, Python, Go, Rust, Java, Ruby, PHP, C#, Swift,
|
|
|
735
735
|
for (const [x, R] of Object.entries(g)) {
|
|
736
736
|
const k = R.filter((b) => f.some((A) => {
|
|
737
737
|
if (A.includes("*")) {
|
|
738
|
-
const
|
|
739
|
-
return
|
|
738
|
+
const E = new RegExp(A.replace(/\*/g, ".*"));
|
|
739
|
+
return E.test(b.template) || E.test(x);
|
|
740
740
|
}
|
|
741
741
|
return b.template.includes(A) || x.includes(A);
|
|
742
742
|
}));
|
|
@@ -797,7 +797,7 @@ Generating instruction files in ${o.outputDirectory}...`)
|
|
|
797
797
|
if (k)
|
|
798
798
|
for (const b of k) {
|
|
799
799
|
F++;
|
|
800
|
-
const A = b.inlineContent ?? Re(u, b.template),
|
|
800
|
+
const A = b.inlineContent ?? Re(u, b.template), E = b.inlineContent ? "Plugin" : "Custom";
|
|
801
801
|
if (!A) {
|
|
802
802
|
console.warn(t.yellow(` โ ๏ธ Template not found: ${b.template}`));
|
|
803
803
|
continue;
|
|
@@ -810,11 +810,11 @@ Generating instruction files in ${o.outputDirectory}...`)
|
|
|
810
810
|
${X}`, G = b.suffix, ee = d.join(h, G);
|
|
811
811
|
P.push(G), n.dryRun ? $("normal", s) && console.log(
|
|
812
812
|
t.cyan(
|
|
813
|
-
` ๐ Would generate: ${t.bold(G)} (from ${
|
|
813
|
+
` ๐ Would generate: ${t.bold(G)} (from ${E})`
|
|
814
814
|
)
|
|
815
815
|
) : (p.writeFileSync(ee, Z), $("normal", s) && console.log(
|
|
816
816
|
t.green(
|
|
817
|
-
` โ
Generated: ${t.bold(G)} (from ${
|
|
817
|
+
` โ
Generated: ${t.bold(G)} (from ${E})`
|
|
818
818
|
)
|
|
819
819
|
));
|
|
820
820
|
}
|
|
@@ -902,22 +902,22 @@ async function Se() {
|
|
|
902
902
|
continue;
|
|
903
903
|
}
|
|
904
904
|
for (const o of a) {
|
|
905
|
-
const
|
|
906
|
-
let
|
|
905
|
+
const i = `${o.name.replace(/^lang-/, "").replace(/-core$/, "")}.instructions.md`;
|
|
906
|
+
let l = null;
|
|
907
907
|
try {
|
|
908
|
-
|
|
909
|
-
} catch (
|
|
908
|
+
l = typeof o.content == "function" ? await o.content() : o.content;
|
|
909
|
+
} catch (g) {
|
|
910
910
|
console.warn(
|
|
911
911
|
t.yellow(
|
|
912
|
-
`โ ๏ธ Plugin ${r.name} template ${o.name} failed to load: ${
|
|
912
|
+
`โ ๏ธ Plugin ${r.name} template ${o.name} failed to load: ${g.message}`
|
|
913
913
|
)
|
|
914
914
|
);
|
|
915
915
|
}
|
|
916
|
-
for (const
|
|
917
|
-
s[
|
|
916
|
+
for (const g of o.tags)
|
|
917
|
+
s[g] || (s[g] = []), s[g].push({
|
|
918
918
|
template: `plugin:${r.name}/${o.name}`,
|
|
919
|
-
suffix:
|
|
920
|
-
inlineContent:
|
|
919
|
+
suffix: i,
|
|
920
|
+
inlineContent: l ?? void 0
|
|
921
921
|
});
|
|
922
922
|
}
|
|
923
923
|
}
|
|
@@ -1043,7 +1043,7 @@ async function ke() {
|
|
|
1043
1043
|
t.cyan(`๐ Validating instruction files with quality scoring...
|
|
1044
1044
|
`)
|
|
1045
1045
|
);
|
|
1046
|
-
const e = j("Loading configuration...").start(), n =
|
|
1046
|
+
const e = j("Loading configuration...").start(), n = O(), s = L(n);
|
|
1047
1047
|
e.succeed("Configuration loaded.");
|
|
1048
1048
|
const r = d.resolve(
|
|
1049
1049
|
process.cwd(),
|
|
@@ -1167,8 +1167,8 @@ async function ze() {
|
|
|
1167
1167
|
), process.exit(1);
|
|
1168
1168
|
}
|
|
1169
1169
|
}
|
|
1170
|
-
const
|
|
1171
|
-
V &&
|
|
1170
|
+
const Ne = U(import.meta.url), V = process.argv[1] ? te(ne(process.argv[1])) : null;
|
|
1171
|
+
V && Ne === V && ze();
|
|
1172
1172
|
export {
|
|
1173
1173
|
ze as main
|
|
1174
1174
|
};
|
package/dist/cli.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cli.mjs","sources":["../src/commands/clean.ts","../src/commands/init.ts","../src/commands/list.ts","../src/commands/plugins.ts","../src/utils/file-extensions.ts","../src/utils/cli-options.ts","../src/commands/refresh.ts","../src/commands/run.ts","../src/commands/validate.ts","../src/cli.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadUserConfig, mergeConfigs } from '@el-j/magic-helix-core';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'clean' command.\n * Removes all generated instruction files.\n */\nexport async function clean() {\n console.log(pc.cyan('๐งน Cleaning generated instruction files...\\n'));\n\n const spinner = ora('Loading configuration...').start();\n\n // Load config to find output directory\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Check if directory exists\n if (!fs.existsSync(targetDir)) {\n console.log(\n pc.yellow(\n `โ ๏ธ Output directory ${config.outputDirectory} does not exist. Nothing to clean.`,\n ),\n );\n return;\n }\n\n // Find all .md files\n const files = fs.readdirSync(targetDir).filter((f) => f.endsWith('.md'));\n\n if (files.length === 0) {\n console.log(pc.gray('No instruction files found. Nothing to clean.'));\n return;\n }\n\n // Show files and ask for confirmation\n console.log(\n pc.yellow(`Found ${files.length} instruction file(s) to delete:\\n`),\n );\n for (const file of files) {\n console.log(pc.gray(` - ${file}`));\n }\n console.log();\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: pc.red(\n `Are you sure you want to delete all ${files.length} file(s)?`,\n ),\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(pc.yellow('Clean cancelled.'));\n return;\n }\n\n // Delete files\n const deleteSpinner = ora('Deleting files...').start();\n let deleteCount = 0;\n let errorCount = 0;\n\n for (const file of files) {\n try {\n fs.unlinkSync(path.join(targetDir, file));\n deleteCount++;\n } catch (e) {\n console.error(\n pc.red(` โ Error deleting ${file}: ${(e as Error).message}`),\n );\n errorCount++;\n }\n }\n\n if (errorCount === 0) {\n deleteSpinner.succeed(\n pc.green(`โ
Successfully deleted ${deleteCount} file(s).`),\n );\n } else {\n deleteSpinner.warn(\n pc.yellow(\n `โ ๏ธ Deleted ${deleteCount} file(s), ${errorCount} error(s) occurred.`,\n ),\n );\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Config } from '@el-j/magic-helix-core';\nimport gradient from 'gradient-string';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n// --- CONFIGURATION ---\nconst CONFIG_FILENAME = 'magic-helix.config.json';\nconst DEFAULT_TEMPLATE_DIR = 'ai_templates';\n\n// This is the *minimal* config file 'init' will create.\n// It's designed for users who want to *extend* the built-in rules.\nconst MINIMAL_USER_CONFIG: Config = {\n target: 'github-copilot',\n templateDirectory: DEFAULT_TEMPLATE_DIR,\n outputDirectory: '.github/instructions',\n dependencyTagMap: {\n // \"my-internal-package\": \"domain-my-rules\"\n },\n configFileTagMap: {\n // \"my-custom-config.json\": \"domain-my-rules\"\n },\n fileGlobTagMap: {\n // \"src/specific-folder/**/*.ts\": \"domain-my-rules\"\n },\n tagTemplateMap: {\n // \"domain-my-rules\": [\n // { \"template\": \"my-custom-rule.md\", \"suffix\": \"my-rule.md\" }\n // ]\n },\n};\n\n/**\n * The 'init' command.\n * Creates a minimal config file and template directory\n * for users who want to *extend* the built-in conventions.\n */\nexport async function init() {\n const spinner = ora(\n pc.bold('Initializing Magic Helix for custom rules...'),\n ).start();\n\n const configPath = path.resolve(process.cwd(), CONFIG_FILENAME);\n const templatePath = path.resolve(process.cwd(), DEFAULT_TEMPLATE_DIR);\n\n // Check if config file already exists\n if (fs.existsSync(configPath)) {\n spinner.stop();\n const { overwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'overwrite',\n message: `A ${CONFIG_FILENAME} file already exists. Do you want to overwrite it with a minimal example?`,\n default: false,\n },\n ]);\n if (!overwrite) {\n spinner.warn(pc.yellow('Operation cancelled.'));\n return;\n }\n spinner.start('Overwriting existing config...');\n }\n\n // 1. Write the minimal config file\n try {\n fs.writeFileSync(\n configPath,\n JSON.stringify(MINIMAL_USER_CONFIG, null, 2),\n 'utf-8',\n );\n spinner.succeed(\n pc.green(`Created minimal config file: ${pc.bold(CONFIG_FILENAME)}`),\n );\n } catch (e) {\n spinner.fail(pc.red(`Error writing config file: ${(e as Error).message}`));\n return;\n }\n\n spinner.start('Creating templates directory...');\n\n // 2. Create the templates directory\n if (!fs.existsSync(templatePath)) {\n fs.mkdirSync(templatePath, { recursive: true });\n }\n\n // 3. Copy *one* example file to show them how it works\n const exampleTemplatePath = path.resolve(templatePath, 'my-custom-rule.md');\n if (!fs.existsSync(exampleTemplatePath)) {\n fs.writeFileSync(\n exampleTemplatePath,\n '# My Team\\'s Custom Rule\\n- This rule is specific to our \"domain-my-rules\" tag.\\n- ALWAYS follow this important pattern.\\n',\n 'utf-8',\n );\n spinner.succeed(\n pc.green(\n `Created templates directory and example file: ${pc.bold(DEFAULT_TEMPLATE_DIR)}`,\n ),\n );\n } else {\n spinner.succeed(\n pc.green(\n `Templates directory ${pc.bold(DEFAULT_TEMPLATE_DIR)} already exists.`,\n ),\n );\n }\n\n console.log(\n gradient.pastel.multiline(\n '\\nโจ Success! Your project is ready for custom rules. โจ',\n ),\n );\n console.log(pc.cyan('\\nNext steps:'));\n console.log(\n ` 1. Edit ${pc.bold(CONFIG_FILENAME)} to define your team's \"tags\".`,\n );\n console.log(\n ` 2. Add your custom .md instruction files to ${pc.bold(DEFAULT_TEMPLATE_DIR)}.`,\n );\n console.log(\n ` 3. Run ${pc.bold('npx @el-j/magic-agent-helix run')} to generate your files.`,\n );\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n} from '@el-j/magic-helix-core';\nimport {\n PluginRegistry,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'list' command.\n * Shows detected projects, tags, and templates without generating files.\n */\nexport async function list() {\n console.log(pc.cyan('๐ Listing project information...\\n'));\n\n const spinner = ora('Loading configuration...').start();\n\n // 1. Load Configs\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n // 2. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(pc.yellow('No projects found.'));\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 3. Analyze projects\n const analyzeSpinner = ora('Analyzing projects...').start();\n for (const project of projects) {\n await analyzeProject(\n project,\n dependencyTagMap,\n configFileTagMap,\n fileGlobTagMap,\n );\n }\n analyzeSpinner.succeed('Analysis complete.\\n');\n\n // 4. Display results\n console.log(pc.cyan(pc.bold('Projects & Tags:\\n')));\n\n for (const project of projects) {\n console.log(pc.bold(`๐ฆ ${project.name}`));\n console.log(pc.gray(` Path: ${project.path}`));\n\n if (project.tags.size === 0) {\n console.log(pc.yellow(' No tags detected'));\n } else {\n console.log(pc.green(` Tags: ${[...project.tags].join(', ')}`));\n\n // Show which templates would be applied\n const templates: string[] = [];\n for (const tag of project.tags) {\n const tagTemplates = tagTemplateMap[tag];\n if (tagTemplates) {\n for (const t of tagTemplates) {\n templates.push(`${project.name}.${t.suffix}`);\n }\n }\n }\n\n if (templates.length > 0) {\n console.log(pc.gray(` Would generate: ${templates.join(', ')}`));\n }\n }\n console.log(); // Empty line\n }\n\n // 5. Show configuration summary\n console.log(pc.cyan(pc.bold('Configuration:\\n')));\n console.log(pc.gray(` Output directory: ${config.outputDirectory}`));\n console.log(pc.gray(` Template directory: ${config.templateDirectory}`));\n console.log(pc.gray(` Target: ${config.target}`));\n}\n\n// --- HELPER FUNCTIONS ---\n\ninterface Project {\n name: string;\n path: string;\n tags: Set<string>;\n}\n\nasync function findProjects(): Promise<Project[]> {\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Use the new polyglot detection\n const registry = PluginRegistry.getInstance();\n await registry.initialize();\n const detectedResults = await registry.detectAllProjects(rootPath);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const proj of detectedProjects) {\n const relativePath = path.relative(rootPath, proj.projectPath);\n projects.push({\n name: proj.name || path.basename(proj.projectPath),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedResults = await registry.detectAllProjects(projectRoot);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0]; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (_e) {\n // Skip errors\n }\n\n // Analyze config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (_e) {\n // Skip errors\n }\n\n // Analyze file globs\n try {\n const { glob } = await import('glob');\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true,\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (_e) {\n // Skip errors\n }\n}\n","import { PluginRegistry } from '@el-j/magic-helix-core';\nimport pc from 'picocolors';\n\ninterface PluginsOptions {\n verbose?: boolean;\n}\n\nexport async function pluginsCommand(\n options: PluginsOptions = {},\n): Promise<void> {\n console.log(pc.blue('๐ MagicAgentHelix Plugin System'));\n console.log();\n\n try {\n const registry = PluginRegistry.getInstance();\n await registry.initialize({ verbose: options.verbose });\n\n const plugins = await registry.getAllPlugins();\n const stats = registry.getStatistics();\n\n if (plugins.length === 0) {\n console.log(pc.yellow('โ ๏ธ No plugins loaded'));\n return;\n }\n\n console.log(pc.green(`โ
${plugins.length} plugin(s) loaded successfully`));\n console.log();\n\n // Display plugins grouped by priority\n const sortedPlugins = plugins.sort((a, b) => b.priority - a.priority);\n\n console.log(pc.bold('Available Language Plugins:'));\n console.log('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ');\n\n for (const plugin of sortedPlugins) {\n const priorityColor =\n plugin.priority >= 90\n ? 'green'\n : plugin.priority >= 70\n ? 'yellow'\n : 'cyan';\n\n console.log(\n `${pc.bold(plugin.displayName)} (${pc[priorityColor](`priority: ${plugin.priority}`)}) v${plugin.version}`,\n );\n\n if (options.verbose) {\n const templates = plugin.getTemplates();\n if (templates.length > 0) {\n console.log(\n ` ๐ Templates: ${templates.map((t) => t.name).join(', ')}`,\n );\n }\n\n const tagMap = plugin.getDependencyTagMap?.();\n if (tagMap && Object.keys(tagMap).length > 0) {\n console.log(\n ` ๐ท๏ธ Detects: ${Object.keys(tagMap).slice(0, 3).join(', ')}${Object.keys(tagMap).length > 3 ? '...' : ''}`,\n );\n }\n console.log();\n }\n }\n\n if (!options.verbose) {\n console.log();\n console.log(pc.dim('๐ก Use --verbose for detailed plugin information'));\n }\n\n console.log();\n console.log(pc.bold('System Statistics:'));\n console.log('โโโโโโโโโโโโโโโโโโ');\n console.log(`๐ Total plugins: ${stats.totalLoaded}`);\n console.log(`โก Average load time: ${stats.averageLoadTime.toFixed(1)}ms`);\n console.log(`โ Load errors: ${stats.totalErrors}`);\n\n if (stats.totalErrors > 0 && options.verbose) {\n const errors = registry.getLoadErrors();\n console.log();\n console.log(pc.red('Load Errors:'));\n console.log('โโโโโโโโโโโโ');\n for (const error of errors) {\n console.log(`โ ${error.source.identifier}: ${error.error.message}`);\n }\n }\n } catch (error) {\n console.error(\n pc.red('โ Failed to load plugin registry:'),\n (error as Error).message,\n );\n process.exit(1);\n }\n}\n","/**\n * Utilities for mapping tags to appropriate file extensions\n */\n\nexport interface FileExtensionMapping {\n extensions: string[];\n description: string;\n}\n\n/**\n * Maps tags to their associated file extensions\n */\nexport const TAG_FILE_EXTENSIONS: Record<string, FileExtensionMapping> = {\n // Frameworks\n 'framework-vue': {\n extensions: ['vue'],\n description: 'Vue components',\n },\n 'framework-react': {\n extensions: ['tsx', 'jsx', 'ts', 'js'],\n description: 'React components',\n },\n 'framework-angular': {\n extensions: ['ts'],\n description: 'Angular components',\n },\n 'framework-nestjs': {\n extensions: ['ts'],\n description: 'NestJS controllers and services',\n },\n\n // Languages\n 'lang-typescript': {\n extensions: ['ts', 'tsx'],\n description: 'TypeScript files',\n },\n 'lang-javascript': {\n extensions: ['js', 'jsx'],\n description: 'JavaScript files',\n },\n 'lang-go': {\n extensions: ['go'],\n description: 'Go files',\n },\n 'lang-python': {\n extensions: ['py'],\n description: 'Python files',\n },\n 'lang-rust': {\n extensions: ['rs'],\n description: 'Rust files',\n },\n 'rust-embedded': {\n extensions: ['rs'],\n description: 'Embedded Rust files',\n },\n hardware2rust: {\n extensions: ['rs'],\n description: 'Hardware2Rust project files',\n },\n 'lang-java': {\n extensions: ['java'],\n description: 'Java files',\n },\n 'lang-swift': {\n extensions: ['swift'],\n description: 'Swift files',\n },\n 'lang-ruby': {\n extensions: ['rb'],\n description: 'Ruby files',\n },\n 'lang-php': {\n extensions: ['php'],\n description: 'PHP files',\n },\n 'lang-csharp': {\n extensions: ['cs'],\n description: 'C# files',\n },\n 'lang-cpp': {\n extensions: ['cpp', 'hpp', 'cc', 'h', 'cxx', 'hxx'],\n description: 'C++ files',\n },\n 'lang-c': {\n extensions: ['c', 'h'],\n description: 'C files',\n },\n 'lang-kotlin': {\n extensions: ['kt', 'kts'],\n description: 'Kotlin files',\n },\n 'lang-scala': {\n extensions: ['scala', 'sc'],\n description: 'Scala files',\n },\n\n // Styling\n 'style-tailwind': {\n extensions: ['ts', 'tsx', 'js', 'jsx', 'vue'],\n description: 'Files using Tailwind CSS',\n },\n 'style-primevue': {\n extensions: ['vue'],\n description: 'Vue files with PrimeVue',\n },\n 'style-mui': {\n extensions: ['tsx', 'jsx'],\n description: 'React files with Material UI',\n },\n\n // Testing\n 'test-vitest': {\n extensions: ['test.ts', 'test.tsx', 'spec.ts', 'spec.tsx'],\n description: 'Vitest test files',\n },\n 'test-jest': {\n extensions: [\n 'test.ts',\n 'test.tsx',\n 'test.js',\n 'test.jsx',\n 'spec.ts',\n 'spec.tsx',\n 'spec.js',\n 'spec.jsx',\n ],\n description: 'Jest test files',\n },\n 'test-cypress': {\n extensions: ['cy.ts', 'cy.js'],\n description: 'Cypress test files',\n },\n 'test-playwright': {\n extensions: ['spec.ts', 'spec.js'],\n description: 'Playwright test files',\n },\n\n // State management\n 'state-rxjs': {\n extensions: ['ts', 'tsx'],\n description: 'Files using RxJS',\n },\n 'state-pinia': {\n extensions: ['ts', 'vue'],\n description: 'Vue files with Pinia',\n },\n 'state-redux': {\n extensions: ['ts', 'tsx', 'js', 'jsx'],\n description: 'Files using Redux',\n },\n 'state-zustand': {\n extensions: ['ts', 'tsx', 'js', 'jsx'],\n description: 'Files using Zustand',\n },\n};\n\n/**\n * Get file extensions for a given tag\n */\nexport function getFileExtensionsForTag(tag: string): string[] {\n return TAG_FILE_EXTENSIONS[tag]?.extensions || [];\n}\n\n/**\n * Build a precise glob pattern based on project path and tags\n */\nexport function buildPreciseGlobPattern(\n projectPath: string,\n tags: Set<string>,\n excludePattern?: string,\n): string {\n const allExtensions = new Set<string>();\n\n // Collect all extensions from all tags\n for (const tag of tags) {\n const exts = getFileExtensionsForTag(tag);\n for (const ext of exts) {\n allExtensions.add(ext);\n }\n }\n\n // Fallback to common extensions if no tags matched\n if (allExtensions.size === 0) {\n return `${projectPath}/src/**/*.{ts,js,vue,tsx,jsx}`;\n }\n\n // Build pattern\n const extList = Array.from(allExtensions).join(',');\n let pattern = `${projectPath}/src/**/*.{${extList}}`;\n\n // Add exclude pattern if provided\n if (excludePattern) {\n // Convert exclude pattern to glob negation\n const excludePatterns = excludePattern.split(',').map((p) => p.trim());\n for (const exclude of excludePatterns) {\n // Handle directory exclusions\n if (exclude.endsWith('/**')) {\n pattern += ` !(${projectPath}/src/${exclude})`;\n } else if (exclude.includes('*')) {\n pattern += ` !(${projectPath}/src/${exclude})`;\n } else {\n // Exact file match\n pattern += ` !(${projectPath}/src/${exclude})`;\n }\n }\n }\n\n return pattern;\n}\n\n/**\n * Get a human-readable description of what file types apply\n */\nexport function getApplyToDescription(tags: Set<string>): string {\n const descriptions: string[] = [];\n\n for (const tag of tags) {\n const mapping = TAG_FILE_EXTENSIONS[tag];\n if (mapping) {\n descriptions.push(mapping.description);\n }\n }\n\n return descriptions.length > 0 ? descriptions.join(', ') : 'Source files';\n}\n","/**\n * Shared CLI options and types\n */\n\nexport interface CliOptions {\n dryRun?: boolean;\n force?: boolean;\n skipPruning?: boolean;\n outputDir?: string;\n config?: string;\n target?: 'github-copilot' | 'claude' | 'copilot-chat' | 'generic';\n verbose?: boolean;\n quiet?: boolean;\n project?: string;\n wizard?: boolean;\n template?: string;\n exclude?: string;\n}\n\n/**\n * Log level based on options\n */\nexport function getLogLevel(\n options: CliOptions,\n): 'verbose' | 'normal' | 'quiet' {\n if (options.quiet) return 'quiet';\n if (options.verbose) return 'verbose';\n return 'normal';\n}\n\n/**\n * Should we log this message at this level?\n */\nexport function shouldLog(\n messageLevel: 'verbose' | 'normal' | 'error',\n logLevel: 'verbose' | 'normal' | 'quiet',\n): boolean {\n if (logLevel === 'quiet' && messageLevel !== 'error') return false;\n if (logLevel === 'normal' && messageLevel === 'verbose') return false;\n return true;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n TagTemplateMap,\n} from '@el-j/magic-helix-core';\nimport {\n type AssistantTarget,\n getFormatter,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport { PluginRegistry } from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\nimport { buildPreciseGlobPattern } from '../utils/file-extensions';\n\n// --- TYPES ---\ninterface Project {\n name: string;\n path: string;\n tags: Set<string>;\n}\n\nimport type { CliOptions } from '../utils/cli-options';\nimport { getLogLevel } from '../utils/cli-options';\n\n/**\n * The 'refresh' command.\n * Rescans the project and updates existing instruction files with new information.\n */\nexport async function refresh(options: CliOptions = {}) {\n const _logLevel = getLogLevel(options);\n\n const mainSpinner = ora('Loading configurations...').start();\n\n // 1. Load Configs\n const userConfig = loadUserConfig(options.config);\n const config = mergeConfigs(userConfig);\n\n // Override target if specified\n if (options.target) {\n config.target = options.target;\n }\n\n mainSpinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n const userTemplateDir = path.resolve(\n process.cwd(),\n config.templateDirectory as string,\n );\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Get the formatter for the target assistant\n const formatter = getFormatter(config.target as AssistantTarget);\n\n // 2. Check if target directory exists\n if (!fs.existsSync(targetDir)) {\n console.log(\n pc.yellow(\n `โ ๏ธ Output directory ${config.outputDirectory} does not exist.`,\n ),\n );\n console.log(\n pc.gray(` Run 'magic-helix run' first to generate instruction files.`),\n );\n return;\n }\n\n // 3. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(\n pc.yellow(\n 'No projects found. Make sure your root package.json has a \"workspaces\" field.',\n ),\n );\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 4. Analyze dependencies and tag projects\n const analyzeSpinner = ora('Analyzing project tags...').start();\n let totalTags = 0;\n for (const project of projects) {\n await analyzeProject(\n project,\n dependencyTagMap as DependencyTagMap,\n configFileTagMap as ConfigFileTagMap,\n fileGlobTagMap as FileGlobTagMap,\n );\n totalTags += project.tags.size;\n }\n analyzeSpinner.succeed(`Project analysis complete. Found ${totalTags} tags.`);\n\n // 5. Update existing instruction files\n console.log(\n pc.cyan(`\\nRefreshing instruction files in ${config.outputDirectory}...`),\n );\n\n let updatedCount = 0;\n let skippedCount = 0;\n\n for (const project of projects) {\n if (project.tags.size === 0) {\n console.log(pc.gray(` Skipping: ${project.name} (No matching tags)`));\n skippedCount++;\n continue;\n }\n\n console.log(pc.bold(` Processing: ${project.name}`));\n console.log(pc.gray(` Tags: ${[...project.tags].join(', ')}`));\n\n const globPattern = buildPreciseGlobPattern(project.path, project.tags);\n\n for (const tag of project.tags) {\n const templates = (tagTemplateMap as TagTemplateMap)[tag];\n if (!templates) continue;\n\n for (const t of templates) {\n const outputFilename = `${project.name}.${t.suffix}`;\n const outputPath = path.join(targetDir, outputFilename);\n\n // Check if file exists\n if (!fs.existsSync(outputPath)) {\n console.log(\n pc.yellow(` โ ๏ธ File not found, skipping: ${outputFilename}`),\n );\n continue;\n }\n\n // Read template from user custom directory\n const templateContent = readTemplate(userTemplateDir, t.template);\n const source = 'Custom';\n\n if (!templateContent) {\n console.warn(pc.yellow(` โ ๏ธ Template not found: ${t.template}`));\n continue;\n }\n\n // Update header with new information\n const header = formatter.getFrontmatter(globPattern, project.name);\n const formattedContent = formatter.format(\n templateContent,\n globPattern,\n project.name,\n );\n const fullContent = `${header}\\n${formattedContent}`;\n\n // Write updated file\n fs.writeFileSync(outputPath, fullContent);\n updatedCount++;\n console.log(\n pc.green(\n ` โ
Refreshed: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n }\n }\n\n console.log('\\nโจ Refresh complete!');\n console.log(pc.green(` Updated: ${updatedCount} files`));\n console.log(pc.gray(` Skipped: ${skippedCount} projects`));\n}\n\n// --- HELPER FUNCTIONS ---\n\nasync function findProjects(): Promise<Project[]> {\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Use the new polyglot detection\n const registry = PluginRegistry.getInstance();\n await registry.initialize();\n const detectedResults = await registry.detectAllProjects(rootPath);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const proj of detectedProjects) {\n const relativePath = path.relative(rootPath, proj.projectPath);\n projects.push({\n name: proj.name || path.basename(proj.projectPath),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Strategy 1: Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedResults = await registry.detectAllProjects(projectRoot);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0]; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Could not analyze dependencies for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 2: Analyze key config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning config files for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 3: Analyze file globs\n try {\n const { glob } = await import('glob');\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true,\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning file globs for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n}\n\nfunction readTemplate(dir: string, templateFile: string): string | null {\n const p = path.join(dir, templateFile);\n try {\n return fs.readFileSync(p, 'utf-8');\n } catch (_e) {\n return null;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n LanguagePlugin,\n TagTemplateMap,\n} from '@el-j/magic-helix-core';\nimport {\n type AssistantTarget,\n PluginRegistry,\n type TemplateDefinition,\n getFormatter,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport { glob } from 'glob';\nimport gradient from 'gradient-string';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\nimport type { CliOptions } from '../utils/cli-options';\nimport { getLogLevel, shouldLog } from '../utils/cli-options';\nimport { buildPreciseGlobPattern } from '../utils/file-extensions';\n\n// --- TYPES ---\ninterface Project {\n name: string; // Sanitized package name, e.g., 'scope-my-app'\n path: string; // Relative path from root, e.g., 'packages/my-app'\n tags: Set<string>;\n}\n\ntype TemplateSource = {\n template: string;\n suffix: string;\n inlineContent?: string;\n};\n\n/**\n * Interactive wizard to guide users through configuration options\n */\nasync function runWizard(): Promise<Partial<CliOptions>> {\n console.log(\n gradient.pastel.multiline('๐ค MagicAgentHelix Interactive Setup Wizard'),\n );\n console.log(\"Let's configure your AI instruction generation...\\n\");\n\n const answers = await inquirer.prompt([\n {\n type: 'list',\n name: 'target',\n message: 'Which AI assistant are you using?',\n choices: [\n { name: 'GitHub Copilot', value: 'github-copilot' },\n { name: 'Claude/Cursor', value: 'claude' },\n { name: 'GitHub Copilot Chat', value: 'copilot-chat' },\n { name: 'Generic Assistant', value: 'generic' },\n ],\n default: 'github-copilot',\n },\n {\n type: 'confirm',\n name: 'dryRun',\n message:\n 'Would you like to preview what would be generated first (dry run)?',\n default: true,\n },\n {\n type: 'input',\n name: 'outputDir',\n message: 'Where should the instruction files be generated?',\n default: '.ai',\n when: (answers) => !answers.dryRun,\n },\n {\n type: 'confirm',\n name: 'force',\n message: 'Overwrite existing files without prompting?',\n default: false,\n when: (answers) => !answers.dryRun,\n },\n {\n type: 'list',\n name: 'verbosity',\n message: 'How much output would you like to see?',\n choices: [\n { name: 'Verbose (detailed information)', value: 'verbose' },\n { name: 'Normal (standard output)', value: 'normal' },\n { name: 'Quiet (minimal output)', value: 'quiet' },\n ],\n default: 'normal',\n },\n ]);\n\n // Convert verbosity to CLI options\n const options: Partial<CliOptions> = {\n target: answers.target,\n dryRun: answers.dryRun,\n };\n\n if (answers.outputDir) {\n options.outputDir = answers.outputDir;\n }\n\n if (answers.force) {\n options.force = answers.force;\n }\n\n if (answers.verbosity === 'verbose') {\n options.verbose = true;\n } else if (answers.verbosity === 'quiet') {\n options.quiet = true;\n }\n\n console.log(pc.green('\\nโ
Configuration complete! Starting analysis...\\n'));\n\n return options;\n}\n\n/**\n * The 'run' command.\n * Scans the monorepo and generates instruction files.\n */\nexport async function run(options: CliOptions = {}) {\n // Run interactive wizard if requested\n let effectiveOptions = options;\n if (options.wizard) {\n const wizardOptions = await runWizard();\n // Merge wizard options with command line options (CLI options take precedence)\n effectiveOptions = { ...wizardOptions, ...options };\n }\n\n const logLevel = getLogLevel(effectiveOptions);\n\n if (shouldLog('normal', logLevel)) {\n console.log(\n gradient.pastel.multiline('๐ค Running AI Convention Aligner...'),\n );\n }\n\n if (effectiveOptions.dryRun && shouldLog('normal', logLevel)) {\n console.log(pc.yellow('๐ DRY RUN MODE - No files will be written\\n'));\n }\n\n const mainSpinner = ora('Loading configurations...').start();\n\n // 1. Load Configs (Built-in + Optional User)\n const userConfig = loadUserConfig(effectiveOptions.config);\n const config = mergeConfigs(userConfig);\n\n // Override output directory if specified\n if (effectiveOptions.outputDir) {\n config.outputDirectory = effectiveOptions.outputDir;\n }\n\n // Override target if specified\n if (effectiveOptions.target) {\n config.target = effectiveOptions.target;\n }\n\n mainSpinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n const userTemplateDir = path.resolve(\n process.cwd(),\n config.templateDirectory as string,\n );\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Get the formatter for the target assistant\n const formatter = getFormatter(config.target as AssistantTarget);\n\n // 2. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(\n pc.yellow(\n 'No projects detected. The tool could not find any supported project types in the current directory.',\n ),\n );\n console.log(\n pc.gray(\n '\\nSupported project types: Node.js, Python, Go, Rust, Java, Ruby, PHP, C#, Swift, C/C++, PlatformIO',\n ),\n );\n console.log(\n pc.gray(\n 'For monorepos, ensure your root package.json has a \"workspaces\" field.',\n ),\n );\n console.log(\n pc.gray(\n 'For standalone projects, ensure you have the appropriate manifest file (package.json, go.mod, Cargo.toml, platformio.ini, etc.)',\n ),\n );\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 3. Analyze dependencies and tag projects\n const analyzeSpinner = ora('Analyzing project tags...').start();\n let totalTags = 0;\n for (const project of projects) {\n // Skip if specific project requested and this isn't it\n if (effectiveOptions.project && project.name !== effectiveOptions.project) {\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(`Skipping ${project.name} (not target project)`));\n }\n continue;\n }\n\n await analyzeProject(\n project,\n dependencyTagMap as DependencyTagMap,\n configFileTagMap as ConfigFileTagMap,\n fileGlobTagMap as FileGlobTagMap,\n );\n totalTags += project.tags.size;\n }\n analyzeSpinner.succeed(`Project analysis complete. Found ${totalTags} tags.`);\n\n // 4. Ensure target directory exists\n if (!effectiveOptions.dryRun) {\n ensureTargetDir(targetDir);\n } else if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(`Would ensure directory: ${targetDir}`));\n }\n\n // Apply template filtering if specified\n let filteredTagTemplateMap = tagTemplateMap as TagTemplateMap;\n if (effectiveOptions.template) {\n const templatePatterns = effectiveOptions.template\n .split(',')\n .map((p) => p.trim());\n filteredTagTemplateMap = {} as TagTemplateMap;\n\n for (const [tag, templates] of Object.entries(tagTemplateMap)) {\n const filteredTemplates = templates.filter((template) => {\n return templatePatterns.some((pattern) => {\n // Support wildcard matching\n if (pattern.includes('*')) {\n const regex = new RegExp(pattern.replace(/\\*/g, '.*'));\n return regex.test(template.template) || regex.test(tag);\n }\n return template.template.includes(pattern) || tag.includes(pattern);\n });\n });\n\n if (filteredTemplates.length > 0) {\n filteredTagTemplateMap[tag] = filteredTemplates;\n }\n }\n\n if (shouldLog('verbose', logLevel)) {\n console.log(\n pc.gray(`Template filter applied: ${effectiveOptions.template}`),\n );\n }\n }\n\n // Merge plugin-provided templates (inline content) with config templates\n const pluginTemplateMap = await getPluginTemplates();\n const combinedTemplateMap: Record<string, TemplateSource[]> = {};\n\n for (const [tag, templates] of Object.entries(filteredTagTemplateMap)) {\n combinedTemplateMap[tag] = templates.map((t) => ({\n template: t.template,\n suffix: t.suffix,\n }));\n }\n\n for (const [tag, templates] of Object.entries(pluginTemplateMap)) {\n if (!combinedTemplateMap[tag]) {\n combinedTemplateMap[tag] = [];\n }\n combinedTemplateMap[tag].push(...templates);\n }\n\n // Debug logging for template maps\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray('\\n--- Template Map Debug ---'));\n console.log(\n pc.gray(\n `Plugin templates: ${Object.keys(pluginTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(pluginTemplateMap).join(', ')}`),\n );\n console.log(\n pc.gray(\n `Config templates: ${Object.keys(filteredTagTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(filteredTagTemplateMap).join(', ')}`),\n );\n console.log(\n pc.gray(\n `Combined templates: ${Object.keys(combinedTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(combinedTemplateMap).join(', ')}`),\n );\n }\n\n // 5. Generate files\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.cyan(`\\nGenerating instruction files in ${config.outputDirectory}...`),\n );\n }\n const generateSpinner = ora('Generating instruction files...').start();\n const generatedFiles: string[] = [];\n let processedProjects = 0;\n let totalTemplates = 0;\n for (const project of projects) {\n // Skip if specific project requested and this isn't it\n if (effectiveOptions.project && project.name !== effectiveOptions.project) {\n continue;\n }\n\n if (project.tags.size === 0) {\n if (shouldLog('normal', logLevel)) {\n console.log(pc.gray(` Skipping: ${project.name} (No matching tags)`));\n }\n continue;\n }\n\n processedProjects++;\n if (shouldLog('normal', logLevel)) {\n console.log(pc.bold(` Processing: ${project.name}`));\n }\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(` Tags: ${[...project.tags].join(', ')}`));\n }\n\n const globPattern = buildPreciseGlobPattern(\n project.path,\n project.tags,\n effectiveOptions.exclude,\n );\n\n for (const tag of project.tags) {\n const templates = combinedTemplateMap[tag];\n if (!templates) continue;\n\n for (const t of templates) {\n totalTemplates++;\n // Use plugin inline content or user custom templates\n const templateContent =\n t.inlineContent ?? readTemplate(userTemplateDir, t.template);\n const source = t.inlineContent ? 'Plugin' : 'Custom';\n\n if (!templateContent) {\n console.warn(pc.yellow(` โ ๏ธ Template not found: ${t.template}`));\n continue;\n }\n\n const header = formatter.getFrontmatter(globPattern, project.name);\n const formattedContent = formatter.format(\n templateContent,\n globPattern,\n project.name,\n );\n const fullContent = `${header}\\n${formattedContent}`;\n\n // Use just the suffix as the filename (e.g., \"typescript.instructions.md\")\n // This follows GitHub Copilot's naming convention for path-specific instructions\n const outputFilename = t.suffix;\n const outputPath = path.join(targetDir, outputFilename);\n\n generatedFiles.push(outputFilename);\n\n if (effectiveOptions.dryRun) {\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.cyan(\n ` ๐ Would generate: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n } else {\n fs.writeFileSync(outputPath, fullContent);\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.green(\n ` โ
Generated: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n }\n }\n }\n }\n\n generateSpinner.succeed(\n `Generated ${generatedFiles.length} files from ${totalTemplates} templates across ${processedProjects} projects`,\n );\n\n // 6. Pruning: Ask to remove old files\n if (!effectiveOptions.dryRun && !effectiveOptions.skipPruning) {\n await pruneOldFiles(targetDir, generatedFiles, effectiveOptions.force);\n } else if (effectiveOptions.dryRun && shouldLog('verbose', logLevel)) {\n console.log(pc.gray('\\nWould check for old files to prune...'));\n }\n\n if (shouldLog('normal', logLevel)) {\n console.log(`\\n${'โ'.repeat(60)}`);\n if (effectiveOptions.dryRun) {\n console.log(pc.cyan('โจ Dry run complete! No files were modified.'));\n console.log(\n pc.gray(\n `๐ Would have generated ${generatedFiles.length} instruction file(s)`,\n ),\n );\n console.log(\n pc.gray(\n `๐ From ${totalTemplates} template(s) across ${processedProjects} project(s)`,\n ),\n );\n } else {\n console.log(pc.green('โจ AI instruction alignment complete!'));\n console.log(\n pc.bold(`๐ Generated ${generatedFiles.length} instruction file(s)`),\n );\n console.log(\n pc.gray(\n `๐ From ${totalTemplates} template(s) across ${processedProjects} project(s)`,\n ),\n );\n console.log(\n pc.gray(`๐ Files are located in: ${pc.bold(config.outputDirectory)}`),\n );\n }\n console.log('โ'.repeat(60));\n }\n\n if (config.target === 'github-copilot' && shouldLog('normal', logLevel)) {\n console.log('\\n--- VS Code + GitHub Copilot Tip ---');\n console.log(\n \"To maximize Copilot's awareness, add this to your workspace .vscode/settings.json:\",\n );\n console.log(`\n \"github.copilot.advanced\": {\n \"instructions\": \".github/instructions\"\n }\n `);\n console.log(\n 'This tells Copilot to *always* read these files. Restart VS Code after adding.',\n );\n }\n}\n\n// --- HELPER FUNCTIONS ---\n\nfunction ensureTargetDir(targetDir: string) {\n const spinner = ora(`Checking target directory: ${targetDir}`).start();\n if (!fs.existsSync(targetDir)) {\n spinner.text = 'Target directory not found. Creating...';\n try {\n fs.mkdirSync(targetDir, { recursive: true });\n spinner.succeed(`Created ${targetDir}`);\n } catch (error) {\n spinner.fail(\n pc.red(\n `Error creating directory: ${(error as Error).message}. Please check permissions.`,\n ),\n );\n process.exit(1);\n }\n } else {\n spinner.succeed('Target directory OK.');\n }\n}\n\nasync function ensureRegistryInitialized() {\n const registry = PluginRegistry.getInstance();\n // initialize will short-circuit if already initialized\n await registry.initialize();\n}\n\nasync function getPluginTemplates(): Promise<Record<string, TemplateSource[]>> {\n await ensureRegistryInitialized();\n const registry = PluginRegistry.getInstance();\n let plugins: LanguagePlugin[] = [];\n\n try {\n // Direct method call instead of type casting\n plugins = await registry.getAllPlugins();\n } catch (e) {\n console.warn(\n pc.yellow(`โ ๏ธ Failed to get plugins: ${(e as Error).message}`),\n );\n console.warn(\n pc.yellow(\n `โ ๏ธ Registry type: ${typeof registry}, has getAllPlugins: ${typeof registry?.getAllPlugins}`,\n ),\n );\n }\n\n if (plugins.length === 0) {\n console.warn(pc.yellow('โ ๏ธ No plugins loaded from registry!'));\n }\n\n const map: Record<string, TemplateSource[]> = {};\n\n for (const plugin of plugins) {\n let templates: TemplateDefinition[] = [];\n try {\n const maybeTemplates = await plugin.getTemplates();\n templates = Array.isArray(maybeTemplates) ? maybeTemplates : [];\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Plugin ${plugin.name} getTemplates failed: ${(e as Error).message}`,\n ),\n );\n continue;\n }\n\n for (const tmpl of templates) {\n const suffix = `${tmpl.name}.md`;\n let content: string | null = null;\n try {\n content =\n typeof tmpl.content === 'function'\n ? await tmpl.content()\n : tmpl.content;\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Plugin ${plugin.name} template ${tmpl.name} failed to load: ${(e as Error).message}`,\n ),\n );\n }\n\n for (const tag of tmpl.tags) {\n if (!map[tag]) map[tag] = [];\n map[tag].push({\n template: `plugin:${plugin.name}/${tmpl.name}`,\n suffix,\n inlineContent: content ?? undefined,\n });\n }\n }\n }\n\n return map;\n}\n\nasync function findProjects(): Promise<Project[]> {\n await ensureRegistryInitialized();\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Initialize plugin registry and detect projects\n const registry = PluginRegistry.getInstance();\n const detectedProjects = await registry.detectAllProjects(rootPath);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const result of detectedProjects) {\n const relativePath = path.relative(rootPath, result.metadata.projectPath);\n projects.push({\n name: sanitizeProjectName(\n result.metadata.name || path.basename(result.metadata.projectPath),\n ),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\n/**\n * Sanitize project names for filesystem-safe output filenames.\n * - Convert scoped names like \"@scope/app\" to \"scope-app\"\n * - Replace path separators and whitespace with '-'\n * - Remove leading '@'\n */\nfunction sanitizeProjectName(name: string): string {\n const trimmed = name.trim();\n // Replace slashes with dashes, remove leading '@'\n let sanitized = trimmed.replace(/^@/, '').replace(/[\\\\/\\s]+/g, '-');\n // Collapse multiple dashes\n sanitized = sanitized.replace(/-+/g, '-');\n return sanitized;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n await ensureRegistryInitialized();\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Strategy 1: Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedProjects = await registry.detectAllProjects(projectRoot);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0].metadata; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Could not analyze dependencies for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 2: Analyze key config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning config files for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 3: Analyze file globs\n try {\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n // Use 'glob' package for async globbing\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true, // Include dotfiles if needed, though 'src' patterns usually don't\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning file globs for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n}\n\nfunction readTemplate(dir: string, templateFile: string): string | null {\n const p = path.join(dir, templateFile);\n try {\n return fs.readFileSync(p, 'utf-8');\n } catch (_e) {\n return null; // Will be handled in the main function\n }\n}\n\nasync function pruneOldFiles(\n targetDir: string,\n generatedFiles: string[],\n force = false,\n) {\n const existingFiles = fs\n .readdirSync(targetDir)\n .filter((f) => f.endsWith('.md'));\n\n const oldFiles = existingFiles.filter((f) => !generatedFiles.includes(f));\n\n if (oldFiles.length > 0) {\n console.warn(\n pc.yellow(\n `\\nโ ๏ธ Found ${oldFiles.length} instruction files that are no longer generated:`,\n ),\n );\n for (const f of oldFiles) {\n console.warn(pc.yellow(` - ${f}`));\n }\n\n let prune = force;\n\n if (!force) {\n const answer = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prune',\n message: `Do you want to delete these ${oldFiles.length} old files?`,\n default: false,\n },\n ]);\n prune = answer.prune;\n }\n\n if (prune) {\n let deleteCount = 0;\n for (const file of oldFiles) {\n try {\n fs.unlinkSync(path.join(targetDir, file));\n deleteCount++;\n } catch (e) {\n console.error(\n pc.red(` โ Error deleting ${file}: ${(e as Error).message}`),\n );\n }\n }\n console.log(`โ
Pruned ${deleteCount} old files.`);\n }\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n loadUserConfig,\n mergeConfigs,\n validateInstructions,\n} from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'validate' command.\n * Checks instruction files for quality based on awesome-ai-system-prompts best practices.\n */\nexport async function validate() {\n console.log(\n pc.cyan('๐ Validating instruction files with quality scoring...\\n'),\n );\n\n const spinner = ora('Loading configuration...').start();\n\n // Load config\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Check if directory exists\n if (!fs.existsSync(targetDir)) {\n spinner.fail(\n pc.red(\n `โ Output directory ${config.outputDirectory} does not exist. Run 'magic-helix run' first.`,\n ),\n );\n return;\n }\n\n // Find all .md files\n const files = fs.readdirSync(targetDir).filter((f) => f.endsWith('.md'));\n\n if (files.length === 0) {\n console.log(\n pc.yellow(\"No instruction files found. Run 'magic-helix run' first.\"),\n );\n return;\n }\n\n console.log(pc.gray(`Checking ${files.length} instruction file(s)...\\n`));\n\n // Telemetry (optional): fall back to no-op if unavailable\n let telemetry: { track: (event: unknown) => void } = { track: () => {} };\n try {\n const core = await import('@el-j/magic-helix-core');\n // Check if createTelemetry is available in the imported core module\n const coreExports = core as Record<string, unknown>;\n if (typeof coreExports.createTelemetry === 'function') {\n const createTelemetry = coreExports.createTelemetry as (\n config: Record<string, unknown>,\n ) => { track: (event: unknown) => void };\n telemetry = createTelemetry({});\n }\n } catch {\n // ignore if core import fails in test/browser\n }\n\n let passCount = 0;\n let failCount = 0;\n const results: Array<{ file: string; score: number; grade: string }> = [];\n\n for (const file of files) {\n const filePath = path.join(targetDir, file);\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n\n // Run quality validation\n const quality = validateInstructions(content);\n const grade = getQualityGrade(quality.overallScore);\n\n results.push({ file, score: quality.overallScore, grade });\n\n if (quality.overallScore >= 70) {\n passCount++;\n } else {\n failCount++;\n }\n\n // Display individual file results\n const scoreColor =\n quality.overallScore >= 90\n ? pc.green\n : quality.overallScore >= 70\n ? pc.blue\n : pc.yellow;\n\n console.log(\n scoreColor(`${grade} ${quality.overallScore}/100`) +\n pc.gray(` - ${file}`),\n );\n\n if (quality.missingElements.length > 0) {\n console.log(\n pc.red(` Missing: ${quality.missingElements.join(', ')}`),\n );\n }\n\n if (quality.recommendations.length > 0 && quality.overallScore < 90) {\n console.log(pc.gray(` Tip: ${quality.recommendations[0]}`));\n }\n\n // Track per-file validation result\n telemetry.track({\n type: 'instruction_validation',\n file,\n score: quality.overallScore,\n structureScore: quality.structureScore,\n clarityScore: quality.clarityScore,\n completenessScore: quality.completenessScore,\n missingCount: quality.missingElements.length,\n });\n } catch (e) {\n failCount++;\n console.log(pc.red(`ERROR - ${file}: ${(e as Error).message}`));\n }\n }\n\n // Display summary\n console.log(pc.bold('\\n=== Validation Summary ===\\n'));\n console.log(pc.green(`โ
Passed (โฅ70): ${passCount}`));\n console.log(pc.red(`โ Failed (<70): ${failCount}`));\n\n const avgScore =\n results.reduce((sum, r) => sum + r.score, 0) / results.length;\n console.log(pc.cyan(`๐ Average Score: ${Math.round(avgScore)}/100`));\n\n telemetry.track({\n type: 'summary',\n files: results.length,\n pass: passCount,\n fail: failCount,\n averageScore: Math.round(avgScore),\n });\n\n if (failCount === 0 && avgScore >= 80) {\n console.log(pc.green('\\nโจ All instruction files meet quality standards!'));\n } else if (failCount > 0) {\n console.log(\n pc.yellow(\n `\\nโ ๏ธ ${failCount} file(s) need improvement. Run with --verbose for details.`,\n ),\n );\n }\n}\n\nfunction getQualityGrade(score: number): string {\n if (score >= 90) return 'A';\n if (score >= 80) return 'B';\n if (score >= 70) return 'C';\n if (score >= 60) return 'D';\n return 'F';\n}\n","#!/usr/bin/env node\n\nimport { readFileSync } from 'node:fs';\nimport { realpathSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { clean } from './commands/clean';\nimport { init } from './commands/init';\nimport { list } from './commands/list';\nimport { pluginsCommand } from './commands/plugins';\nimport { refresh } from './commands/refresh';\nimport { run } from './commands/run';\nimport { validate } from './commands/validate';\n\n// This is the main entry point for the CLI tool.\n// It uses 'commander' to set up sub-commands: 'init' and 'run'.\n\n// Read version from package.json\nfunction getVersion(): string {\n try {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const packageJsonPath = join(__dirname, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return packageJson.version;\n } catch (_error) {\n return '2.0.0-beta.1'; // Fallback version\n }\n}\n\nasync function main() {\n try {\n const program = new Command();\n\n program\n .name('magic-helix')\n .description(\n 'Magic Helix CLI for aligning AI instructions in your monorepo.',\n )\n .version(getVersion());\n\n program\n .command('init')\n .description(\n 'Initialize a custom magic-helix.config.json to extend the built-in rules.',\n )\n .action(init);\n\n program\n .command('run')\n .description(\n 'Scan the monorepo and generate AI instruction files based on built-in and custom rules.',\n )\n .option(\n '--dry-run',\n 'Preview what would be generated without writing files',\n )\n .option('--force', 'Overwrite files and prune without prompting')\n .option('--skip-pruning', \"Don't ask to remove old files\")\n .option('--output-dir <path>', 'Custom output directory')\n .option('--config <path>', 'Path to custom config file')\n .option(\n '--target <assistant>',\n 'AI assistant target (github-copilot, claude, copilot-chat, generic)',\n )\n .option('--verbose', 'Show detailed output')\n .option('--quiet', 'Show minimal output')\n .option('--project <name>', 'Target a specific project only')\n .option('--wizard', 'Run in interactive wizard mode')\n .option(\n '--template <pattern>',\n \"Filter templates by pattern (e.g., 'react,vue')\",\n )\n .option(\n '--exclude <pattern>',\n \"Exclude files matching pattern (e.g., 'test/**,*.spec.ts')\",\n )\n .action(run);\n\n program\n .command('refresh')\n .description(\n 'Rescan the project and update existing instruction files with changed project information.',\n )\n .alias('resync')\n .option('--config <path>', 'Path to custom config file')\n .option(\n '--target <assistant>',\n 'AI assistant target (github-copilot, claude, copilot-chat, generic)',\n )\n .option('--verbose', 'Show detailed output')\n .option('--quiet', 'Show minimal output')\n .option('--project <name>', 'Target a specific project only')\n .action(refresh);\n\n program\n .command('list')\n .description(\n 'Show detected projects, tags, and templates without generating files.',\n )\n .action(list);\n\n program\n .command('validate')\n .description('Check instruction files for common issues and integrity.')\n .action(validate);\n\n program\n .command('clean')\n .description('Remove all generated instruction files.')\n .action(clean);\n\n program\n .command('plugins')\n .description(\n 'List available language detection plugins and their status.',\n )\n .option('--verbose', 'Show detailed plugin information')\n .action((options) => pluginsCommand(options));\n\n // Set 'run' as the default command if no other command is specified\n if (process.argv.length < 3) {\n program.action(run);\n }\n\n await program.parseAsync(process.argv);\n } catch (err) {\n console.error(\n pc.red(`โ An unexpected error occurred: ${(err as Error).message}`),\n );\n process.exit(1);\n }\n}\n\n// Check if this module is being run directly\n// Works correctly even when executed via npm bin symlinks\nconst modulePath = fileURLToPath(import.meta.url);\nconst scriptPath = process.argv[1]\n ? realpathSync(resolve(process.argv[1]))\n : null;\n\nif (scriptPath && modulePath === scriptPath) {\n main();\n}\n\n// Export main for testing\nexport { main };\n"],"names":["clean","pc","spinner","ora","userConfig","loadUserConfig","config","mergeConfigs","targetDir","path","fs","files","f","file","confirm","inquirer","deleteSpinner","deleteCount","errorCount","e","CONFIG_FILENAME","DEFAULT_TEMPLATE_DIR","MINIMAL_USER_CONFIG","init","configPath","templatePath","overwrite","exampleTemplatePath","gradient","list","dependencyTagMap","configFileTagMap","fileGlobTagMap","tagTemplateMap","projectSpinner","projects","findProjects","analyzeSpinner","project","analyzeProject","templates","tag","tagTemplates","t","rootPath","registry","PluginRegistry","detectedProjects","r","proj","relativePath","depMap","configMap","globMap","projectRoot","projectMetadata","dep","baseName","glob","pattern","pluginsCommand","options","plugins","stats","sortedPlugins","a","b","plugin","priorityColor","tagMap","errors","error","TAG_FILE_EXTENSIONS","getFileExtensionsForTag","buildPreciseGlobPattern","projectPath","tags","excludePattern","allExtensions","exts","ext","extList","excludePatterns","p","exclude","getLogLevel","shouldLog","messageLevel","logLevel","refresh","mainSpinner","userTemplateDir","formatter","getFormatter","totalTags","updatedCount","skippedCount","globPattern","outputFilename","outputPath","templateContent","readTemplate","source","header","formattedContent","fullContent","dir","templateFile","runWizard","answers","run","effectiveOptions","ensureTargetDir","filteredTagTemplateMap","templatePatterns","filteredTemplates","template","regex","pluginTemplateMap","getPluginTemplates","combinedTemplateMap","generateSpinner","generatedFiles","processedProjects","totalTemplates","pruneOldFiles","ensureRegistryInitialized","map","maybeTemplates","tmpl","suffix","content","result","sanitizeProjectName","name","sanitized","force","oldFiles","prune","validate","telemetry","coreExports","createTelemetry","passCount","failCount","results","filePath","quality","validateInstructions","grade","getQualityGrade","scoreColor","avgScore","sum","score","getVersion","__filename","fileURLToPath","__dirname","dirname","packageJsonPath","join","readFileSync","main","program","Command","err","modulePath","scriptPath","realpathSync","resolve"],"mappings":";;;;;;;;;;;;;AAWA,eAAsBA,KAAQ;AAC5B,UAAQ,IAAIC,EAAG,KAAK;AAAA,CAA8C,CAAC;AAEnE,QAAMC,IAAUC,EAAI,0BAA0B,EAAE,MAAA,GAG1CC,IAAaC,EAAA,GACbC,IAASC,EAAaH,CAAU;AACtC,EAAAF,EAAQ,QAAQ,uB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A,EAED,OAAOtD,CAAG,GAEbsD,EACG,QAAQ,SAAS,EACjB;AAAA,MACC;AAAA,IAAA,EAED,MAAM,QAAQ,EACd,OAAO,mBAAmB,4BAA4B,EACtD;AAAA,MACC;AAAA,MACA;AAAA,IAAA,EAED,OAAO,aAAa,sBAAsB,EAC1C,OAAO,WAAW,qBAAqB,EACvC,OAAO,oBAAoB,gCAAgC,EAC3D,OAAO3E,EAAO,GAEjB2E,EACG,QAAQ,MAAM,EACd;AAAA,MACC;AAAA,IAAA,EAED,OAAOvI,EAAI,GAEduI,EACG,QAAQ,UAAU,EAClB,YAAY,0DAA0D,EACtE,OAAOzB,EAAQ,GAElByB,EACG,QAAQ,OAAO,EACf,YAAY,yCAAyC,EACrD,OAAOpK,EAAK,GAEfoK,EACG,QAAQ,SAAS,EACjB;AAAA,MACC;AAAA,IAAA,EAED,OAAO,aAAa,kCAAkC,EACtD,OAAO,CAACvG,MAAYD,GAAeC,CAAO,CAAC,GAG1C,QAAQ,KAAK,SAAS,KACxBuG,EAAQ,OAAOtD,CAAG,GAGpB,MAAMsD,EAAQ,WAAW,QAAQ,IAAI;AAAA,EACvC,SAASE,GAAK;AACZ,YAAQ;AAAA,MACNrK,EAAG,IAAI,mCAAoCqK,EAAc,OAAO,EAAE;AAAA,IAAA,GAEpE,QAAQ,KAAK,CAAC;AAAA,EAChB;AACF;AAIA,MAAMC,KAAaV,EAAc,YAAY,GAAG,GAC1CW,IAAa,QAAQ,KAAK,CAAC,IAC7BC,GAAaC,GAAQ,QAAQ,KAAK,CAAC,CAAC,CAAC,IACrC;AAEAF,KAAcD,OAAeC,KAC/BL,GAAA;"}
|
|
1
|
+
{"version":3,"file":"cli.mjs","sources":["../src/commands/clean.ts","../src/commands/init.ts","../src/commands/list.ts","../src/commands/plugins.ts","../src/utils/file-extensions.ts","../src/utils/cli-options.ts","../src/commands/refresh.ts","../src/commands/run.ts","../src/commands/validate.ts","../src/cli.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport { loadUserConfig, mergeConfigs } from '@el-j/magic-helix-core';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'clean' command.\n * Removes all generated instruction files.\n */\nexport async function clean() {\n console.log(pc.cyan('๐งน Cleaning generated instruction files...\\n'));\n\n const spinner = ora('Loading configuration...').start();\n\n // Load config to find output directory\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Check if directory exists\n if (!fs.existsSync(targetDir)) {\n console.log(\n pc.yellow(\n `โ ๏ธ Output directory ${config.outputDirectory} does not exist. Nothing to clean.`,\n ),\n );\n return;\n }\n\n // Find all .md files\n const files = fs.readdirSync(targetDir).filter((f) => f.endsWith('.md'));\n\n if (files.length === 0) {\n console.log(pc.gray('No instruction files found. Nothing to clean.'));\n return;\n }\n\n // Show files and ask for confirmation\n console.log(\n pc.yellow(`Found ${files.length} instruction file(s) to delete:\\n`),\n );\n for (const file of files) {\n console.log(pc.gray(` - ${file}`));\n }\n console.log();\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: pc.red(\n `Are you sure you want to delete all ${files.length} file(s)?`,\n ),\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(pc.yellow('Clean cancelled.'));\n return;\n }\n\n // Delete files\n const deleteSpinner = ora('Deleting files...').start();\n let deleteCount = 0;\n let errorCount = 0;\n\n for (const file of files) {\n try {\n fs.unlinkSync(path.join(targetDir, file));\n deleteCount++;\n } catch (e) {\n console.error(\n pc.red(` โ Error deleting ${file}: ${(e as Error).message}`),\n );\n errorCount++;\n }\n }\n\n if (errorCount === 0) {\n deleteSpinner.succeed(\n pc.green(`โ
Successfully deleted ${deleteCount} file(s).`),\n );\n } else {\n deleteSpinner.warn(\n pc.yellow(\n `โ ๏ธ Deleted ${deleteCount} file(s), ${errorCount} error(s) occurred.`,\n ),\n );\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type { Config } from '@el-j/magic-helix-core';\nimport gradient from 'gradient-string';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n// --- CONFIGURATION ---\nconst CONFIG_FILENAME = 'magic-helix.config.json';\nconst DEFAULT_TEMPLATE_DIR = 'ai_templates';\n\n// This is the *minimal* config file 'init' will create.\n// It's designed for users who want to *extend* the built-in rules.\nconst MINIMAL_USER_CONFIG: Config = {\n target: 'github-copilot',\n templateDirectory: DEFAULT_TEMPLATE_DIR,\n outputDirectory: '.github/instructions',\n dependencyTagMap: {\n // \"my-internal-package\": \"domain-my-rules\"\n },\n configFileTagMap: {\n // \"my-custom-config.json\": \"domain-my-rules\"\n },\n fileGlobTagMap: {\n // \"src/specific-folder/**/*.ts\": \"domain-my-rules\"\n },\n tagTemplateMap: {\n // \"domain-my-rules\": [\n // { \"template\": \"my-custom-rule.md\", \"suffix\": \"my-rule.md\" }\n // ]\n },\n};\n\n/**\n * The 'init' command.\n * Creates a minimal config file and template directory\n * for users who want to *extend* the built-in conventions.\n */\nexport async function init() {\n const spinner = ora(\n pc.bold('Initializing Magic Helix for custom rules...'),\n ).start();\n\n const configPath = path.resolve(process.cwd(), CONFIG_FILENAME);\n const templatePath = path.resolve(process.cwd(), DEFAULT_TEMPLATE_DIR);\n\n // Check if config file already exists\n if (fs.existsSync(configPath)) {\n spinner.stop();\n const { overwrite } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'overwrite',\n message: `A ${CONFIG_FILENAME} file already exists. Do you want to overwrite it with a minimal example?`,\n default: false,\n },\n ]);\n if (!overwrite) {\n spinner.warn(pc.yellow('Operation cancelled.'));\n return;\n }\n spinner.start('Overwriting existing config...');\n }\n\n // 1. Write the minimal config file\n try {\n fs.writeFileSync(\n configPath,\n JSON.stringify(MINIMAL_USER_CONFIG, null, 2),\n 'utf-8',\n );\n spinner.succeed(\n pc.green(`Created minimal config file: ${pc.bold(CONFIG_FILENAME)}`),\n );\n } catch (e) {\n spinner.fail(pc.red(`Error writing config file: ${(e as Error).message}`));\n return;\n }\n\n spinner.start('Creating templates directory...');\n\n // 2. Create the templates directory\n if (!fs.existsSync(templatePath)) {\n fs.mkdirSync(templatePath, { recursive: true });\n }\n\n // 3. Copy *one* example file to show them how it works\n const exampleTemplatePath = path.resolve(templatePath, 'my-custom-rule.md');\n if (!fs.existsSync(exampleTemplatePath)) {\n fs.writeFileSync(\n exampleTemplatePath,\n '# My Team\\'s Custom Rule\\n- This rule is specific to our \"domain-my-rules\" tag.\\n- ALWAYS follow this important pattern.\\n',\n 'utf-8',\n );\n spinner.succeed(\n pc.green(\n `Created templates directory and example file: ${pc.bold(DEFAULT_TEMPLATE_DIR)}`,\n ),\n );\n } else {\n spinner.succeed(\n pc.green(\n `Templates directory ${pc.bold(DEFAULT_TEMPLATE_DIR)} already exists.`,\n ),\n );\n }\n\n console.log(\n gradient.pastel.multiline(\n '\\nโจ Success! Your project is ready for custom rules. โจ',\n ),\n );\n console.log(pc.cyan('\\nNext steps:'));\n console.log(\n ` 1. Edit ${pc.bold(CONFIG_FILENAME)} to define your team's \"tags\".`,\n );\n console.log(\n ` 2. Add your custom .md instruction files to ${pc.bold(DEFAULT_TEMPLATE_DIR)}.`,\n );\n console.log(\n ` 3. Run ${pc.bold('npx @el-j/magic-agent-helix run')} to generate your files.`,\n );\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n} from '@el-j/magic-helix-core';\nimport {\n PluginRegistry,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'list' command.\n * Shows detected projects, tags, and templates without generating files.\n */\nexport async function list() {\n console.log(pc.cyan('๐ Listing project information...\\n'));\n\n const spinner = ora('Loading configuration...').start();\n\n // 1. Load Configs\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n // 2. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(pc.yellow('No projects found.'));\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 3. Analyze projects\n const analyzeSpinner = ora('Analyzing projects...').start();\n for (const project of projects) {\n await analyzeProject(\n project,\n dependencyTagMap,\n configFileTagMap,\n fileGlobTagMap,\n );\n }\n analyzeSpinner.succeed('Analysis complete.\\n');\n\n // 4. Display results\n console.log(pc.cyan(pc.bold('Projects & Tags:\\n')));\n\n for (const project of projects) {\n console.log(pc.bold(`๐ฆ ${project.name}`));\n console.log(pc.gray(` Path: ${project.path}`));\n\n if (project.tags.size === 0) {\n console.log(pc.yellow(' No tags detected'));\n } else {\n console.log(pc.green(` Tags: ${[...project.tags].join(', ')}`));\n\n // Show which templates would be applied\n const templates: string[] = [];\n for (const tag of project.tags) {\n const tagTemplates = tagTemplateMap[tag];\n if (tagTemplates) {\n for (const t of tagTemplates) {\n templates.push(`${project.name}.${t.suffix}`);\n }\n }\n }\n\n if (templates.length > 0) {\n console.log(pc.gray(` Would generate: ${templates.join(', ')}`));\n }\n }\n console.log(); // Empty line\n }\n\n // 5. Show configuration summary\n console.log(pc.cyan(pc.bold('Configuration:\\n')));\n console.log(pc.gray(` Output directory: ${config.outputDirectory}`));\n console.log(pc.gray(` Template directory: ${config.templateDirectory}`));\n console.log(pc.gray(` Target: ${config.target}`));\n}\n\n// --- HELPER FUNCTIONS ---\n\ninterface Project {\n name: string;\n path: string;\n tags: Set<string>;\n}\n\nasync function findProjects(): Promise<Project[]> {\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Use the new polyglot detection\n const registry = PluginRegistry.getInstance();\n await registry.initialize();\n const detectedResults = await registry.detectAllProjects(rootPath);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const proj of detectedProjects) {\n const relativePath = path.relative(rootPath, proj.projectPath);\n projects.push({\n name: proj.name || path.basename(proj.projectPath),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedResults = await registry.detectAllProjects(projectRoot);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0]; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (_e) {\n // Skip errors\n }\n\n // Analyze config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (_e) {\n // Skip errors\n }\n\n // Analyze file globs\n try {\n const { glob } = await import('glob');\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true,\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (_e) {\n // Skip errors\n }\n}\n","import { PluginRegistry } from '@el-j/magic-helix-core';\nimport pc from 'picocolors';\n\ninterface PluginsOptions {\n verbose?: boolean;\n}\n\nexport async function pluginsCommand(\n options: PluginsOptions = {},\n): Promise<void> {\n console.log(pc.blue('๐ MagicAgentHelix Plugin System'));\n console.log();\n\n try {\n const registry = PluginRegistry.getInstance();\n await registry.initialize({ verbose: options.verbose });\n\n const plugins = await registry.getAllPlugins();\n const stats = registry.getStatistics();\n\n if (plugins.length === 0) {\n console.log(pc.yellow('โ ๏ธ No plugins loaded'));\n return;\n }\n\n console.log(pc.green(`โ
${plugins.length} plugin(s) loaded successfully`));\n console.log();\n\n // Display plugins grouped by priority\n const sortedPlugins = plugins.sort((a, b) => b.priority - a.priority);\n\n console.log(pc.bold('Available Language Plugins:'));\n console.log('โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ');\n\n for (const plugin of sortedPlugins) {\n const priorityColor =\n plugin.priority >= 90\n ? 'green'\n : plugin.priority >= 70\n ? 'yellow'\n : 'cyan';\n\n console.log(\n `${pc.bold(plugin.displayName)} (${pc[priorityColor](`priority: ${plugin.priority}`)}) v${plugin.version}`,\n );\n\n if (options.verbose) {\n const templates = plugin.getTemplates();\n if (templates.length > 0) {\n console.log(\n ` ๐ Templates: ${templates.map((t) => t.name).join(', ')}`,\n );\n }\n\n const tagMap = plugin.getDependencyTagMap?.();\n if (tagMap && Object.keys(tagMap).length > 0) {\n console.log(\n ` ๐ท๏ธ Detects: ${Object.keys(tagMap).slice(0, 3).join(', ')}${Object.keys(tagMap).length > 3 ? '...' : ''}`,\n );\n }\n console.log();\n }\n }\n\n if (!options.verbose) {\n console.log();\n console.log(pc.dim('๐ก Use --verbose for detailed plugin information'));\n }\n\n console.log();\n console.log(pc.bold('System Statistics:'));\n console.log('โโโโโโโโโโโโโโโโโโ');\n console.log(`๐ Total plugins: ${stats.totalLoaded}`);\n console.log(`โก Average load time: ${stats.averageLoadTime.toFixed(1)}ms`);\n console.log(`โ Load errors: ${stats.totalErrors}`);\n\n if (stats.totalErrors > 0 && options.verbose) {\n const errors = registry.getLoadErrors();\n console.log();\n console.log(pc.red('Load Errors:'));\n console.log('โโโโโโโโโโโโ');\n for (const error of errors) {\n console.log(`โ ${error.source.identifier}: ${error.error.message}`);\n }\n }\n } catch (error) {\n console.error(\n pc.red('โ Failed to load plugin registry:'),\n (error as Error).message,\n );\n process.exit(1);\n }\n}\n","/**\n * Utilities for mapping tags to appropriate file extensions\n */\n\nexport interface FileExtensionMapping {\n extensions: string[];\n description: string;\n}\n\n/**\n * Maps tags to their associated file extensions\n */\nexport const TAG_FILE_EXTENSIONS: Record<string, FileExtensionMapping> = {\n // Frameworks\n 'framework-vue': {\n extensions: ['vue'],\n description: 'Vue components',\n },\n 'framework-react': {\n extensions: ['tsx', 'jsx', 'ts', 'js'],\n description: 'React components',\n },\n 'framework-angular': {\n extensions: ['ts'],\n description: 'Angular components',\n },\n 'framework-nestjs': {\n extensions: ['ts'],\n description: 'NestJS controllers and services',\n },\n\n // Languages\n 'lang-typescript': {\n extensions: ['ts', 'tsx'],\n description: 'TypeScript files',\n },\n 'lang-javascript': {\n extensions: ['js', 'jsx'],\n description: 'JavaScript files',\n },\n 'lang-go': {\n extensions: ['go'],\n description: 'Go files',\n },\n 'lang-python': {\n extensions: ['py'],\n description: 'Python files',\n },\n 'lang-rust': {\n extensions: ['rs'],\n description: 'Rust files',\n },\n 'rust-embedded': {\n extensions: ['rs'],\n description: 'Embedded Rust files',\n },\n hardware2rust: {\n extensions: ['rs'],\n description: 'Hardware2Rust project files',\n },\n 'lang-java': {\n extensions: ['java'],\n description: 'Java files',\n },\n 'lang-swift': {\n extensions: ['swift'],\n description: 'Swift files',\n },\n 'lang-ruby': {\n extensions: ['rb'],\n description: 'Ruby files',\n },\n 'lang-php': {\n extensions: ['php'],\n description: 'PHP files',\n },\n 'lang-csharp': {\n extensions: ['cs'],\n description: 'C# files',\n },\n 'lang-cpp': {\n extensions: ['cpp', 'hpp', 'cc', 'h', 'cxx', 'hxx'],\n description: 'C++ files',\n },\n 'lang-c': {\n extensions: ['c', 'h'],\n description: 'C files',\n },\n 'lang-kotlin': {\n extensions: ['kt', 'kts'],\n description: 'Kotlin files',\n },\n 'lang-scala': {\n extensions: ['scala', 'sc'],\n description: 'Scala files',\n },\n\n // Styling\n 'style-tailwind': {\n extensions: ['ts', 'tsx', 'js', 'jsx', 'vue'],\n description: 'Files using Tailwind CSS',\n },\n 'style-primevue': {\n extensions: ['vue'],\n description: 'Vue files with PrimeVue',\n },\n 'style-mui': {\n extensions: ['tsx', 'jsx'],\n description: 'React files with Material UI',\n },\n\n // Testing\n 'test-vitest': {\n extensions: ['test.ts', 'test.tsx', 'spec.ts', 'spec.tsx'],\n description: 'Vitest test files',\n },\n 'test-jest': {\n extensions: [\n 'test.ts',\n 'test.tsx',\n 'test.js',\n 'test.jsx',\n 'spec.ts',\n 'spec.tsx',\n 'spec.js',\n 'spec.jsx',\n ],\n description: 'Jest test files',\n },\n 'test-cypress': {\n extensions: ['cy.ts', 'cy.js'],\n description: 'Cypress test files',\n },\n 'test-playwright': {\n extensions: ['spec.ts', 'spec.js'],\n description: 'Playwright test files',\n },\n\n // State management\n 'state-rxjs': {\n extensions: ['ts', 'tsx'],\n description: 'Files using RxJS',\n },\n 'state-pinia': {\n extensions: ['ts', 'vue'],\n description: 'Vue files with Pinia',\n },\n 'state-redux': {\n extensions: ['ts', 'tsx', 'js', 'jsx'],\n description: 'Files using Redux',\n },\n 'state-zustand': {\n extensions: ['ts', 'tsx', 'js', 'jsx'],\n description: 'Files using Zustand',\n },\n};\n\n/**\n * Get file extensions for a given tag\n */\nexport function getFileExtensionsForTag(tag: string): string[] {\n return TAG_FILE_EXTENSIONS[tag]?.extensions || [];\n}\n\n/**\n * Build a precise glob pattern based on project path and tags\n */\nexport function buildPreciseGlobPattern(\n projectPath: string,\n tags: Set<string>,\n excludePattern?: string,\n): string {\n const allExtensions = new Set<string>();\n\n // Collect all extensions from all tags\n for (const tag of tags) {\n const exts = getFileExtensionsForTag(tag);\n for (const ext of exts) {\n allExtensions.add(ext);\n }\n }\n\n // Fallback to common extensions if no tags matched\n if (allExtensions.size === 0) {\n return `${projectPath}/src/**/*.{ts,js,vue,tsx,jsx}`;\n }\n\n // Build pattern\n const extList = Array.from(allExtensions).join(',');\n let pattern = `${projectPath}/src/**/*.{${extList}}`;\n\n // Add exclude pattern if provided\n if (excludePattern) {\n // Convert exclude pattern to glob negation\n const excludePatterns = excludePattern.split(',').map((p) => p.trim());\n for (const exclude of excludePatterns) {\n // Handle directory exclusions\n if (exclude.endsWith('/**')) {\n pattern += ` !(${projectPath}/src/${exclude})`;\n } else if (exclude.includes('*')) {\n pattern += ` !(${projectPath}/src/${exclude})`;\n } else {\n // Exact file match\n pattern += ` !(${projectPath}/src/${exclude})`;\n }\n }\n }\n\n return pattern;\n}\n\n/**\n * Get a human-readable description of what file types apply\n */\nexport function getApplyToDescription(tags: Set<string>): string {\n const descriptions: string[] = [];\n\n for (const tag of tags) {\n const mapping = TAG_FILE_EXTENSIONS[tag];\n if (mapping) {\n descriptions.push(mapping.description);\n }\n }\n\n return descriptions.length > 0 ? descriptions.join(', ') : 'Source files';\n}\n","/**\n * Shared CLI options and types\n */\n\nexport interface CliOptions {\n dryRun?: boolean;\n force?: boolean;\n skipPruning?: boolean;\n outputDir?: string;\n config?: string;\n target?: 'github-copilot' | 'claude' | 'copilot-chat' | 'generic';\n verbose?: boolean;\n quiet?: boolean;\n project?: string;\n wizard?: boolean;\n template?: string;\n exclude?: string;\n}\n\n/**\n * Log level based on options\n */\nexport function getLogLevel(\n options: CliOptions,\n): 'verbose' | 'normal' | 'quiet' {\n if (options.quiet) return 'quiet';\n if (options.verbose) return 'verbose';\n return 'normal';\n}\n\n/**\n * Should we log this message at this level?\n */\nexport function shouldLog(\n messageLevel: 'verbose' | 'normal' | 'error',\n logLevel: 'verbose' | 'normal' | 'quiet',\n): boolean {\n if (logLevel === 'quiet' && messageLevel !== 'error') return false;\n if (logLevel === 'normal' && messageLevel === 'verbose') return false;\n return true;\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n TagTemplateMap,\n} from '@el-j/magic-helix-core';\nimport {\n type AssistantTarget,\n getFormatter,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport { PluginRegistry } from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\nimport { buildPreciseGlobPattern } from '../utils/file-extensions';\n\n// --- TYPES ---\ninterface Project {\n name: string;\n path: string;\n tags: Set<string>;\n}\n\nimport type { CliOptions } from '../utils/cli-options';\nimport { getLogLevel } from '../utils/cli-options';\n\n/**\n * The 'refresh' command.\n * Rescans the project and updates existing instruction files with new information.\n */\nexport async function refresh(options: CliOptions = {}) {\n const _logLevel = getLogLevel(options);\n\n const mainSpinner = ora('Loading configurations...').start();\n\n // 1. Load Configs\n const userConfig = loadUserConfig(options.config);\n const config = mergeConfigs(userConfig);\n\n // Override target if specified\n if (options.target) {\n config.target = options.target;\n }\n\n mainSpinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n const userTemplateDir = path.resolve(\n process.cwd(),\n config.templateDirectory as string,\n );\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Get the formatter for the target assistant\n const formatter = getFormatter(config.target as AssistantTarget);\n\n // 2. Check if target directory exists\n if (!fs.existsSync(targetDir)) {\n console.log(\n pc.yellow(\n `โ ๏ธ Output directory ${config.outputDirectory} does not exist.`,\n ),\n );\n console.log(\n pc.gray(` Run 'magic-helix run' first to generate instruction files.`),\n );\n return;\n }\n\n // 3. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(\n pc.yellow(\n 'No projects found. Make sure your root package.json has a \"workspaces\" field.',\n ),\n );\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 4. Analyze dependencies and tag projects\n const analyzeSpinner = ora('Analyzing project tags...').start();\n let totalTags = 0;\n for (const project of projects) {\n await analyzeProject(\n project,\n dependencyTagMap as DependencyTagMap,\n configFileTagMap as ConfigFileTagMap,\n fileGlobTagMap as FileGlobTagMap,\n );\n totalTags += project.tags.size;\n }\n analyzeSpinner.succeed(`Project analysis complete. Found ${totalTags} tags.`);\n\n // 5. Update existing instruction files\n console.log(\n pc.cyan(`\\nRefreshing instruction files in ${config.outputDirectory}...`),\n );\n\n let updatedCount = 0;\n let skippedCount = 0;\n\n for (const project of projects) {\n if (project.tags.size === 0) {\n console.log(pc.gray(` Skipping: ${project.name} (No matching tags)`));\n skippedCount++;\n continue;\n }\n\n console.log(pc.bold(` Processing: ${project.name}`));\n console.log(pc.gray(` Tags: ${[...project.tags].join(', ')}`));\n\n const globPattern = buildPreciseGlobPattern(project.path, project.tags);\n\n for (const tag of project.tags) {\n const templates = (tagTemplateMap as TagTemplateMap)[tag];\n if (!templates) continue;\n\n for (const t of templates) {\n const outputFilename = `${project.name}.${t.suffix}`;\n const outputPath = path.join(targetDir, outputFilename);\n\n // Check if file exists\n if (!fs.existsSync(outputPath)) {\n console.log(\n pc.yellow(` โ ๏ธ File not found, skipping: ${outputFilename}`),\n );\n continue;\n }\n\n // Read template from user custom directory\n const templateContent = readTemplate(userTemplateDir, t.template);\n const source = 'Custom';\n\n if (!templateContent) {\n console.warn(pc.yellow(` โ ๏ธ Template not found: ${t.template}`));\n continue;\n }\n\n // Update header with new information\n const header = formatter.getFrontmatter(globPattern, project.name);\n const formattedContent = formatter.format(\n templateContent,\n globPattern,\n project.name,\n );\n const fullContent = `${header}\\n${formattedContent}`;\n\n // Write updated file\n fs.writeFileSync(outputPath, fullContent);\n updatedCount++;\n console.log(\n pc.green(\n ` โ
Refreshed: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n }\n }\n\n console.log('\\nโจ Refresh complete!');\n console.log(pc.green(` Updated: ${updatedCount} files`));\n console.log(pc.gray(` Skipped: ${skippedCount} projects`));\n}\n\n// --- HELPER FUNCTIONS ---\n\nasync function findProjects(): Promise<Project[]> {\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Use the new polyglot detection\n const registry = PluginRegistry.getInstance();\n await registry.initialize();\n const detectedResults = await registry.detectAllProjects(rootPath);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const proj of detectedProjects) {\n const relativePath = path.relative(rootPath, proj.projectPath);\n projects.push({\n name: proj.name || path.basename(proj.projectPath),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Strategy 1: Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedResults = await registry.detectAllProjects(projectRoot);\n const detectedProjects = detectedResults.map((r) => r.metadata);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0]; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Could not analyze dependencies for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 2: Analyze key config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning config files for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 3: Analyze file globs\n try {\n const { glob } = await import('glob');\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true,\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning file globs for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n}\n\nfunction readTemplate(dir: string, templateFile: string): string | null {\n const p = path.join(dir, templateFile);\n try {\n return fs.readFileSync(p, 'utf-8');\n } catch (_e) {\n return null;\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport type {\n ConfigFileTagMap,\n DependencyTagMap,\n FileGlobTagMap,\n LanguagePlugin,\n TagTemplateMap,\n} from '@el-j/magic-helix-core';\nimport {\n type AssistantTarget,\n PluginRegistry,\n type TemplateDefinition,\n getFormatter,\n loadUserConfig,\n mergeConfigs,\n} from '@el-j/magic-helix-core';\nimport { glob } from 'glob';\nimport gradient from 'gradient-string';\nimport inquirer from 'inquirer';\nimport ora from 'ora';\nimport pc from 'picocolors';\nimport type { CliOptions } from '../utils/cli-options';\nimport { getLogLevel, shouldLog } from '../utils/cli-options';\nimport { buildPreciseGlobPattern } from '../utils/file-extensions';\n\n// --- TYPES ---\ninterface Project {\n name: string; // Sanitized package name, e.g., 'scope-my-app'\n path: string; // Relative path from root, e.g., 'packages/my-app'\n tags: Set<string>;\n}\n\ntype TemplateSource = {\n template: string;\n suffix: string;\n inlineContent?: string;\n};\n\n/**\n * Interactive wizard to guide users through configuration options\n */\nasync function runWizard(): Promise<Partial<CliOptions>> {\n console.log(\n gradient.pastel.multiline('๐ค MagicAgentHelix Interactive Setup Wizard'),\n );\n console.log(\"Let's configure your AI instruction generation...\\n\");\n\n const answers = await inquirer.prompt([\n {\n type: 'list',\n name: 'target',\n message: 'Which AI assistant are you using?',\n choices: [\n { name: 'GitHub Copilot', value: 'github-copilot' },\n { name: 'Claude/Cursor', value: 'claude' },\n { name: 'GitHub Copilot Chat', value: 'copilot-chat' },\n { name: 'Generic Assistant', value: 'generic' },\n ],\n default: 'github-copilot',\n },\n {\n type: 'confirm',\n name: 'dryRun',\n message:\n 'Would you like to preview what would be generated first (dry run)?',\n default: true,\n },\n {\n type: 'input',\n name: 'outputDir',\n message: 'Where should the instruction files be generated?',\n default: '.ai',\n when: (answers) => !answers.dryRun,\n },\n {\n type: 'confirm',\n name: 'force',\n message: 'Overwrite existing files without prompting?',\n default: false,\n when: (answers) => !answers.dryRun,\n },\n {\n type: 'list',\n name: 'verbosity',\n message: 'How much output would you like to see?',\n choices: [\n { name: 'Verbose (detailed information)', value: 'verbose' },\n { name: 'Normal (standard output)', value: 'normal' },\n { name: 'Quiet (minimal output)', value: 'quiet' },\n ],\n default: 'normal',\n },\n ]);\n\n // Convert verbosity to CLI options\n const options: Partial<CliOptions> = {\n target: answers.target,\n dryRun: answers.dryRun,\n };\n\n if (answers.outputDir) {\n options.outputDir = answers.outputDir;\n }\n\n if (answers.force) {\n options.force = answers.force;\n }\n\n if (answers.verbosity === 'verbose') {\n options.verbose = true;\n } else if (answers.verbosity === 'quiet') {\n options.quiet = true;\n }\n\n console.log(pc.green('\\nโ
Configuration complete! Starting analysis...\\n'));\n\n return options;\n}\n\n/**\n * The 'run' command.\n * Scans the monorepo and generates instruction files.\n */\nexport async function run(options: CliOptions = {}) {\n // Run interactive wizard if requested\n let effectiveOptions = options;\n if (options.wizard) {\n const wizardOptions = await runWizard();\n // Merge wizard options with command line options (CLI options take precedence)\n effectiveOptions = { ...wizardOptions, ...options };\n }\n\n const logLevel = getLogLevel(effectiveOptions);\n\n if (shouldLog('normal', logLevel)) {\n console.log(\n gradient.pastel.multiline('๐ค Running AI Convention Aligner...'),\n );\n }\n\n if (effectiveOptions.dryRun && shouldLog('normal', logLevel)) {\n console.log(pc.yellow('๐ DRY RUN MODE - No files will be written\\n'));\n }\n\n const mainSpinner = ora('Loading configurations...').start();\n\n // 1. Load Configs (Built-in + Optional User)\n const userConfig = loadUserConfig(effectiveOptions.config);\n const config = mergeConfigs(userConfig);\n\n // Override output directory if specified\n if (effectiveOptions.outputDir) {\n config.outputDirectory = effectiveOptions.outputDir;\n }\n\n // Override target if specified\n if (effectiveOptions.target) {\n config.target = effectiveOptions.target;\n }\n\n mainSpinner.succeed('Configuration loaded.');\n\n const { dependencyTagMap, configFileTagMap, fileGlobTagMap, tagTemplateMap } =\n config;\n\n const userTemplateDir = path.resolve(\n process.cwd(),\n config.templateDirectory as string,\n );\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Get the formatter for the target assistant\n const formatter = getFormatter(config.target as AssistantTarget);\n\n // 2. Find all projects\n const projectSpinner = ora('Scanning for projects...').start();\n const projects = await findProjects();\n if (projects.length === 0) {\n projectSpinner.warn(\n pc.yellow(\n 'No projects detected. The tool could not find any supported project types in the current directory.',\n ),\n );\n console.log(\n pc.gray(\n '\\nSupported project types: Node.js, Python, Go, Rust, Java, Ruby, PHP, C#, Swift, C/C++, PlatformIO',\n ),\n );\n console.log(\n pc.gray(\n 'For monorepos, ensure your root package.json has a \"workspaces\" field.',\n ),\n );\n console.log(\n pc.gray(\n 'For standalone projects, ensure you have the appropriate manifest file (package.json, go.mod, Cargo.toml, platformio.ini, etc.)',\n ),\n );\n return;\n }\n projectSpinner.succeed(`Found ${projects.length} projects.`);\n\n // 3. Analyze dependencies and tag projects\n const analyzeSpinner = ora('Analyzing project tags...').start();\n let totalTags = 0;\n for (const project of projects) {\n // Skip if specific project requested and this isn't it\n if (effectiveOptions.project && project.name !== effectiveOptions.project) {\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(`Skipping ${project.name} (not target project)`));\n }\n continue;\n }\n\n await analyzeProject(\n project,\n dependencyTagMap as DependencyTagMap,\n configFileTagMap as ConfigFileTagMap,\n fileGlobTagMap as FileGlobTagMap,\n );\n totalTags += project.tags.size;\n }\n analyzeSpinner.succeed(`Project analysis complete. Found ${totalTags} tags.`);\n\n // 4. Ensure target directory exists\n if (!effectiveOptions.dryRun) {\n ensureTargetDir(targetDir);\n } else if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(`Would ensure directory: ${targetDir}`));\n }\n\n // Apply template filtering if specified\n let filteredTagTemplateMap = tagTemplateMap as TagTemplateMap;\n if (effectiveOptions.template) {\n const templatePatterns = effectiveOptions.template\n .split(',')\n .map((p) => p.trim());\n filteredTagTemplateMap = {} as TagTemplateMap;\n\n for (const [tag, templates] of Object.entries(tagTemplateMap)) {\n const filteredTemplates = templates.filter((template) => {\n return templatePatterns.some((pattern) => {\n // Support wildcard matching\n if (pattern.includes('*')) {\n const regex = new RegExp(pattern.replace(/\\*/g, '.*'));\n return regex.test(template.template) || regex.test(tag);\n }\n return template.template.includes(pattern) || tag.includes(pattern);\n });\n });\n\n if (filteredTemplates.length > 0) {\n filteredTagTemplateMap[tag] = filteredTemplates;\n }\n }\n\n if (shouldLog('verbose', logLevel)) {\n console.log(\n pc.gray(`Template filter applied: ${effectiveOptions.template}`),\n );\n }\n }\n\n // Merge plugin-provided templates (inline content) with config templates\n const pluginTemplateMap = await getPluginTemplates();\n const combinedTemplateMap: Record<string, TemplateSource[]> = {};\n\n for (const [tag, templates] of Object.entries(filteredTagTemplateMap)) {\n combinedTemplateMap[tag] = templates.map((t) => ({\n template: t.template,\n suffix: t.suffix,\n }));\n }\n\n for (const [tag, templates] of Object.entries(pluginTemplateMap)) {\n if (!combinedTemplateMap[tag]) {\n combinedTemplateMap[tag] = [];\n }\n combinedTemplateMap[tag].push(...templates);\n }\n\n // Debug logging for template maps\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray('\\n--- Template Map Debug ---'));\n console.log(\n pc.gray(\n `Plugin templates: ${Object.keys(pluginTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(pluginTemplateMap).join(', ')}`),\n );\n console.log(\n pc.gray(\n `Config templates: ${Object.keys(filteredTagTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(filteredTagTemplateMap).join(', ')}`),\n );\n console.log(\n pc.gray(\n `Combined templates: ${Object.keys(combinedTemplateMap).length} tags`,\n ),\n );\n console.log(\n pc.gray(` Tags: ${Object.keys(combinedTemplateMap).join(', ')}`),\n );\n }\n\n // 5. Generate files\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.cyan(`\\nGenerating instruction files in ${config.outputDirectory}...`),\n );\n }\n const generateSpinner = ora('Generating instruction files...').start();\n const generatedFiles: string[] = [];\n let processedProjects = 0;\n let totalTemplates = 0;\n for (const project of projects) {\n // Skip if specific project requested and this isn't it\n if (effectiveOptions.project && project.name !== effectiveOptions.project) {\n continue;\n }\n\n if (project.tags.size === 0) {\n if (shouldLog('normal', logLevel)) {\n console.log(pc.gray(` Skipping: ${project.name} (No matching tags)`));\n }\n continue;\n }\n\n processedProjects++;\n if (shouldLog('normal', logLevel)) {\n console.log(pc.bold(` Processing: ${project.name}`));\n }\n if (shouldLog('verbose', logLevel)) {\n console.log(pc.gray(` Tags: ${[...project.tags].join(', ')}`));\n }\n\n const globPattern = buildPreciseGlobPattern(\n project.path,\n project.tags,\n effectiveOptions.exclude,\n );\n\n for (const tag of project.tags) {\n const templates = combinedTemplateMap[tag];\n if (!templates) continue;\n\n for (const t of templates) {\n totalTemplates++;\n // Use plugin inline content or user custom templates\n const templateContent =\n t.inlineContent ?? readTemplate(userTemplateDir, t.template);\n const source = t.inlineContent ? 'Plugin' : 'Custom';\n\n if (!templateContent) {\n console.warn(pc.yellow(` โ ๏ธ Template not found: ${t.template}`));\n continue;\n }\n\n const header = formatter.getFrontmatter(globPattern, project.name);\n const formattedContent = formatter.format(\n templateContent,\n globPattern,\n project.name,\n );\n const fullContent = `${header}\\n${formattedContent}`;\n\n // Use just the suffix as the filename (e.g., \"typescript.instructions.md\")\n // This follows GitHub Copilot's naming convention for path-specific instructions\n const outputFilename = t.suffix;\n const outputPath = path.join(targetDir, outputFilename);\n\n generatedFiles.push(outputFilename);\n\n if (effectiveOptions.dryRun) {\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.cyan(\n ` ๐ Would generate: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n } else {\n fs.writeFileSync(outputPath, fullContent);\n if (shouldLog('normal', logLevel)) {\n console.log(\n pc.green(\n ` โ
Generated: ${pc.bold(outputFilename)} (from ${source})`,\n ),\n );\n }\n }\n }\n }\n }\n\n generateSpinner.succeed(\n `Generated ${generatedFiles.length} files from ${totalTemplates} templates across ${processedProjects} projects`,\n );\n\n // 6. Pruning: Ask to remove old files\n if (!effectiveOptions.dryRun && !effectiveOptions.skipPruning) {\n await pruneOldFiles(targetDir, generatedFiles, effectiveOptions.force);\n } else if (effectiveOptions.dryRun && shouldLog('verbose', logLevel)) {\n console.log(pc.gray('\\nWould check for old files to prune...'));\n }\n\n if (shouldLog('normal', logLevel)) {\n console.log(`\\n${'โ'.repeat(60)}`);\n if (effectiveOptions.dryRun) {\n console.log(pc.cyan('โจ Dry run complete! No files were modified.'));\n console.log(\n pc.gray(\n `๐ Would have generated ${generatedFiles.length} instruction file(s)`,\n ),\n );\n console.log(\n pc.gray(\n `๐ From ${totalTemplates} template(s) across ${processedProjects} project(s)`,\n ),\n );\n } else {\n console.log(pc.green('โจ AI instruction alignment complete!'));\n console.log(\n pc.bold(`๐ Generated ${generatedFiles.length} instruction file(s)`),\n );\n console.log(\n pc.gray(\n `๐ From ${totalTemplates} template(s) across ${processedProjects} project(s)`,\n ),\n );\n console.log(\n pc.gray(`๐ Files are located in: ${pc.bold(config.outputDirectory)}`),\n );\n }\n console.log('โ'.repeat(60));\n }\n\n if (config.target === 'github-copilot' && shouldLog('normal', logLevel)) {\n console.log('\\n--- VS Code + GitHub Copilot Tip ---');\n console.log(\n \"To maximize Copilot's awareness, add this to your workspace .vscode/settings.json:\",\n );\n console.log(`\n \"github.copilot.advanced\": {\n \"instructions\": \".github/instructions\"\n }\n `);\n console.log(\n 'This tells Copilot to *always* read these files. Restart VS Code after adding.',\n );\n }\n}\n\n// --- HELPER FUNCTIONS ---\n\nfunction ensureTargetDir(targetDir: string) {\n const spinner = ora(`Checking target directory: ${targetDir}`).start();\n if (!fs.existsSync(targetDir)) {\n spinner.text = 'Target directory not found. Creating...';\n try {\n fs.mkdirSync(targetDir, { recursive: true });\n spinner.succeed(`Created ${targetDir}`);\n } catch (error) {\n spinner.fail(\n pc.red(\n `Error creating directory: ${(error as Error).message}. Please check permissions.`,\n ),\n );\n process.exit(1);\n }\n } else {\n spinner.succeed('Target directory OK.');\n }\n}\n\nasync function ensureRegistryInitialized() {\n const registry = PluginRegistry.getInstance();\n // initialize will short-circuit if already initialized\n await registry.initialize();\n}\n\nasync function getPluginTemplates(): Promise<Record<string, TemplateSource[]>> {\n await ensureRegistryInitialized();\n const registry = PluginRegistry.getInstance();\n let plugins: LanguagePlugin[] = [];\n\n try {\n // Direct method call instead of type casting\n plugins = await registry.getAllPlugins();\n } catch (e) {\n console.warn(\n pc.yellow(`โ ๏ธ Failed to get plugins: ${(e as Error).message}`),\n );\n console.warn(\n pc.yellow(\n `โ ๏ธ Registry type: ${typeof registry}, has getAllPlugins: ${typeof registry?.getAllPlugins}`,\n ),\n );\n }\n\n if (plugins.length === 0) {\n console.warn(pc.yellow('โ ๏ธ No plugins loaded from registry!'));\n }\n\n const map: Record<string, TemplateSource[]> = {};\n\n for (const plugin of plugins) {\n let templates: TemplateDefinition[] = [];\n try {\n const maybeTemplates = await plugin.getTemplates();\n templates = Array.isArray(maybeTemplates) ? maybeTemplates : [];\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Plugin ${plugin.name} getTemplates failed: ${(e as Error).message}`,\n ),\n );\n continue;\n }\n\n for (const tmpl of templates) {\n // Convert template name to suffix: 'lang-typescript' โ 'typescript.instructions.md'\n // 'react-core' โ 'react.instructions.md', etc.\n const baseName = tmpl.name.replace(/^lang-/, '').replace(/-core$/, '');\n const suffix = `${baseName}.instructions.md`;\n let content: string | null = null;\n try {\n content =\n typeof tmpl.content === 'function'\n ? await tmpl.content()\n : tmpl.content;\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Plugin ${plugin.name} template ${tmpl.name} failed to load: ${(e as Error).message}`,\n ),\n );\n }\n\n for (const tag of tmpl.tags) {\n if (!map[tag]) map[tag] = [];\n map[tag].push({\n template: `plugin:${plugin.name}/${tmpl.name}`,\n suffix,\n inlineContent: content ?? undefined,\n });\n }\n }\n }\n\n return map;\n}\n\nasync function findProjects(): Promise<Project[]> {\n await ensureRegistryInitialized();\n const projects: Project[] = [];\n const rootPath = process.cwd();\n\n // Initialize plugin registry and detect projects\n const registry = PluginRegistry.getInstance();\n const detectedProjects = await registry.detectAllProjects(rootPath);\n\n if (detectedProjects.length === 0) {\n return [];\n }\n\n for (const result of detectedProjects) {\n const relativePath = path.relative(rootPath, result.metadata.projectPath);\n projects.push({\n name: sanitizeProjectName(\n result.metadata.name || path.basename(result.metadata.projectPath),\n ),\n path: relativePath || '.',\n tags: new Set<string>(),\n });\n }\n\n return projects;\n}\n\n/**\n * Sanitize project names for filesystem-safe output filenames.\n * - Convert scoped names like \"@scope/app\" to \"scope-app\"\n * - Replace path separators and whitespace with '-'\n * - Remove leading '@'\n */\nfunction sanitizeProjectName(name: string): string {\n const trimmed = name.trim();\n // Replace slashes with dashes, remove leading '@'\n let sanitized = trimmed.replace(/^@/, '').replace(/[\\\\/\\s]+/g, '-');\n // Collapse multiple dashes\n sanitized = sanitized.replace(/-+/g, '-');\n return sanitized;\n}\n\nasync function analyzeProject(\n project: Project,\n depMap: DependencyTagMap,\n configMap: ConfigFileTagMap,\n globMap: FileGlobTagMap,\n) {\n await ensureRegistryInitialized();\n const projectRoot = path.resolve(process.cwd(), project.path);\n\n // Strategy 1: Analyze dependencies from any manifest file\n try {\n const registry = PluginRegistry.getInstance();\n const detectedProjects = await registry.detectAllProjects(projectRoot);\n if (detectedProjects.length > 0) {\n const projectMetadata = detectedProjects[0].metadata; // Use first match\n\n if (projectMetadata.tags?.length) {\n for (const tag of projectMetadata.tags) {\n project.tags.add(tag);\n }\n }\n\n for (const dep in projectMetadata.dependencies) {\n // Check both the full dependency name and the package/module name\n if (depMap[dep]) {\n project.tags.add(depMap[dep]);\n }\n\n // For scoped packages like @scope/pkg or group:artifact, try the base name too\n const baseName = dep.split(/[@/:]/g).pop();\n if (baseName && depMap[baseName]) {\n project.tags.add(depMap[baseName]);\n }\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Could not analyze dependencies for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 2: Analyze key config files\n try {\n for (const file in configMap) {\n const tag = configMap[file];\n const configPath = path.join(projectRoot, file);\n if (fs.existsSync(configPath)) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning config files for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n\n // Strategy 3: Analyze file globs\n try {\n for (const pattern in globMap) {\n const tag = globMap[pattern];\n // Use 'glob' package for async globbing\n const results = await glob(pattern, {\n cwd: projectRoot,\n nodir: true,\n dot: true, // Include dotfiles if needed, though 'src' patterns usually don't\n });\n if (results.length > 0) {\n project.tags.add(tag);\n }\n }\n } catch (e) {\n console.warn(\n pc.yellow(\n `โ ๏ธ Error scanning file globs for ${project.name}: ${(e as Error).message}`,\n ),\n );\n }\n}\n\nfunction readTemplate(dir: string, templateFile: string): string | null {\n const p = path.join(dir, templateFile);\n try {\n return fs.readFileSync(p, 'utf-8');\n } catch (_e) {\n return null; // Will be handled in the main function\n }\n}\n\nasync function pruneOldFiles(\n targetDir: string,\n generatedFiles: string[],\n force = false,\n) {\n const existingFiles = fs\n .readdirSync(targetDir)\n .filter((f) => f.endsWith('.md'));\n\n const oldFiles = existingFiles.filter((f) => !generatedFiles.includes(f));\n\n if (oldFiles.length > 0) {\n console.warn(\n pc.yellow(\n `\\nโ ๏ธ Found ${oldFiles.length} instruction files that are no longer generated:`,\n ),\n );\n for (const f of oldFiles) {\n console.warn(pc.yellow(` - ${f}`));\n }\n\n let prune = force;\n\n if (!force) {\n const answer = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'prune',\n message: `Do you want to delete these ${oldFiles.length} old files?`,\n default: false,\n },\n ]);\n prune = answer.prune;\n }\n\n if (prune) {\n let deleteCount = 0;\n for (const file of oldFiles) {\n try {\n fs.unlinkSync(path.join(targetDir, file));\n deleteCount++;\n } catch (e) {\n console.error(\n pc.red(` โ Error deleting ${file}: ${(e as Error).message}`),\n );\n }\n }\n console.log(`โ
Pruned ${deleteCount} old files.`);\n }\n }\n}\n","import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n loadUserConfig,\n mergeConfigs,\n validateInstructions,\n} from '@el-j/magic-helix-core';\nimport ora from 'ora';\nimport pc from 'picocolors';\n\n/**\n * The 'validate' command.\n * Checks instruction files for quality based on awesome-ai-system-prompts best practices.\n */\nexport async function validate() {\n console.log(\n pc.cyan('๐ Validating instruction files with quality scoring...\\n'),\n );\n\n const spinner = ora('Loading configuration...').start();\n\n // Load config\n const userConfig = loadUserConfig();\n const config = mergeConfigs(userConfig);\n spinner.succeed('Configuration loaded.');\n\n const targetDir = path.resolve(\n process.cwd(),\n config.outputDirectory as string,\n );\n\n // Check if directory exists\n if (!fs.existsSync(targetDir)) {\n spinner.fail(\n pc.red(\n `โ Output directory ${config.outputDirectory} does not exist. Run 'magic-helix run' first.`,\n ),\n );\n return;\n }\n\n // Find all .md files\n const files = fs.readdirSync(targetDir).filter((f) => f.endsWith('.md'));\n\n if (files.length === 0) {\n console.log(\n pc.yellow(\"No instruction files found. Run 'magic-helix run' first.\"),\n );\n return;\n }\n\n console.log(pc.gray(`Checking ${files.length} instruction file(s)...\\n`));\n\n // Telemetry (optional): fall back to no-op if unavailable\n let telemetry: { track: (event: unknown) => void } = { track: () => {} };\n try {\n const core = await import('@el-j/magic-helix-core');\n // Check if createTelemetry is available in the imported core module\n const coreExports = core as Record<string, unknown>;\n if (typeof coreExports.createTelemetry === 'function') {\n const createTelemetry = coreExports.createTelemetry as (\n config: Record<string, unknown>,\n ) => { track: (event: unknown) => void };\n telemetry = createTelemetry({});\n }\n } catch {\n // ignore if core import fails in test/browser\n }\n\n let passCount = 0;\n let failCount = 0;\n const results: Array<{ file: string; score: number; grade: string }> = [];\n\n for (const file of files) {\n const filePath = path.join(targetDir, file);\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n\n // Run quality validation\n const quality = validateInstructions(content);\n const grade = getQualityGrade(quality.overallScore);\n\n results.push({ file, score: quality.overallScore, grade });\n\n if (quality.overallScore >= 70) {\n passCount++;\n } else {\n failCount++;\n }\n\n // Display individual file results\n const scoreColor =\n quality.overallScore >= 90\n ? pc.green\n : quality.overallScore >= 70\n ? pc.blue\n : pc.yellow;\n\n console.log(\n scoreColor(`${grade} ${quality.overallScore}/100`) +\n pc.gray(` - ${file}`),\n );\n\n if (quality.missingElements.length > 0) {\n console.log(\n pc.red(` Missing: ${quality.missingElements.join(', ')}`),\n );\n }\n\n if (quality.recommendations.length > 0 && quality.overallScore < 90) {\n console.log(pc.gray(` Tip: ${quality.recommendations[0]}`));\n }\n\n // Track per-file validation result\n telemetry.track({\n type: 'instruction_validation',\n file,\n score: quality.overallScore,\n structureScore: quality.structureScore,\n clarityScore: quality.clarityScore,\n completenessScore: quality.completenessScore,\n missingCount: quality.missingElements.length,\n });\n } catch (e) {\n failCount++;\n console.log(pc.red(`ERROR - ${file}: ${(e as Error).message}`));\n }\n }\n\n // Display summary\n console.log(pc.bold('\\n=== Validation Summary ===\\n'));\n console.log(pc.green(`โ
Passed (โฅ70): ${passCount}`));\n console.log(pc.red(`โ Failed (<70): ${failCount}`));\n\n const avgScore =\n results.reduce((sum, r) => sum + r.score, 0) / results.length;\n console.log(pc.cyan(`๐ Average Score: ${Math.round(avgScore)}/100`));\n\n telemetry.track({\n type: 'summary',\n files: results.length,\n pass: passCount,\n fail: failCount,\n averageScore: Math.round(avgScore),\n });\n\n if (failCount === 0 && avgScore >= 80) {\n console.log(pc.green('\\nโจ All instruction files meet quality standards!'));\n } else if (failCount > 0) {\n console.log(\n pc.yellow(\n `\\nโ ๏ธ ${failCount} file(s) need improvement. Run with --verbose for details.`,\n ),\n );\n }\n}\n\nfunction getQualityGrade(score: number): string {\n if (score >= 90) return 'A';\n if (score >= 80) return 'B';\n if (score >= 70) return 'C';\n if (score >= 60) return 'D';\n return 'F';\n}\n","#!/usr/bin/env node\n\nimport { readFileSync } from 'node:fs';\nimport { realpathSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { Command } from 'commander';\nimport pc from 'picocolors';\nimport { clean } from './commands/clean';\nimport { init } from './commands/init';\nimport { list } from './commands/list';\nimport { pluginsCommand } from './commands/plugins';\nimport { refresh } from './commands/refresh';\nimport { run } from './commands/run';\nimport { validate } from './commands/validate';\n\n// This is the main entry point for the CLI tool.\n// It uses 'commander' to set up sub-commands: 'init' and 'run'.\n\n// Read version from package.json\nfunction getVersion(): string {\n try {\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const packageJsonPath = join(__dirname, '..', 'package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n return packageJson.version;\n } catch (_error) {\n return '2.0.0-beta.1'; // Fallback version\n }\n}\n\nasync function main() {\n try {\n const program = new Command();\n\n program\n .name('magic-helix')\n .description(\n 'Magic Helix CLI for aligning AI instructions in your monorepo.',\n )\n .version(getVersion());\n\n program\n .command('init')\n .description(\n 'Initialize a custom magic-helix.config.json to extend the built-in rules.',\n )\n .action(init);\n\n program\n .command('run')\n .description(\n 'Scan the monorepo and generate AI instruction files based on built-in and custom rules.',\n )\n .option(\n '--dry-run',\n 'Preview what would be generated without writing files',\n )\n .option('--force', 'Overwrite files and prune without prompting')\n .option('--skip-pruning', \"Don't ask to remove old files\")\n .option('--output-dir <path>', 'Custom output directory')\n .option('--config <path>', 'Path to custom config file')\n .option(\n '--target <assistant>',\n 'AI assistant target (github-copilot, claude, copilot-chat, generic)',\n )\n .option('--verbose', 'Show detailed output')\n .option('--quiet', 'Show minimal output')\n .option('--project <name>', 'Target a specific project only')\n .option('--wizard', 'Run in interactive wizard mode')\n .option(\n '--template <pattern>',\n \"Filter templates by pattern (e.g., 'react,vue')\",\n )\n .option(\n '--exclude <pattern>',\n \"Exclude files matching pattern (e.g., 'test/**,*.spec.ts')\",\n )\n .action(run);\n\n program\n .command('refresh')\n .description(\n 'Rescan the project and update existing instruction files with changed project information.',\n )\n .alias('resync')\n .option('--config <path>', 'Path to custom config file')\n .option(\n '--target <assistant>',\n 'AI assistant target (github-copilot, claude, copilot-chat, generic)',\n )\n .option('--verbose', 'Show detailed output')\n .option('--quiet', 'Show minimal output')\n .option('--project <name>', 'Target a specific project only')\n .action(refresh);\n\n program\n .command('list')\n .description(\n 'Show detected projects, tags, and templates without generating files.',\n )\n .action(list);\n\n program\n .command('validate')\n .description('Check instruction files for common issues and integrity.')\n .action(validate);\n\n program\n .command('clean')\n .description('Remove all generated instruction files.')\n .action(clean);\n\n program\n .command('plugins')\n .description(\n 'List available language detection plugins and their status.',\n )\n .option('--verbose', 'Show detailed plugin information')\n .action((options) => pluginsCommand(options));\n\n // Set 'run' as the default command if no other command is specified\n if (process.argv.length < 3) {\n program.action(run);\n }\n\n await program.parseAsync(process.argv);\n } catch (err) {\n console.error(\n pc.red(`โ An unexpected error occurred: ${(err as Error).message}`),\n );\n process.exit(1);\n }\n}\n\n// Check if this module is being run directly\n// Works correctly even when executed via npm bin symlinks\nconst modulePath = fileURLToPath(import.meta.url);\nconst scriptPath = process.argv[1]\n ? realpathSync(resolve(process.argv[1]))\n : null;\n\nif (scriptPath && modulePath === scriptPath) {\n main();\n}\n\n// Export main for testing\nexport { main };\n"],"names":["clean","pc","spinner","ora","userConfig","loadUserConfig","config","mergeConfigs","targetDir","path","fs","files","f","file","confirm","inquirer","deleteSpinner","deleteCount","errorCount","e","CONFIG_FILENAME","DEFAULT_TEMPLATE_DIR","MINIMAL_USER_CONFIG","init","configPath","templatePath","overwrite","exampleTemplatePath","gradient","list","dependencyTagMap","configFileTagMap","fileGlobTagMap","tagTemplateMap","projectSpinner","projects","findProjects","analyzeSpinner","project","analyzeProject","templates","tag","tagTemplates","t","rootPath","registry","PluginRegistry","detectedProjects","r","proj","relativePath","depMap","configMap","globMap","projectRoot","projectMetadata","dep","baseName","glob","pattern","pluginsCommand","options","plugins","stats","sortedPlugins","a","b","plugin","priorityColor","tagMap","errors","error","TAG_FILE_EXTENSIONS","getFileExtensionsForTag","buildPreciseGlobPattern","projectPath","tags","excludePattern","allExtensions","exts","ext","extList","excludePatterns","p","exclude","getLogLevel","shouldLog","messageLevel","logLevel","refresh","mainSpinner","userTemplateDir","formatter","getFormatter","totalTags","updatedCount","skippedCount","globPattern","outputFilename","outputPath","templateContent","readTemplate","source","header","formattedContent","fullContent","dir","templateFile","runWizard","answers","run","effectiveOptions","ensureTargetDir","filteredTagTemplateMap","templatePatterns","filteredTemplates","template","regex","pluginTemplateMap","getPluginTemplates","combinedTemplateMap","generateSpinner","generatedFiles","processedProjects","totalTemplates","pruneOldFiles","ensureRegistryInitialized","map","maybeTemplates","tmpl","suffix","content","result","sanitizeProjectName","name","sanitized","force","oldFiles","prune","validate","telemetry","coreExports","createTelemetry","passCount","failCount","results","filePath","quality","validateInstructions","grade","getQualityGrade","scoreColor","avgScore","sum","score","getVersion","__filename","fileURLToPath","__dirname","dirname","packageJsonPath","join","readFileSync","main","program","Command","err","modulePath","scriptPath","realpathSync","resolve"],"mappings":";;;;;;;;;;;;;AAWA,eAAsBA,KAAQ;AAC5B,UAAQ,IAAIC,EAAG,KAAK;AAAA,CAA8C,CAAC;AAEnE,QAAMC,IAAUC,EAAI,0BAA0B,EAAE,MAAA,GAG1CC,IAAaC,EAAA,GACbC,IAASC,EAAaH,CAAU;AACtC,EAAAF,EAAQ,QAAQ,uBAAuB;AAEvC,Q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