workflow-agent-cli 2.20.1 → 2.21.2
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/chunk-KVM6A42U.js +321 -0
- package/dist/chunk-KVM6A42U.js.map +1 -0
- package/dist/chunk-OMHCXETM.js +238 -0
- package/dist/chunk-OMHCXETM.js.map +1 -0
- package/dist/{chunk-6NWQLGHI.js → chunk-XGS2VFBP.js} +5 -323
- package/dist/chunk-XGS2VFBP.js.map +1 -0
- package/dist/{chunk-CIGGRLZU.js → chunk-YR2X64TH.js} +74 -21
- package/dist/chunk-YR2X64TH.js.map +1 -0
- package/dist/cli/index.js +1414 -603
- package/dist/cli/index.js.map +1 -1
- package/dist/index.js +10 -8
- package/dist/scripts/postinstall.js +23 -2
- package/dist/scripts/postinstall.js.map +1 -1
- package/dist/verify-2PDVNYWV.js +8 -0
- package/dist/verify-2PDVNYWV.js.map +1 -0
- package/package.json +33 -28
- package/dist/chunk-6NWQLGHI.js.map +0 -1
- package/dist/chunk-CIGGRLZU.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -1,15 +1,9 @@
|
|
|
1
1
|
import {
|
|
2
|
-
QUALITY_CHECKS,
|
|
3
2
|
analyzeProject,
|
|
4
|
-
applyFix,
|
|
5
3
|
formatAuditReport,
|
|
6
4
|
generateAuditReport,
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
runAllSetups,
|
|
10
|
-
runCheck,
|
|
11
|
-
stageAllChanges
|
|
12
|
-
} from "./chunk-6NWQLGHI.js";
|
|
5
|
+
runAllSetups
|
|
6
|
+
} from "./chunk-XGS2VFBP.js";
|
|
13
7
|
import {
|
|
14
8
|
applyReferenceFix,
|
|
15
9
|
discoverCustomScopes,
|
|
@@ -34,6 +28,14 @@ import {
|
|
|
34
28
|
autoFixConfigFile,
|
|
35
29
|
writeFixedConfig
|
|
36
30
|
} from "./chunk-YELUGXOM.js";
|
|
31
|
+
import {
|
|
32
|
+
QUALITY_CHECKS,
|
|
33
|
+
applyFix,
|
|
34
|
+
hasUncommittedChanges,
|
|
35
|
+
runAllChecks,
|
|
36
|
+
runCheck,
|
|
37
|
+
stageAllChanges
|
|
38
|
+
} from "./chunk-KVM6A42U.js";
|
|
37
39
|
export {
|
|
38
40
|
QUALITY_CHECKS,
|
|
39
41
|
WorkflowConfigSchema,
|
|
@@ -3,12 +3,14 @@ import {
|
|
|
3
3
|
DEPRECATED_SCRIPTS,
|
|
4
4
|
SCRIPT_CATEGORIES,
|
|
5
5
|
TOTAL_SCRIPTS,
|
|
6
|
+
VALID_COMMANDS,
|
|
6
7
|
WORKFLOW_SCRIPTS,
|
|
7
8
|
WORKFLOW_SCRIPTS_VERSION,
|
|
8
9
|
findTemplatesDirectory,
|
|
9
10
|
generateCopilotInstructions,
|
|
10
|
-
installMandatoryTemplates
|
|
11
|
-
|
|
11
|
+
installMandatoryTemplates,
|
|
12
|
+
validateAllScripts
|
|
13
|
+
} from "../chunk-YR2X64TH.js";
|
|
12
14
|
|
|
13
15
|
// src/scripts/postinstall.ts
|
|
14
16
|
import { readFileSync, writeFileSync, existsSync } from "fs";
|
|
@@ -57,6 +59,25 @@ function addScriptsToPackageJson() {
|
|
|
57
59
|
removedScripts.push(deprecatedScript);
|
|
58
60
|
}
|
|
59
61
|
}
|
|
62
|
+
const existingWorkflowScripts = Object.keys(packageJson.scripts).filter(
|
|
63
|
+
(name) => name.startsWith("workflow:")
|
|
64
|
+
);
|
|
65
|
+
const invalidScripts = validateAllScripts(
|
|
66
|
+
Object.fromEntries(existingWorkflowScripts.map((s) => [s, ""]))
|
|
67
|
+
);
|
|
68
|
+
if (invalidScripts.length > 0) {
|
|
69
|
+
console.log(
|
|
70
|
+
`
|
|
71
|
+
\u26A0\uFE0F Warning: Found ${invalidScripts.length} workflow scripts with non-standard naming:`
|
|
72
|
+
);
|
|
73
|
+
for (const script of invalidScripts) {
|
|
74
|
+
console.log(` - ${script}`);
|
|
75
|
+
}
|
|
76
|
+
console.log(`
|
|
77
|
+
Valid top-level commands are: ${VALID_COMMANDS.join(", ")}`);
|
|
78
|
+
console.log(` Scripts must follow: workflow:<command>[-<action>[-<subaction>]]
|
|
79
|
+
`);
|
|
80
|
+
}
|
|
60
81
|
for (const [scriptName, scriptCommand] of Object.entries(
|
|
61
82
|
WORKFLOW_SCRIPTS
|
|
62
83
|
)) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/scripts/postinstall.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Post-install script that automatically adds workflow scripts to package.json\n * when installed as a local dependency (not global).\n *\n * On package update, this will also add any new scripts that were added in newer versions.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from \"fs\";\nimport { join, dirname } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport {\n WORKFLOW_SCRIPTS,\n DEPRECATED_SCRIPTS,\n WORKFLOW_SCRIPTS_VERSION,\n SCRIPT_CATEGORIES,\n TOTAL_SCRIPTS,\n} from \"./workflow-scripts.js\";\nimport { generateCopilotInstructions } from \"./copilot-instructions-generator.js\";\nimport {\n installMandatoryTemplates,\n findTemplatesDirectory,\n} from \"./template-installer.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nfunction isGlobalInstall(): boolean {\n // Check if we're being installed globally\n const installPath = process.env.npm_config_global;\n return installPath === \"true\";\n}\n\nfunction findProjectRoot(): string | null {\n // When installed as a dependency, npm/pnpm runs postinstall from the package directory\n // which is inside node_modules/@hawkinside_out/workflow-agent\n // We need to find the project root (the directory containing node_modules)\n\n const currentDir = process.cwd();\n\n // Check if we're inside node_modules\n if (currentDir.includes(\"node_modules\")) {\n // Split on 'node_modules' and take everything before it\n // This handles both node_modules/@scope/package and node_modules/package\n const parts = currentDir.split(\"node_modules\");\n if (parts.length > 0 && parts[0]) {\n // Remove trailing slash\n return parts[0].replace(/\\/$/, \"\");\n }\n }\n\n // If not in node_modules, we're probably in a monorepo workspace during development\n // Don't modify package.json in this case\n return null;\n}\n\nfunction addScriptsToPackageJson(): void {\n try {\n // Don't run for global installs\n if (isGlobalInstall()) {\n return;\n }\n\n const projectRoot = findProjectRoot();\n if (!projectRoot) {\n return;\n }\n\n const packageJsonPath = join(projectRoot, \"package.json\");\n\n if (!existsSync(packageJsonPath)) {\n return;\n }\n\n // Read existing package.json\n const packageJsonContent = readFileSync(packageJsonPath, \"utf-8\");\n const packageJson = JSON.parse(packageJsonContent);\n\n // Initialize scripts object if it doesn't exist\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n // Track changes\n const addedScripts: string[] = [];\n const updatedScripts: string[] = [];\n const removedScripts: string[] = [];\n\n // Step 1: Remove deprecated scripts\n for (const deprecatedScript of DEPRECATED_SCRIPTS) {\n if (packageJson.scripts[deprecatedScript] !== undefined) {\n delete packageJson.scripts[deprecatedScript];\n removedScripts.push(deprecatedScript);\n }\n }\n\n // Step 2: Add/update all workflow scripts (ensures updates get new scripts)\n for (const [scriptName, scriptCommand] of Object.entries(\n WORKFLOW_SCRIPTS,\n )) {\n if (!packageJson.scripts[scriptName]) {\n // Script doesn't exist - add it\n packageJson.scripts[scriptName] = scriptCommand;\n addedScripts.push(scriptName);\n } else if (packageJson.scripts[scriptName] !== scriptCommand) {\n // Script exists but has different value - update it\n packageJson.scripts[scriptName] = scriptCommand;\n updatedScripts.push(scriptName);\n }\n // If script exists with same value, do nothing (already up to date)\n }\n\n const totalChanges =\n addedScripts.length + updatedScripts.length + removedScripts.length;\n\n if (totalChanges > 0) {\n // Write back to package.json with proper formatting\n writeFileSync(\n packageJsonPath,\n JSON.stringify(packageJson, null, 2) + \"\\n\",\n \"utf-8\",\n );\n\n // Build summary message\n const summaryParts: string[] = [];\n if (addedScripts.length > 0) {\n summaryParts.push(`${addedScripts.length} new`);\n }\n if (updatedScripts.length > 0) {\n summaryParts.push(`${updatedScripts.length} updated`);\n }\n if (removedScripts.length > 0) {\n summaryParts.push(`${removedScripts.length} deprecated removed`);\n }\n\n console.log(\n `\\n✓ Workflow scripts configured in package.json (${summaryParts.join(\", \")}):`,\n );\n\n // Log removed deprecated scripts\n if (removedScripts.length > 0) {\n console.log(`\\n ⚠️ Removed deprecated scripts:`);\n for (const script of removedScripts) {\n console.log(` - ${script}`);\n }\n console.log(\n `\\n 💡 Updated to workflow-agent v${WORKFLOW_SCRIPTS_VERSION} with new command syntax.`,\n );\n console.log(` Old: workflow-agent learn:list`);\n console.log(` New: workflow-agent learn list\\n`);\n }\n\n // Display scripts by category\n for (const [category, scripts] of Object.entries(SCRIPT_CATEGORIES)) {\n console.log(`\\n ${category}:`);\n for (const script of scripts) {\n const isNew = addedScripts.includes(script);\n const isUpdated = updatedScripts.includes(script);\n const marker = isNew ? \" (new)\" : isUpdated ? \" (updated)\" : \"\";\n console.log(` - ${script}${marker}`);\n }\n }\n\n console.log(`\\n Total: ${TOTAL_SCRIPTS} scripts available`);\n console.log(\n \"\\nRun them with: npm run workflow:init (or pnpm run workflow:init)\\n\",\n );\n }\n\n // Install mandatory templates if guidelines directory doesn't exist\n const guidelinesDir = join(projectRoot, \"guidelines\");\n if (!existsSync(guidelinesDir)) {\n const templatesDir = findTemplatesDirectory(__dirname);\n if (templatesDir) {\n const templateResult = installMandatoryTemplates(\n projectRoot,\n templatesDir,\n { silent: false, skipIfExists: true, mandatoryOnly: true },\n );\n if (templateResult.installed.length > 0) {\n console.log(\n `✓ Installed ${templateResult.installed.length} mandatory guideline templates`,\n );\n }\n }\n }\n\n // Generate .github/copilot-instructions.md if guidelines exist\n if (existsSync(guidelinesDir)) {\n const result = generateCopilotInstructions(projectRoot, { silent: true });\n if (result.success) {\n const status = result.isNew ? \"Generated\" : \"Updated\";\n console.log(\n `✓ ${status} .github/copilot-instructions.md from ${result.guidelinesCount} guidelines`,\n );\n if (result.preservedCustomContent) {\n console.log(\" (Custom content preserved)\");\n }\n }\n }\n } catch (error) {\n // Silently fail - this is a nice-to-have feature\n // We don't want to break the installation if something goes wrong\n }\n}\n\n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YAAY,eAAe,SAAS,MAAM;AAChD,gBAAM,SAAS,QAAQ,WAAW,YAAY,eAAe;AAC7D,kBAAQ,IAAI,SAAS,MAAM,GAAG,MAAM,EAAE;AAAA,QACxC;AAAA,MACF;AAEA,cAAQ,IAAI;AAAA,WAAc,aAAa,oBAAoB;AAC3D,cAAQ;AAAA,QACN;AAAA,MACF;AAAA,IACF;AAGA,UAAM,gBAAgB,KAAK,aAAa,YAAY;AACpD,QAAI,CAAC,WAAW,aAAa,GAAG;AAC9B,YAAM,eAAe,uBAAuB,SAAS;AACrD,UAAI,cAAc;AAChB,cAAM,iBAAiB;AAAA,UACrB;AAAA,UACA;AAAA,UACA,EAAE,QAAQ,OAAO,cAAc,MAAM,eAAe,KAAK;AAAA,QAC3D;AACA,YAAI,eAAe,UAAU,SAAS,GAAG;AACvC,kBAAQ;AAAA,YACN,oBAAe,eAAe,UAAU,MAAM;AAAA,UAChD;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAGA,QAAI,WAAW,aAAa,GAAG;AAC7B,YAAM,SAAS,4BAA4B,aAAa,EAAE,QAAQ,KAAK,CAAC;AACxE,UAAI,OAAO,SAAS;AAClB,cAAM,SAAS,OAAO,QAAQ,cAAc;AAC5C,gBAAQ;AAAA,UACN,UAAK,MAAM,yCAAyC,OAAO,eAAe;AAAA,QAC5E;AACA,YAAI,OAAO,wBAAwB;AACjC,kBAAQ,IAAI,8BAA8B;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAGhB;AACF;AAGA,wBAAwB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../../src/scripts/postinstall.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * Post-install script that automatically adds workflow scripts to package.json\n * when installed as a local dependency (not global).\n *\n * On package update, this will also add any new scripts that were added in newer versions.\n */\n\nimport { readFileSync, writeFileSync, existsSync } from \"fs\";\nimport { join, dirname } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport {\n WORKFLOW_SCRIPTS,\n DEPRECATED_SCRIPTS,\n WORKFLOW_SCRIPTS_VERSION,\n SCRIPT_CATEGORIES,\n TOTAL_SCRIPTS,\n validateAllScripts,\n VALID_COMMANDS,\n} from \"./workflow-scripts.js\";\nimport { generateCopilotInstructions } from \"./copilot-instructions-generator.js\";\nimport {\n installMandatoryTemplates,\n findTemplatesDirectory,\n} from \"./template-installer.js\";\n\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\nfunction isGlobalInstall(): boolean {\n // Check if we're being installed globally\n const installPath = process.env.npm_config_global;\n return installPath === \"true\";\n}\n\nfunction findProjectRoot(): string | null {\n // When installed as a dependency, npm/pnpm runs postinstall from the package directory\n // which is inside node_modules/@hawkinside_out/workflow-agent\n // We need to find the project root (the directory containing node_modules)\n\n const currentDir = process.cwd();\n\n // Check if we're inside node_modules\n if (currentDir.includes(\"node_modules\")) {\n // Split on 'node_modules' and take everything before it\n // This handles both node_modules/@scope/package and node_modules/package\n const parts = currentDir.split(\"node_modules\");\n if (parts.length > 0 && parts[0]) {\n // Remove trailing slash\n return parts[0].replace(/\\/$/, \"\");\n }\n }\n\n // If not in node_modules, we're probably in a monorepo workspace during development\n // Don't modify package.json in this case\n return null;\n}\n\nfunction addScriptsToPackageJson(): void {\n try {\n // Don't run for global installs\n if (isGlobalInstall()) {\n return;\n }\n\n const projectRoot = findProjectRoot();\n if (!projectRoot) {\n return;\n }\n\n const packageJsonPath = join(projectRoot, \"package.json\");\n\n if (!existsSync(packageJsonPath)) {\n return;\n }\n\n // Read existing package.json\n const packageJsonContent = readFileSync(packageJsonPath, \"utf-8\");\n const packageJson = JSON.parse(packageJsonContent);\n\n // Initialize scripts object if it doesn't exist\n if (!packageJson.scripts) {\n packageJson.scripts = {};\n }\n\n // Track changes\n const addedScripts: string[] = [];\n const updatedScripts: string[] = [];\n const removedScripts: string[] = [];\n\n // Step 1: Remove deprecated scripts\n for (const deprecatedScript of DEPRECATED_SCRIPTS) {\n if (packageJson.scripts[deprecatedScript] !== undefined) {\n delete packageJson.scripts[deprecatedScript];\n removedScripts.push(deprecatedScript);\n }\n }\n\n // Step 1.5: Validate existing workflow: scripts follow the naming pattern\n const existingWorkflowScripts = Object.keys(packageJson.scripts).filter(\n (name) => name.startsWith(\"workflow:\"),\n );\n const invalidScripts = validateAllScripts(\n Object.fromEntries(existingWorkflowScripts.map((s) => [s, \"\"])),\n );\n if (invalidScripts.length > 0) {\n console.log(\n `\\n⚠️ Warning: Found ${invalidScripts.length} workflow scripts with non-standard naming:`,\n );\n for (const script of invalidScripts) {\n console.log(` - ${script}`);\n }\n console.log(`\\n Valid top-level commands are: ${VALID_COMMANDS.join(\", \")}`);\n console.log(` Scripts must follow: workflow:<command>[-<action>[-<subaction>]]\\n`);\n }\n\n // Step 2: Add/update all workflow scripts (ensures updates get new scripts)\n for (const [scriptName, scriptCommand] of Object.entries(\n WORKFLOW_SCRIPTS,\n )) {\n if (!packageJson.scripts[scriptName]) {\n // Script doesn't exist - add it\n packageJson.scripts[scriptName] = scriptCommand;\n addedScripts.push(scriptName);\n } else if (packageJson.scripts[scriptName] !== scriptCommand) {\n // Script exists but has different value - update it\n packageJson.scripts[scriptName] = scriptCommand;\n updatedScripts.push(scriptName);\n }\n // If script exists with same value, do nothing (already up to date)\n }\n\n const totalChanges =\n addedScripts.length + updatedScripts.length + removedScripts.length;\n\n if (totalChanges > 0) {\n // Write back to package.json with proper formatting\n writeFileSync(\n packageJsonPath,\n JSON.stringify(packageJson, null, 2) + \"\\n\",\n \"utf-8\",\n );\n\n // Build summary message\n const summaryParts: string[] = [];\n if (addedScripts.length > 0) {\n summaryParts.push(`${addedScripts.length} new`);\n }\n if (updatedScripts.length > 0) {\n summaryParts.push(`${updatedScripts.length} updated`);\n }\n if (removedScripts.length > 0) {\n summaryParts.push(`${removedScripts.length} deprecated removed`);\n }\n\n console.log(\n `\\n✓ Workflow scripts configured in package.json (${summaryParts.join(\", \")}):`,\n );\n\n // Log removed deprecated scripts\n if (removedScripts.length > 0) {\n console.log(`\\n ⚠️ Removed deprecated scripts:`);\n for (const script of removedScripts) {\n console.log(` - ${script}`);\n }\n console.log(\n `\\n 💡 Updated to workflow-agent v${WORKFLOW_SCRIPTS_VERSION} with new command syntax.`,\n );\n console.log(` Old: workflow-agent learn:list`);\n console.log(` New: workflow-agent learn list\\n`);\n }\n\n // Display scripts by category\n for (const [category, scripts] of Object.entries(SCRIPT_CATEGORIES)) {\n console.log(`\\n ${category}:`);\n for (const script of scripts) {\n const isNew = addedScripts.includes(script);\n const isUpdated = updatedScripts.includes(script);\n const marker = isNew ? \" (new)\" : isUpdated ? \" (updated)\" : \"\";\n console.log(` - ${script}${marker}`);\n }\n }\n\n console.log(`\\n Total: ${TOTAL_SCRIPTS} scripts available`);\n console.log(\n \"\\nRun them with: npm run workflow:init (or pnpm run workflow:init)\\n\",\n );\n }\n\n // Install mandatory templates if guidelines directory doesn't exist\n const guidelinesDir = join(projectRoot, \"guidelines\");\n if (!existsSync(guidelinesDir)) {\n const templatesDir = findTemplatesDirectory(__dirname);\n if (templatesDir) {\n const templateResult = installMandatoryTemplates(\n projectRoot,\n templatesDir,\n { silent: false, skipIfExists: true, mandatoryOnly: true },\n );\n if (templateResult.installed.length > 0) {\n console.log(\n `✓ Installed ${templateResult.installed.length} mandatory guideline templates`,\n );\n }\n }\n }\n\n // Generate .github/copilot-instructions.md if guidelines exist\n if (existsSync(guidelinesDir)) {\n const result = generateCopilotInstructions(projectRoot, { silent: true });\n if (result.success) {\n const status = result.isNew ? \"Generated\" : \"Updated\";\n console.log(\n `✓ ${status} .github/copilot-instructions.md from ${result.guidelinesCount} guidelines`,\n );\n if (result.preservedCustomContent) {\n console.log(\" (Custom content preserved)\");\n }\n }\n }\n } catch (error) {\n // Silently fail - this is a nice-to-have feature\n // We don't want to break the installation if something goes wrong\n }\n}\n\n// Run the script\naddScriptsToPackageJson();\n"],"mappings":";;;;;;;;;;;;;;;AASA,SAAS,cAAc,eAAe,kB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AAe;AAAA,QAC5E;AACA,YAAI,OAAO,wBAAwB;AACjC,kBAAQ,IAAI,8BAA8B;AAAA,QAC5C;AAAA,MACF;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAGhB;AACF;AAGA,wBAAwB;","names":[]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "workflow-agent-cli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.21.2",
|
|
4
4
|
"description": "A self-evolving workflow management system for AI agent development",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"workflow",
|
|
@@ -53,37 +53,42 @@
|
|
|
53
53
|
"postinstall": "node dist/scripts/postinstall.js || true",
|
|
54
54
|
"prepublishOnly": "pnpm build && pnpm test",
|
|
55
55
|
"workflow": "node dist/cli/index.js",
|
|
56
|
+
"workflow:version": "node dist/cli/index.js --version",
|
|
56
57
|
"workflow:init": "node dist/cli/index.js init",
|
|
57
58
|
"workflow:validate": "node dist/cli/index.js validate",
|
|
59
|
+
"workflow:config": "node dist/cli/index.js config show",
|
|
60
|
+
"workflow:config-show": "node dist/cli/index.js config show",
|
|
61
|
+
"workflow:config-set": "node dist/cli/index.js config set",
|
|
62
|
+
"workflow:suggest": "node dist/cli/index.js suggest",
|
|
63
|
+
"workflow:setup": "node dist/cli/index.js setup",
|
|
64
|
+
"workflow:setup-auto": "node dist/cli/index.js setup auto",
|
|
58
65
|
"workflow:doctor": "node dist/cli/index.js doctor",
|
|
66
|
+
"workflow:scope": "node dist/cli/index.js scope list",
|
|
67
|
+
"workflow:scope-list": "node dist/cli/index.js scope list",
|
|
68
|
+
"workflow:scope-create": "node dist/cli/index.js scope create",
|
|
69
|
+
"workflow:scope-migrate": "node dist/cli/index.js scope migrate",
|
|
70
|
+
"workflow:scope-hooks": "node dist/cli/index.js scope hooks status",
|
|
71
|
+
"workflow:scope-hooks-install": "node dist/cli/index.js scope hooks install",
|
|
72
|
+
"workflow:scope-hooks-uninstall": "node dist/cli/index.js scope hooks uninstall",
|
|
73
|
+
"workflow:scope-hooks-test": "node dist/cli/index.js scope hooks test",
|
|
59
74
|
"workflow:verify": "node dist/cli/index.js verify",
|
|
60
|
-
"workflow:
|
|
61
|
-
"workflow:
|
|
62
|
-
"workflow:
|
|
63
|
-
"workflow:
|
|
64
|
-
"
|
|
65
|
-
"
|
|
66
|
-
"
|
|
67
|
-
"
|
|
68
|
-
"
|
|
69
|
-
"
|
|
70
|
-
"
|
|
71
|
-
"
|
|
72
|
-
"
|
|
73
|
-
"
|
|
74
|
-
"
|
|
75
|
-
"
|
|
76
|
-
"
|
|
77
|
-
"learn:stats": "node dist/cli/index.js learn:stats",
|
|
78
|
-
"solution": "node dist/cli/index.js solution:list",
|
|
79
|
-
"solution:capture": "node dist/cli/index.js solution:capture",
|
|
80
|
-
"solution:search": "node dist/cli/index.js solution:search",
|
|
81
|
-
"solution:list": "node dist/cli/index.js solution:list",
|
|
82
|
-
"solution:apply": "node dist/cli/index.js solution:apply",
|
|
83
|
-
"solution:deprecate": "node dist/cli/index.js solution:deprecate",
|
|
84
|
-
"solution:stats": "node dist/cli/index.js solution:stats",
|
|
85
|
-
"scope:create": "node dist/cli/index.js scope:create",
|
|
86
|
-
"scope:migrate": "node dist/cli/index.js scope:migrate"
|
|
75
|
+
"workflow:verify-fix": "node dist/cli/index.js verify --fix",
|
|
76
|
+
"workflow:pre-commit": "node dist/cli/index.js pre-commit",
|
|
77
|
+
"workflow:learn": "node dist/cli/index.js learn list",
|
|
78
|
+
"workflow:learn-list": "node dist/cli/index.js learn list",
|
|
79
|
+
"workflow:learn-analyze": "node dist/cli/index.js learn analyze",
|
|
80
|
+
"workflow:learn-capture": "node dist/cli/index.js learn capture",
|
|
81
|
+
"workflow:learn-stats": "node dist/cli/index.js learn stats",
|
|
82
|
+
"workflow:solution": "node dist/cli/index.js solution list",
|
|
83
|
+
"workflow:solution-list": "node dist/cli/index.js solution list",
|
|
84
|
+
"workflow:solution-create": "node dist/cli/index.js solution create",
|
|
85
|
+
"workflow:solution-search": "node dist/cli/index.js solution search",
|
|
86
|
+
"workflow:sync": "node dist/cli/index.js sync",
|
|
87
|
+
"workflow:sync-push": "node dist/cli/index.js sync --push",
|
|
88
|
+
"workflow:sync-pull": "node dist/cli/index.js sync --pull",
|
|
89
|
+
"workflow:docs": "node dist/cli/index.js docs validate",
|
|
90
|
+
"workflow:docs-validate": "node dist/cli/index.js docs validate",
|
|
91
|
+
"workflow:docs-advisory": "node dist/cli/index.js docs advisory"
|
|
87
92
|
},
|
|
88
93
|
"dependencies": {
|
|
89
94
|
"@clack/prompts": "^0.7.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/check-runner.ts","../src/utils/auto-setup.ts","../src/utils/git-repo.ts"],"sourcesContent":["/**\n * Check Runner - Orchestrates quality checks with fix-and-revalidate pattern\n *\n * Pattern: Run check → If fails, fix → Re-run ALL checks from start\n * This ensures fixes don't introduce new issues in earlier checks.\n */\n\nimport { execa, type ExecaError } from \"execa\";\nimport chalk from \"chalk\";\n\nexport interface CheckDefinition {\n name: string;\n displayName: string;\n command: string;\n args: string[];\n fixCommand?: string;\n fixArgs?: string[];\n canAutoFix: boolean;\n}\n\nexport interface CheckResult {\n check: CheckDefinition;\n success: boolean;\n output: string;\n error?: string;\n duration: number;\n}\n\nexport interface AppliedFix {\n checkName: string;\n displayName: string;\n command: string;\n timestamp: Date;\n}\n\nexport interface RunAllChecksResult {\n success: boolean;\n results: CheckResult[];\n totalAttempts: number;\n fixesApplied: number;\n appliedFixes: AppliedFix[];\n pendingFixes?: Array<{ check: CheckDefinition; command: string }>;\n}\n\nexport type ProgressType = \"info\" | \"success\" | \"error\" | \"warning\";\n\nexport interface CheckRunnerOptions {\n maxRetries?: number;\n autoFix?: boolean;\n dryRun?: boolean;\n onProgress?: (message: string, type: ProgressType) => void;\n}\n\n/**\n * Standard quality checks in recommended order\n * Order: typecheck → lint → format → test → build\n * Type errors cascade, so we fix them first\n */\nexport const QUALITY_CHECKS: CheckDefinition[] = [\n {\n name: \"typecheck\",\n displayName: \"Type Check\",\n command: \"pnpm\",\n args: [\"typecheck\"],\n canAutoFix: false, // TypeScript errors need manual/LLM fix\n },\n {\n name: \"lint\",\n displayName: \"Lint\",\n command: \"pnpm\",\n args: [\"lint\"],\n fixCommand: \"pnpm\",\n fixArgs: [\"lint\", \"--fix\"],\n canAutoFix: true,\n },\n {\n name: \"format\",\n displayName: \"Format\",\n command: \"pnpm\",\n args: [\"format\", \"--check\"],\n fixCommand: \"pnpm\",\n fixArgs: [\"format\"],\n canAutoFix: true,\n },\n {\n name: \"test\",\n displayName: \"Tests\",\n command: \"pnpm\",\n args: [\"test\"],\n canAutoFix: false, // Tests need manual/LLM fix\n },\n {\n name: \"build\",\n displayName: \"Build\",\n command: \"pnpm\",\n args: [\"build\"],\n canAutoFix: false, // Build errors need manual/LLM fix\n },\n];\n\n/**\n * Run a single check\n */\nexport async function runCheck(\n check: CheckDefinition,\n cwd: string,\n): Promise<CheckResult> {\n const startTime = Date.now();\n\n try {\n const result = await execa(check.command, check.args, {\n cwd,\n reject: false,\n all: true,\n });\n\n const duration = Date.now() - startTime;\n\n if (result.exitCode === 0) {\n return {\n check,\n success: true,\n output: result.all || \"\",\n duration,\n };\n } else {\n return {\n check,\n success: false,\n output: result.all || \"\",\n error: result.stderr || result.all || \"Check failed\",\n duration,\n };\n }\n } catch (error) {\n const duration = Date.now() - startTime;\n const execaError = error as ExecaError;\n\n return {\n check,\n success: false,\n output: execaError.all?.toString() || execaError.message || \"\",\n error: execaError.message,\n duration,\n };\n }\n}\n\n/**\n * Apply fix for a check that supports auto-fix\n */\nexport async function applyFix(\n check: CheckDefinition,\n cwd: string,\n): Promise<{ success: boolean; output: string }> {\n if (!check.canAutoFix || !check.fixCommand) {\n return { success: false, output: \"Check does not support auto-fix\" };\n }\n\n try {\n const result = await execa(check.fixCommand, check.fixArgs || [], {\n cwd,\n reject: false,\n all: true,\n });\n\n return {\n success: result.exitCode === 0,\n output: result.all || \"\",\n };\n } catch (error) {\n const execaError = error as ExecaError;\n return {\n success: false,\n output: execaError.message,\n };\n }\n}\n\n/**\n * Format a fix command for display\n */\nfunction formatFixCommand(check: CheckDefinition): string {\n if (!check.fixCommand) return \"\";\n return `${check.fixCommand} ${(check.fixArgs || []).join(\" \")}`;\n}\n\n/**\n * Run all quality checks with fix-and-revalidate pattern\n *\n * When a check fails and can be auto-fixed:\n * 1. Apply the fix\n * 2. Re-run ALL checks from the beginning\n * 3. Repeat until all pass or max retries reached\n *\n * @param cwd - Working directory\n * @param options - Configuration options\n */\nexport async function runAllChecks(\n cwd: string,\n options: CheckRunnerOptions = {},\n): Promise<RunAllChecksResult> {\n const {\n maxRetries = 10,\n autoFix = true,\n dryRun = false,\n onProgress,\n } = options;\n\n const log = (message: string, type: ProgressType = \"info\") => {\n if (onProgress) {\n onProgress(message, type);\n } else {\n // Default console output with colors\n switch (type) {\n case \"success\":\n console.log(chalk.green(message));\n break;\n case \"error\":\n console.log(chalk.red(message));\n break;\n case \"warning\":\n console.log(chalk.yellow(message));\n break;\n default:\n console.log(message);\n }\n }\n };\n\n let attempt = 0;\n let fixesApplied = 0;\n const appliedFixes: AppliedFix[] = [];\n const pendingFixes: Array<{ check: CheckDefinition; command: string }> = [];\n\n while (attempt < maxRetries) {\n attempt++;\n\n log(`\\n${\"━\".repeat(50)}`, \"info\");\n log(`🔄 Validation Cycle ${attempt}/${maxRetries}`, \"info\");\n log(`${\"━\".repeat(50)}\\n`, \"info\");\n\n const results: CheckResult[] = [];\n let allPassed = true;\n let fixAppliedThisCycle = false;\n\n // Run each check in order\n for (let i = 0; i < QUALITY_CHECKS.length; i++) {\n const check = QUALITY_CHECKS[i];\n const stepNum = i + 1;\n const totalSteps = QUALITY_CHECKS.length;\n\n log(`📋 Step ${stepNum}/${totalSteps}: ${check.displayName}...`, \"info\");\n\n const result = await runCheck(check, cwd);\n results.push(result);\n\n if (result.success) {\n log(`✅ ${check.displayName} passed (${result.duration}ms)`, \"success\");\n } else {\n allPassed = false;\n log(`❌ ${check.displayName} failed`, \"error\");\n\n // Try to auto-fix if possible\n if (autoFix && check.canAutoFix && check.fixCommand) {\n if (dryRun) {\n // In dry-run mode, just record what would be fixed\n log(\n `🔧 [DRY-RUN] Would run: ${formatFixCommand(check)}`,\n \"warning\",\n );\n pendingFixes.push({ check, command: formatFixCommand(check) });\n\n // Continue to next check to show all issues\n continue;\n }\n\n log(`🔧 Attempting auto-fix for ${check.displayName}...`, \"warning\");\n\n const fixResult = await applyFix(check, cwd);\n\n if (fixResult.success) {\n log(`✨ Auto-fix applied for ${check.displayName}`, \"success\");\n fixesApplied++;\n appliedFixes.push({\n checkName: check.name,\n displayName: check.displayName,\n command: formatFixCommand(check),\n timestamp: new Date(),\n });\n fixAppliedThisCycle = true;\n\n // IMPORTANT: Re-run ALL checks from the beginning\n log(\n `\\n🔄 Fix applied - restarting all checks to verify...`,\n \"warning\",\n );\n break; // Exit the for loop to restart from the beginning\n } else {\n log(`⚠️ Auto-fix failed for ${check.displayName}`, \"error\");\n log(` Manual intervention required`, \"error\");\n\n // Show error details\n if (result.error) {\n const errorPreview = result.error.slice(0, 500);\n log(`\\n${chalk.dim(errorPreview)}`, \"error\");\n if (result.error.length > 500) {\n log(\n chalk.dim(\n `... (${result.error.length - 500} more characters)`,\n ),\n \"error\",\n );\n }\n }\n\n return {\n success: false,\n results,\n totalAttempts: attempt,\n fixesApplied,\n appliedFixes,\n };\n }\n } else {\n // Cannot auto-fix this check\n if (check.canAutoFix) {\n log(\n `⚠️ ${check.displayName} can be fixed with: ${formatFixCommand(check)}`,\n \"warning\",\n );\n } else {\n log(`⚠️ ${check.displayName} requires manual fix`, \"error\");\n }\n\n // Show error details\n if (result.error) {\n const errorPreview = result.error.slice(0, 500);\n log(`\\n${chalk.dim(errorPreview)}`, \"error\");\n if (result.error.length > 500) {\n log(\n chalk.dim(`... (${result.error.length - 500} more characters)`),\n \"error\",\n );\n }\n }\n\n if (!dryRun) {\n return {\n success: false,\n results,\n totalAttempts: attempt,\n fixesApplied,\n appliedFixes,\n };\n }\n }\n }\n }\n\n // Handle dry-run completion\n if (dryRun && pendingFixes.length > 0) {\n log(`\\n${\"━\".repeat(50)}`, \"info\");\n log(`📋 DRY-RUN SUMMARY`, \"info\");\n log(`${\"━\".repeat(50)}`, \"info\");\n log(`\\nThe following fixes would be applied:`, \"warning\");\n for (const fix of pendingFixes) {\n log(` • ${fix.check.displayName}: ${fix.command}`, \"info\");\n }\n log(`\\nRun without --dry-run to apply fixes.`, \"info\");\n\n return {\n success: false,\n results,\n totalAttempts: attempt,\n fixesApplied: 0,\n appliedFixes: [],\n pendingFixes,\n };\n }\n\n // If all checks passed, we're done!\n if (allPassed) {\n return {\n success: true,\n results,\n totalAttempts: attempt,\n fixesApplied,\n appliedFixes,\n };\n }\n\n // If no fix was applied this cycle but we still failed, we're stuck\n if (!fixAppliedThisCycle) {\n return {\n success: false,\n results,\n totalAttempts: attempt,\n fixesApplied,\n appliedFixes,\n };\n }\n\n // Otherwise, continue to next cycle (fix was applied, need to re-verify)\n }\n\n // Max retries exceeded\n log(`\\n❌ Maximum retries (${maxRetries}) exceeded`, \"error\");\n\n return {\n success: false,\n results: [],\n totalAttempts: attempt,\n fixesApplied,\n appliedFixes,\n };\n}\n\n/**\n * Check if there are uncommitted changes in git\n */\nexport async function hasUncommittedChanges(cwd: string): Promise<boolean> {\n try {\n const result = await execa(\"git\", [\"status\", \"--porcelain\"], { cwd });\n return result.stdout.trim().length > 0;\n } catch {\n return false;\n }\n}\n\n/**\n * Stage all changes in git\n */\nexport async function stageAllChanges(cwd: string): Promise<boolean> {\n try {\n await execa(\"git\", [\"add\", \"-A\"], { cwd });\n return true;\n } catch {\n return false;\n }\n}\n","/**\n * Auto-Setup Utilities\n *\n * Intelligent project setup that:\n * - Analyzes what a project has and needs\n * - Generates audit reports showing what will change\n * - MERGES with existing configs (improves, doesn't replace)\n * - Batches dependency installs for performance\n * - Supports monorepos with root + shared configs\n *\n * Works like a developer would: analyze first, then configure.\n */\n\nimport { existsSync } from \"fs\";\nimport { readFile, writeFile, mkdir } from \"fs/promises\";\nimport { join } from \"path\";\nimport { execa } from \"execa\";\nimport {\n detectPackageManager,\n isMonorepo,\n getPackageScripts,\n type PackageManager,\n} from \"./git-repo.js\";\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface ProjectAnalysis {\n packageManager: PackageManager;\n isMonorepo: boolean;\n isTypeScript: boolean;\n framework: FrameworkType;\n existing: ExistingConfigs;\n scripts: ExistingScripts;\n setupPlans: SetupPlan[];\n}\n\nexport interface ExistingConfigs {\n typescript: boolean;\n eslint: boolean;\n eslintFlat: boolean;\n prettier: boolean;\n vitest: boolean;\n jest: boolean;\n husky: boolean;\n simpleGitHooks: boolean;\n githubActions: boolean;\n}\n\nexport interface ExistingScripts {\n build: boolean;\n test: boolean;\n lint: boolean;\n format: boolean;\n typecheck: boolean;\n verify: boolean;\n}\n\nexport interface SetupPlan {\n name: string;\n description: string;\n priority: \"high\" | \"medium\" | \"low\";\n changes: ConfigChange[];\n dependencies: string[];\n devDependencies: string[];\n}\n\nexport interface ConfigChange {\n type: \"add\" | \"modify\" | \"unchanged\";\n file: string;\n key?: string;\n oldValue?: unknown;\n newValue?: unknown;\n description: string;\n}\n\nexport interface SetupResult {\n success: boolean;\n name: string;\n message: string;\n filesCreated: string[];\n filesUpdated: string[];\n packagesInstalled: string[];\n}\n\nexport interface AuditReport {\n analysis: ProjectAnalysis;\n totalChanges: number;\n allDependencies: string[];\n allDevDependencies: string[];\n plans: SetupPlan[];\n}\n\nexport type FrameworkType =\n | \"nextjs\"\n | \"remix\"\n | \"react\"\n | \"vue\"\n | \"nuxt\"\n | \"svelte\"\n | \"node\"\n | \"express\"\n | \"hono\"\n | \"shopify\"\n | \"unknown\";\n\n// Package.json structure for type safety\ninterface PackageJson {\n name?: string;\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n scripts?: Record<string, string>;\n \"simple-git-hooks\"?: Record<string, string>;\n \"lint-staged\"?: Record<string, string | string[]>;\n [key: string]: unknown;\n}\n\n// TSConfig structure\ninterface TSConfig {\n compilerOptions?: Record<string, unknown>;\n include?: string[];\n exclude?: string[];\n [key: string]: unknown;\n}\n\n// ============================================================================\n// Project Analysis\n// ============================================================================\n\n/**\n * Analyze a project to determine what setup is needed\n */\nexport async function analyzeProject(\n projectPath: string = process.cwd(),\n): Promise<ProjectAnalysis> {\n const packageManager = await detectPackageManager(projectPath);\n const mono = await isMonorepo(projectPath);\n const scripts = await getPackageScripts(projectPath);\n\n // Check for TypeScript\n const isTypeScript =\n existsSync(join(projectPath, \"tsconfig.json\")) ||\n existsSync(join(projectPath, \"src/index.ts\")) ||\n existsSync(join(projectPath, \"index.ts\"));\n\n // Detect framework\n const framework = await detectFramework(projectPath);\n\n // Check existing configs\n const existing: ExistingConfigs = {\n typescript: existsSync(join(projectPath, \"tsconfig.json\")),\n eslint:\n existsSync(join(projectPath, \"eslint.config.js\")) ||\n existsSync(join(projectPath, \"eslint.config.mjs\")) ||\n existsSync(join(projectPath, \".eslintrc.js\")) ||\n existsSync(join(projectPath, \".eslintrc.json\")) ||\n existsSync(join(projectPath, \".eslintrc\")),\n eslintFlat:\n existsSync(join(projectPath, \"eslint.config.js\")) ||\n existsSync(join(projectPath, \"eslint.config.mjs\")),\n prettier:\n existsSync(join(projectPath, \".prettierrc\")) ||\n existsSync(join(projectPath, \".prettierrc.json\")) ||\n existsSync(join(projectPath, \"prettier.config.js\")) ||\n existsSync(join(projectPath, \"prettier.config.mjs\")),\n vitest:\n existsSync(join(projectPath, \"vitest.config.ts\")) ||\n existsSync(join(projectPath, \"vitest.config.js\")),\n jest:\n existsSync(join(projectPath, \"jest.config.js\")) ||\n existsSync(join(projectPath, \"jest.config.ts\")),\n husky: existsSync(join(projectPath, \".husky\")),\n simpleGitHooks:\n existsSync(join(projectPath, \".git/hooks/pre-commit\")) ||\n (await hasSimpleGitHooksConfig(projectPath)),\n githubActions: existsSync(join(projectPath, \".github/workflows\")),\n };\n\n // Check existing scripts\n const existingScripts: ExistingScripts = {\n build: !!scripts.build,\n test: !!scripts.test,\n lint: !!scripts.lint,\n format: !!scripts.format,\n typecheck: !!scripts.typecheck,\n verify: !!scripts.verify,\n };\n\n // Generate setup plans\n const setupPlans = await generateSetupPlans(\n projectPath,\n packageManager,\n isTypeScript,\n framework,\n existing,\n existingScripts,\n mono,\n );\n\n return {\n packageManager,\n isMonorepo: mono,\n isTypeScript,\n framework,\n existing,\n scripts: existingScripts,\n setupPlans,\n };\n}\n\nasync function hasSimpleGitHooksConfig(projectPath: string): Promise<boolean> {\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (!existsSync(pkgPath)) return false;\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n return !!pkg[\"simple-git-hooks\"];\n } catch {\n return false;\n }\n}\n\n/**\n * Detect the framework used in the project\n */\nasync function detectFramework(projectPath: string): Promise<FrameworkType> {\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (!existsSync(pkgPath)) return \"unknown\";\n\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n\n // Shopify theme detection\n if (\n existsSync(join(projectPath, \"shopify.theme.toml\")) ||\n existsSync(join(projectPath, \"config/settings_schema.json\")) ||\n deps[\"@shopify/cli\"] ||\n deps[\"@shopify/theme\"]\n ) {\n return \"shopify\";\n }\n\n // Framework detection by dependencies\n if (deps.next) return \"nextjs\";\n if (deps[\"@remix-run/react\"]) return \"remix\";\n if (deps.nuxt) return \"nuxt\";\n if (deps.vue) return \"vue\";\n if (deps.svelte || deps[\"@sveltejs/kit\"]) return \"svelte\";\n if (deps.react && !deps.next) return \"react\";\n if (deps.hono) return \"hono\";\n if (deps.express) return \"express\";\n if (deps[\"@types/node\"] || pkg.type === \"module\") return \"node\";\n\n return \"unknown\";\n } catch {\n return \"unknown\";\n }\n}\n\n// ============================================================================\n// Setup Plan Generation\n// ============================================================================\n\nasync function generateSetupPlans(\n projectPath: string,\n packageManager: PackageManager,\n isTypeScript: boolean,\n framework: FrameworkType,\n existing: ExistingConfigs,\n scripts: ExistingScripts,\n isMonorepo: boolean,\n): Promise<SetupPlan[]> {\n const plans: SetupPlan[] = [];\n\n // TypeScript setup/improvement\n if (isTypeScript) {\n plans.push(\n await planTypeScriptSetup(\n projectPath,\n framework,\n existing.typescript,\n isMonorepo,\n ),\n );\n }\n\n // ESLint setup/improvement\n plans.push(\n await planESLintSetup(projectPath, isTypeScript, framework, existing),\n );\n\n // Prettier setup/improvement\n plans.push(await planPrettierSetup(projectPath, existing.prettier));\n\n // Testing setup\n plans.push(\n await planTestingSetup(projectPath, isTypeScript, framework, existing),\n );\n\n // Build configuration (for non-framework TS projects)\n if (isTypeScript && ![\"nextjs\", \"remix\", \"nuxt\"].includes(framework)) {\n plans.push(await planBuildSetup(projectPath, scripts.build));\n }\n\n // Scripts setup\n plans.push(\n await planScriptsSetup(projectPath, isTypeScript, framework, scripts),\n );\n\n // Pre-commit hooks\n plans.push(await planHooksSetup(projectPath, existing));\n\n // GitHub Actions CI\n plans.push(\n await planCISetup(\n projectPath,\n packageManager,\n isTypeScript,\n framework,\n existing.githubActions,\n isMonorepo,\n ),\n );\n\n return plans;\n}\n\n// ============================================================================\n// Individual Plan Generators\n// ============================================================================\n\nasync function planTypeScriptSetup(\n projectPath: string,\n _framework: FrameworkType,\n hasExisting: boolean,\n isMonorepo: boolean,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n // Check if typescript is installed\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n if (!allDeps.typescript) {\n devDeps.push(\"typescript\");\n }\n\n if (hasExisting) {\n // Audit existing config\n const tsconfig = await readTSConfig(join(projectPath, \"tsconfig.json\"));\n const opts = tsconfig.compilerOptions || {};\n\n // Recommend improvements\n if (!opts.strict) {\n changes.push({\n type: \"modify\",\n file: \"tsconfig.json\",\n key: \"compilerOptions.strict\",\n oldValue: opts.strict,\n newValue: true,\n description: \"Enable strict type checking\",\n });\n }\n if (!opts.skipLibCheck) {\n changes.push({\n type: \"modify\",\n file: \"tsconfig.json\",\n key: \"compilerOptions.skipLibCheck\",\n oldValue: opts.skipLibCheck,\n newValue: true,\n description:\n \"Skip type checking of declaration files for faster builds\",\n });\n }\n if (opts.target !== \"ES2022\" && opts.target !== \"ESNext\") {\n changes.push({\n type: \"modify\",\n file: \"tsconfig.json\",\n key: \"compilerOptions.target\",\n oldValue: opts.target,\n newValue: \"ES2022\",\n description: \"Use modern JavaScript target\",\n });\n }\n } else {\n changes.push({\n type: \"add\",\n file: isMonorepo ? \"tsconfig.base.json\" : \"tsconfig.json\",\n description: `Create TypeScript configuration${isMonorepo ? \" (shared base for monorepo)\" : \"\"}`,\n });\n }\n\n return {\n name: \"typescript\",\n description: hasExisting\n ? \"Improve TypeScript configuration\"\n : \"Set up TypeScript configuration\",\n priority: \"high\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planESLintSetup(\n projectPath: string,\n isTypeScript: boolean,\n framework: FrameworkType,\n existing: ExistingConfigs,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n\n // Core ESLint\n if (!allDeps.eslint) {\n devDeps.push(\"eslint\");\n }\n\n // TypeScript support\n if (isTypeScript) {\n if (!allDeps[\"@typescript-eslint/eslint-plugin\"]) {\n devDeps.push(\"@typescript-eslint/eslint-plugin\");\n }\n if (!allDeps[\"@typescript-eslint/parser\"]) {\n devDeps.push(\"@typescript-eslint/parser\");\n }\n if (!allDeps[\"typescript-eslint\"]) {\n devDeps.push(\"typescript-eslint\");\n }\n }\n\n // Framework-specific plugins\n if (framework === \"react\" || framework === \"nextjs\") {\n if (!allDeps[\"eslint-plugin-react\"]) devDeps.push(\"eslint-plugin-react\");\n if (!allDeps[\"eslint-plugin-react-hooks\"])\n devDeps.push(\"eslint-plugin-react-hooks\");\n }\n\n if (existing.eslint) {\n if (!existing.eslintFlat) {\n changes.push({\n type: \"modify\",\n file: \"eslint.config.mjs\",\n description: \"Migrate to ESLint 9 flat config format (recommended)\",\n });\n } else {\n changes.push({\n type: \"unchanged\",\n file: \"eslint.config.mjs\",\n description: \"ESLint flat config already exists\",\n });\n }\n } else {\n changes.push({\n type: \"add\",\n file: \"eslint.config.mjs\",\n description: \"Create ESLint configuration with TypeScript support\",\n });\n }\n\n return {\n name: \"eslint\",\n description: existing.eslint\n ? \"Audit ESLint configuration and dependencies\"\n : \"Set up ESLint for code linting\",\n priority: \"high\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planPrettierSetup(\n projectPath: string,\n hasExisting: boolean,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n\n if (!allDeps.prettier) {\n devDeps.push(\"prettier\");\n }\n\n if (hasExisting) {\n const prettierConfig = await readPrettierConfig(projectPath);\n // Check for recommended settings\n if (prettierConfig.printWidth === undefined) {\n changes.push({\n type: \"modify\",\n file: \".prettierrc\",\n key: \"printWidth\",\n newValue: 100,\n description: \"Add printWidth setting\",\n });\n }\n if (prettierConfig.trailingComma === undefined) {\n changes.push({\n type: \"modify\",\n file: \".prettierrc\",\n key: \"trailingComma\",\n newValue: \"es5\",\n description: \"Add trailing comma setting\",\n });\n }\n if (changes.length === 0) {\n changes.push({\n type: \"unchanged\",\n file: \".prettierrc\",\n description: \"Prettier configuration is complete\",\n });\n }\n } else {\n changes.push({\n type: \"add\",\n file: \".prettierrc\",\n description: \"Create Prettier configuration\",\n });\n changes.push({\n type: \"add\",\n file: \".prettierignore\",\n description: \"Create Prettier ignore file\",\n });\n }\n\n return {\n name: \"prettier\",\n description: hasExisting\n ? \"Audit Prettier configuration\"\n : \"Set up Prettier for code formatting\",\n priority: \"high\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planTestingSetup(\n projectPath: string,\n isTypeScript: boolean,\n framework: FrameworkType,\n existing: ExistingConfigs,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n\n // Respect existing Jest - don't force Vitest\n if (existing.jest) {\n changes.push({\n type: \"unchanged\",\n file: \"jest.config.*\",\n description: \"Jest configuration exists (preserving existing setup)\",\n });\n return {\n name: \"testing\",\n description: \"Jest testing already configured\",\n priority: \"high\",\n changes,\n dependencies: [],\n devDependencies: [],\n };\n }\n\n // Set up Vitest\n if (!allDeps.vitest) {\n devDeps.push(\"vitest\");\n }\n if (!allDeps[\"@vitest/coverage-v8\"]) {\n devDeps.push(\"@vitest/coverage-v8\");\n }\n\n // DOM testing for frontend frameworks\n if ([\"react\", \"nextjs\", \"vue\", \"nuxt\", \"svelte\"].includes(framework)) {\n if (!allDeps.jsdom) devDeps.push(\"jsdom\");\n if (framework === \"react\" || framework === \"nextjs\") {\n if (!allDeps[\"@testing-library/react\"])\n devDeps.push(\"@testing-library/react\");\n }\n }\n\n if (existing.vitest) {\n changes.push({\n type: \"unchanged\",\n file: `vitest.config.${isTypeScript ? \"ts\" : \"js\"}`,\n description: \"Vitest configuration already exists\",\n });\n } else {\n changes.push({\n type: \"add\",\n file: `vitest.config.${isTypeScript ? \"ts\" : \"js\"}`,\n description: \"Create Vitest configuration\",\n });\n }\n\n return {\n name: \"testing\",\n description: existing.vitest\n ? \"Audit Vitest dependencies\"\n : \"Set up Vitest for testing\",\n priority: \"high\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planBuildSetup(\n projectPath: string,\n hasBuildScript: boolean,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n\n if (hasBuildScript) {\n changes.push({\n type: \"unchanged\",\n file: \"package.json\",\n key: \"scripts.build\",\n description: \"Build script already configured\",\n });\n } else {\n if (!allDeps.tsup) {\n devDeps.push(\"tsup\");\n }\n changes.push({\n type: \"add\",\n file: \"tsup.config.ts\",\n description: \"Create tsup build configuration\",\n });\n }\n\n return {\n name: \"build\",\n description: hasBuildScript\n ? \"Build configuration exists\"\n : \"Set up tsup for TypeScript builds\",\n priority: \"medium\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planScriptsSetup(\n _projectPath: string,\n isTypeScript: boolean,\n _framework: FrameworkType,\n scripts: ExistingScripts,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const scriptsToAdd: Record<string, string> = {};\n\n if (!scripts.lint) {\n scriptsToAdd.lint = \"eslint src\";\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"scripts.lint\",\n newValue: \"eslint src\",\n description: \"Add lint script\",\n });\n }\n\n if (!scripts.format) {\n scriptsToAdd.format = 'prettier --write \"src/**/*.{ts,tsx,js,jsx,json}\"';\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"scripts.format\",\n newValue: scriptsToAdd.format,\n description: \"Add format script\",\n });\n }\n\n if (isTypeScript && !scripts.typecheck) {\n scriptsToAdd.typecheck = \"tsc --noEmit\";\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"scripts.typecheck\",\n newValue: \"tsc --noEmit\",\n description: \"Add typecheck script\",\n });\n }\n\n if (!scripts.test) {\n scriptsToAdd.test = \"vitest run\";\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"scripts.test\",\n newValue: \"vitest run\",\n description: \"Add test script\",\n });\n }\n\n if (!scripts.verify) {\n scriptsToAdd.verify = \"workflow-agent verify\";\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"scripts.verify\",\n newValue: \"workflow-agent verify\",\n description: \"Add verify script\",\n });\n }\n\n if (Object.keys(scriptsToAdd).length === 0) {\n changes.push({\n type: \"unchanged\",\n file: \"package.json\",\n description: \"All standard scripts already configured\",\n });\n }\n\n return {\n name: \"scripts\",\n description: \"Configure npm scripts\",\n priority: \"medium\",\n changes,\n dependencies: [],\n devDependencies: [],\n };\n}\n\nasync function planHooksSetup(\n projectPath: string,\n existing: ExistingConfigs,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n const devDeps: string[] = [];\n\n const pkg = await readPackageJson(projectPath);\n const deps = pkg.dependencies || {};\n const devDepsPkg = pkg.devDependencies || {};\n const allDeps = { ...deps, ...devDepsPkg };\n\n // Prefer simple-git-hooks over husky\n if (!allDeps[\"simple-git-hooks\"]) {\n devDeps.push(\"simple-git-hooks\");\n }\n if (!allDeps[\"lint-staged\"]) {\n devDeps.push(\"lint-staged\");\n }\n\n if (existing.husky || existing.simpleGitHooks) {\n changes.push({\n type: \"modify\",\n file: \"package.json\",\n key: \"simple-git-hooks\",\n description: \"Ensure pre-commit hook configuration\",\n });\n } else {\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"simple-git-hooks\",\n newValue: { \"pre-commit\": \"npx lint-staged\" },\n description: \"Add pre-commit hook configuration\",\n });\n changes.push({\n type: \"add\",\n file: \"package.json\",\n key: \"lint-staged\",\n description: \"Add lint-staged configuration\",\n });\n }\n\n return {\n name: \"hooks\",\n description:\n existing.husky || existing.simpleGitHooks\n ? \"Audit pre-commit hooks\"\n : \"Set up pre-commit hooks\",\n priority: \"medium\",\n changes,\n dependencies: [],\n devDependencies: devDeps,\n };\n}\n\nasync function planCISetup(\n projectPath: string,\n _packageManager: PackageManager,\n _isTypeScript: boolean,\n _framework: FrameworkType,\n hasExisting: boolean,\n _isMonorepo: boolean,\n): Promise<SetupPlan> {\n const changes: ConfigChange[] = [];\n\n if (hasExisting) {\n // Check if ci.yml exists specifically\n if (existsSync(join(projectPath, \".github/workflows/ci.yml\"))) {\n changes.push({\n type: \"unchanged\",\n file: \".github/workflows/ci.yml\",\n description: \"CI workflow already exists\",\n });\n } else {\n changes.push({\n type: \"add\",\n file: \".github/workflows/ci.yml\",\n description: \"Add CI workflow (other workflows exist)\",\n });\n }\n } else {\n changes.push({\n type: \"add\",\n file: \".github/workflows/ci.yml\",\n description: \"Create GitHub Actions CI workflow\",\n });\n }\n\n return {\n name: \"ci\",\n description: hasExisting\n ? \"Audit CI configuration\"\n : \"Set up GitHub Actions CI\",\n priority: \"low\",\n changes,\n dependencies: [],\n devDependencies: [],\n };\n}\n\n// ============================================================================\n// Audit Report Generation\n// ============================================================================\n\n/**\n * Generate a comprehensive audit report\n */\nexport async function generateAuditReport(\n projectPath: string = process.cwd(),\n): Promise<AuditReport> {\n const analysis = await analyzeProject(projectPath);\n\n // Collect all dependencies across plans\n const allDeps = new Set<string>();\n const allDevDeps = new Set<string>();\n\n for (const plan of analysis.setupPlans) {\n plan.dependencies.forEach((d) => allDeps.add(d));\n plan.devDependencies.forEach((d) => allDevDeps.add(d));\n }\n\n // Count total changes\n const totalChanges = analysis.setupPlans.reduce(\n (sum, plan) =>\n sum + plan.changes.filter((c) => c.type !== \"unchanged\").length,\n 0,\n );\n\n return {\n analysis,\n totalChanges,\n allDependencies: Array.from(allDeps),\n allDevDependencies: Array.from(allDevDeps),\n plans: analysis.setupPlans,\n };\n}\n\n/**\n * Format audit report for console display\n */\nexport function formatAuditReport(report: AuditReport): string {\n const lines: string[] = [];\n\n lines.push(\"📋 Auto-Setup Audit Report\\n\");\n lines.push(`Framework: ${report.analysis.framework}`);\n lines.push(`Package Manager: ${report.analysis.packageManager}`);\n lines.push(`TypeScript: ${report.analysis.isTypeScript ? \"Yes\" : \"No\"}`);\n lines.push(`Monorepo: ${report.analysis.isMonorepo ? \"Yes\" : \"No\"}\\n`);\n\n for (const plan of report.plans) {\n const hasChanges = plan.changes.some((c) => c.type !== \"unchanged\");\n const icon = hasChanges ? \"🔧\" : \"✓\";\n lines.push(\n `${icon} ${plan.name.charAt(0).toUpperCase() + plan.name.slice(1)}`,\n );\n\n for (const change of plan.changes) {\n const symbol =\n change.type === \"add\" ? \"+\" : change.type === \"modify\" ? \"~\" : \"=\";\n\n let line = ` ${symbol} ${change.description}`;\n if (\n change.key &&\n change.oldValue !== undefined &&\n change.newValue !== undefined\n ) {\n line += ` (${String(change.oldValue)} → ${String(change.newValue)})`;\n }\n lines.push(line);\n }\n\n if (plan.devDependencies.length > 0) {\n lines.push(` 📦 Install: ${plan.devDependencies.join(\", \")}`);\n }\n lines.push(\"\");\n }\n\n if (report.allDevDependencies.length > 0) {\n lines.push(\"Dependencies to install (batched):\");\n const pm = report.analysis.packageManager;\n const cmd =\n pm === \"npm\" ? \"npm install\" : pm === \"yarn\" ? \"yarn add\" : `${pm} add`;\n lines.push(` ${cmd} -D ${report.allDevDependencies.join(\" \")}`);\n lines.push(\"\");\n }\n\n lines.push(`Total changes: ${report.totalChanges}`);\n\n return lines.join(\"\\n\");\n}\n\n// ============================================================================\n// Setup Execution\n// ============================================================================\n\n/**\n * Execute all setup plans\n */\nexport async function runAllSetups(\n projectPath: string = process.cwd(),\n onProgress?: (step: string, status: \"start\" | \"done\" | \"error\") => void,\n): Promise<SetupResult[]> {\n const report = await generateAuditReport(projectPath);\n const results: SetupResult[] = [];\n const filesCreated: string[] = [];\n const filesUpdated: string[] = [];\n\n // Step 1: Batch install all dependencies\n if (report.allDevDependencies.length > 0) {\n onProgress?.(\"Installing dependencies\", \"start\");\n try {\n await installDependencies(\n projectPath,\n report.analysis.packageManager,\n report.allDevDependencies,\n );\n onProgress?.(\"Installing dependencies\", \"done\");\n } catch (error) {\n onProgress?.(\"Installing dependencies\", \"error\");\n results.push({\n success: false,\n name: \"dependencies\",\n message: `Failed to install: ${error instanceof Error ? error.message : String(error)}`,\n filesCreated: [],\n filesUpdated: [],\n packagesInstalled: [],\n });\n return results;\n }\n }\n\n // Step 2: Apply each setup\n for (const plan of report.plans) {\n const hasChanges = plan.changes.some((c) => c.type !== \"unchanged\");\n if (!hasChanges && plan.devDependencies.length === 0) continue;\n\n onProgress?.(`Setting up ${plan.name}`, \"start\");\n\n try {\n const result = await applySetupPlan(projectPath, plan, report.analysis);\n results.push(result);\n filesCreated.push(...result.filesCreated);\n filesUpdated.push(...result.filesUpdated);\n onProgress?.(`Setting up ${plan.name}`, \"done\");\n } catch (error) {\n onProgress?.(`Setting up ${plan.name}`, \"error\");\n results.push({\n success: false,\n name: plan.name,\n message: `Failed: ${error instanceof Error ? error.message : String(error)}`,\n filesCreated: [],\n filesUpdated: [],\n packagesInstalled: [],\n });\n }\n }\n\n // Step 3: Initialize git hooks\n onProgress?.(\"Initializing git hooks\", \"start\");\n try {\n await execa(\"npx\", [\"simple-git-hooks\"], {\n cwd: projectPath,\n stdio: \"pipe\",\n });\n onProgress?.(\"Initializing git hooks\", \"done\");\n } catch {\n // May fail if not in a git repo\n onProgress?.(\"Initializing git hooks\", \"error\");\n }\n\n return results;\n}\n\nasync function installDependencies(\n projectPath: string,\n packageManager: PackageManager,\n packages: string[],\n): Promise<void> {\n if (packages.length === 0) return;\n\n const commands: Record<PackageManager, { cmd: string; args: string[] }> = {\n npm: { cmd: \"npm\", args: [\"install\", \"--save-dev\"] },\n pnpm: { cmd: \"pnpm\", args: [\"add\", \"-D\"] },\n yarn: { cmd: \"yarn\", args: [\"add\", \"-D\"] },\n bun: { cmd: \"bun\", args: [\"add\", \"-D\"] },\n };\n\n const { cmd, args } = commands[packageManager];\n await execa(cmd, [...args, ...packages], {\n cwd: projectPath,\n stdio: \"pipe\",\n });\n}\n\nasync function applySetupPlan(\n projectPath: string,\n plan: SetupPlan,\n analysis: ProjectAnalysis,\n): Promise<SetupResult> {\n const filesCreated: string[] = [];\n const filesUpdated: string[] = [];\n\n switch (plan.name) {\n case \"typescript\":\n await applyTypeScriptSetup(\n projectPath,\n analysis,\n filesCreated,\n filesUpdated,\n );\n break;\n case \"eslint\":\n await applyESLintSetup(projectPath, analysis, filesCreated, filesUpdated);\n break;\n case \"prettier\":\n await applyPrettierSetup(projectPath, filesCreated, filesUpdated);\n break;\n case \"testing\":\n await applyTestingSetup(\n projectPath,\n analysis,\n filesCreated,\n filesUpdated,\n );\n break;\n case \"build\":\n await applyBuildSetup(projectPath, filesCreated, filesUpdated);\n break;\n case \"scripts\":\n await applyScriptsSetup(projectPath, analysis, filesUpdated);\n break;\n case \"hooks\":\n await applyHooksSetup(projectPath, filesUpdated);\n break;\n case \"ci\":\n await applyCISetup(projectPath, analysis, filesCreated, filesUpdated);\n break;\n }\n\n return {\n success: true,\n name: plan.name,\n message: `${plan.name} configured successfully`,\n filesCreated,\n filesUpdated,\n packagesInstalled: plan.devDependencies,\n };\n}\n\n// ============================================================================\n// Setup Application Functions\n// ============================================================================\n\nasync function applyTypeScriptSetup(\n projectPath: string,\n analysis: ProjectAnalysis,\n filesCreated: string[],\n filesUpdated: string[],\n): Promise<void> {\n const configName = analysis.isMonorepo\n ? \"tsconfig.base.json\"\n : \"tsconfig.json\";\n const configPath = join(projectPath, configName);\n\n let tsconfig: Record<string, unknown> = {};\n\n if (existsSync(configPath)) {\n tsconfig = await readJsonFile(configPath);\n filesUpdated.push(configName);\n } else {\n filesCreated.push(configName);\n }\n\n // Ensure compilerOptions\n if (!tsconfig.compilerOptions) {\n tsconfig.compilerOptions = {};\n }\n const opts = tsconfig.compilerOptions as Record<string, unknown>;\n\n // Apply improvements (merge with existing)\n const improvements: Record<string, unknown> = {\n target: opts.target || \"ES2022\",\n module: opts.module || \"ESNext\",\n moduleResolution: opts.moduleResolution || \"bundler\",\n esModuleInterop: opts.esModuleInterop ?? true,\n strict: opts.strict ?? true,\n skipLibCheck: opts.skipLibCheck ?? true,\n resolveJsonModule: opts.resolveJsonModule ?? true,\n isolatedModules: opts.isolatedModules ?? true,\n declaration: opts.declaration ?? true,\n declarationMap: opts.declarationMap ?? true,\n sourceMap: opts.sourceMap ?? true,\n };\n\n // Framework-specific options\n const frameworkOpts = getFrameworkTsOptions(analysis.framework);\n\n tsconfig.compilerOptions = { ...opts, ...improvements, ...frameworkOpts };\n\n // Ensure include/exclude\n if (!tsconfig.include) {\n tsconfig.include = [\"src/**/*\"];\n }\n if (!tsconfig.exclude) {\n tsconfig.exclude = [\"node_modules\", \"dist\", \"coverage\"];\n }\n\n await writeFile(configPath, JSON.stringify(tsconfig, null, 2) + \"\\n\");\n}\n\nfunction getFrameworkTsOptions(\n framework: FrameworkType,\n): Record<string, unknown> {\n switch (framework) {\n case \"nextjs\":\n return {\n lib: [\"dom\", \"dom.iterable\", \"esnext\"],\n jsx: \"preserve\",\n incremental: true,\n plugins: [{ name: \"next\" }],\n };\n case \"react\":\n case \"remix\":\n return {\n lib: [\"dom\", \"dom.iterable\", \"esnext\"],\n jsx: \"react-jsx\",\n };\n case \"vue\":\n case \"nuxt\":\n return {\n lib: [\"esnext\", \"dom\"],\n jsx: \"preserve\",\n };\n default:\n return {};\n }\n}\n\nasync function applyESLintSetup(\n projectPath: string,\n analysis: ProjectAnalysis,\n filesCreated: string[],\n _filesUpdated: string[],\n): Promise<void> {\n // Only create new config if no flat config exists\n if (analysis.existing.eslintFlat) {\n return;\n }\n\n const configPath = join(projectPath, \"eslint.config.mjs\");\n const config = generateESLintFlatConfig(\n analysis.isTypeScript,\n analysis.framework,\n );\n\n await writeFile(configPath, config);\n filesCreated.push(\"eslint.config.mjs\");\n}\n\nfunction generateESLintFlatConfig(\n isTypeScript: boolean,\n framework: FrameworkType,\n): string {\n const imports: string[] = [];\n const configs: string[] = [];\n\n if (isTypeScript) {\n imports.push(`import tseslint from \"typescript-eslint\";`);\n }\n\n // Add react plugin import if needed\n if (framework === \"react\" || framework === \"nextjs\") {\n imports.push(`import react from \"eslint-plugin-react\";`);\n imports.push(`import reactHooks from \"eslint-plugin-react-hooks\";`);\n }\n\n // Base config\n if (isTypeScript) {\n configs.push(` ...tseslint.configs.recommended`);\n }\n\n configs.push(` {\n files: [\"**/*.${isTypeScript ? \"{ts,tsx}\" : \"{js,jsx}\"}\"],\n rules: {\n ${isTypeScript ? `\"@typescript-eslint/no-unused-vars\": [\"error\", { argsIgnorePattern: \"^_\" }],` : \"\"}\n \"no-console\": \"warn\",\n },\n }`);\n\n configs.push(` {\n ignores: [\"dist/\", \"node_modules/\", \"coverage/\", \".next/\", \"build/\"],\n }`);\n\n return `${imports.join(\"\\n\")}\n\nexport default [\n${configs.join(\",\\n\")}\n];\n`;\n}\n\nasync function applyPrettierSetup(\n projectPath: string,\n filesCreated: string[],\n filesUpdated: string[],\n): Promise<void> {\n const prettierPath = join(projectPath, \".prettierrc\");\n\n let config: Record<string, unknown> = {\n semi: true,\n singleQuote: false,\n tabWidth: 2,\n trailingComma: \"es5\",\n printWidth: 100,\n bracketSpacing: true,\n };\n\n if (existsSync(prettierPath)) {\n const existing = await readPrettierConfig(projectPath);\n config = { ...config, ...existing };\n filesUpdated.push(\".prettierrc\");\n } else {\n filesCreated.push(\".prettierrc\");\n }\n\n await writeFile(prettierPath, JSON.stringify(config, null, 2) + \"\\n\");\n\n // Create .prettierignore if it doesn't exist\n const ignorePath = join(projectPath, \".prettierignore\");\n if (!existsSync(ignorePath)) {\n const ignoreContent = `dist/\nnode_modules/\ncoverage/\n.next/\nbuild/\n*.min.js\npnpm-lock.yaml\npackage-lock.json\nyarn.lock\n`;\n await writeFile(ignorePath, ignoreContent);\n filesCreated.push(\".prettierignore\");\n }\n}\n\nasync function applyTestingSetup(\n projectPath: string,\n analysis: ProjectAnalysis,\n filesCreated: string[],\n _filesUpdated: string[],\n): Promise<void> {\n // Skip if jest exists or vitest already configured\n if (analysis.existing.jest || analysis.existing.vitest) {\n return;\n }\n\n const ext = analysis.isTypeScript ? \"ts\" : \"js\";\n const configPath = join(projectPath, `vitest.config.${ext}`);\n\n const environment = [\"react\", \"nextjs\", \"vue\", \"nuxt\", \"svelte\"].includes(\n analysis.framework,\n )\n ? \"jsdom\"\n : \"node\";\n\n const config = `import { defineConfig } from \"vitest/config\";\n\nexport default defineConfig({\n test: {\n globals: true,\n environment: \"${environment}\",\n coverage: {\n provider: \"v8\",\n reporter: [\"text\", \"json\", \"html\"],\n exclude: [\"node_modules/\", \"dist/\", \"**/*.test.${ext}\"],\n },\n include: [\"src/**/*.test.${ext}\", \"tests/**/*.test.${ext}\"],\n },\n});\n`;\n\n await writeFile(configPath, config);\n filesCreated.push(`vitest.config.${ext}`);\n}\n\nasync function applyBuildSetup(\n projectPath: string,\n filesCreated: string[],\n _filesUpdated: string[],\n): Promise<void> {\n const configPath = join(projectPath, \"tsup.config.ts\");\n\n if (existsSync(configPath)) {\n return;\n }\n\n const config = `import { defineConfig } from \"tsup\";\n\nexport default defineConfig({\n entry: [\"src/index.ts\"],\n format: [\"esm\"],\n dts: true,\n clean: true,\n sourcemap: true,\n});\n`;\n\n await writeFile(configPath, config);\n filesCreated.push(\"tsup.config.ts\");\n}\n\nasync function applyScriptsSetup(\n projectPath: string,\n analysis: ProjectAnalysis,\n filesUpdated: string[],\n): Promise<void> {\n const pkgPath = join(projectPath, \"package.json\");\n const pkg = await readPackageJson(projectPath);\n const scripts = pkg.scripts || {};\n\n // Add missing scripts (don't overwrite)\n const scriptsToAdd: Record<string, string> = {\n lint: \"eslint src\",\n \"lint:fix\": \"eslint src --fix\",\n format: 'prettier --write \"src/**/*.{ts,tsx,js,jsx,json}\"',\n \"format:check\": 'prettier --check \"src/**/*.{ts,tsx,js,jsx,json}\"',\n test: \"vitest run\",\n \"test:watch\": \"vitest\",\n \"test:coverage\": \"vitest run --coverage\",\n verify: \"workflow-agent verify\",\n \"verify:fix\": \"workflow-agent verify --fix\",\n \"pre-commit\": \"workflow-agent verify --fix\",\n };\n\n if (analysis.isTypeScript) {\n scriptsToAdd.typecheck = \"tsc --noEmit\";\n }\n\n let added = false;\n for (const [name, cmd] of Object.entries(scriptsToAdd)) {\n if (!scripts[name]) {\n scripts[name] = cmd;\n added = true;\n }\n }\n\n if (added) {\n pkg.scripts = scripts;\n await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + \"\\n\");\n filesUpdated.push(\"package.json\");\n }\n}\n\nasync function applyHooksSetup(\n projectPath: string,\n filesUpdated: string[],\n): Promise<void> {\n const pkgPath = join(projectPath, \"package.json\");\n const pkg = await readPackageJson(projectPath);\n\n // Add simple-git-hooks config\n if (!pkg[\"simple-git-hooks\"]) {\n pkg[\"simple-git-hooks\"] = {\n \"pre-commit\": \"npx lint-staged\",\n };\n }\n\n // Add lint-staged config\n if (!pkg[\"lint-staged\"]) {\n pkg[\"lint-staged\"] = {\n \"*.{ts,tsx,js,jsx}\": [\"eslint --fix\", \"prettier --write\"],\n \"*.{json,md,yml,yaml}\": [\"prettier --write\"],\n };\n }\n\n await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + \"\\n\");\n filesUpdated.push(\"package.json\");\n}\n\nasync function applyCISetup(\n projectPath: string,\n analysis: ProjectAnalysis,\n filesCreated: string[],\n _filesUpdated: string[],\n): Promise<void> {\n const workflowsDir = join(projectPath, \".github/workflows\");\n await mkdir(workflowsDir, { recursive: true });\n\n const ciPath = join(workflowsDir, \"ci.yml\");\n\n if (existsSync(ciPath)) {\n return;\n }\n\n const workflow = generateCIWorkflow(\n analysis.packageManager,\n analysis.isTypeScript,\n analysis.framework,\n analysis.isMonorepo,\n );\n\n await writeFile(ciPath, workflow);\n filesCreated.push(\".github/workflows/ci.yml\");\n}\n\nfunction generateCIWorkflow(\n packageManager: PackageManager,\n isTypeScript: boolean,\n framework: FrameworkType,\n _isMonorepo: boolean,\n): string {\n const runCmd =\n packageManager === \"npm\"\n ? \"npm run\"\n : packageManager === \"yarn\"\n ? \"yarn\"\n : packageManager;\n const isPnpm = packageManager === \"pnpm\";\n\n return `name: CI\n\non:\n push:\n branches: [main, master]\n pull_request:\n branches: [main, master]\n\njobs:\n ci:\n runs-on: ubuntu-latest\n\n steps:\n - name: Checkout\n uses: actions/checkout@v4\n\n - name: Setup Node.js\n uses: actions/setup-node@v4\n with:\n node-version: \"20\"\n${\n isPnpm\n ? `\n - name: Install pnpm\n uses: pnpm/action-setup@v4\n with:\n version: 9\n`\n : \"\"\n}\n - name: Install dependencies\n run: ${packageManager} install\n\n${\n isTypeScript\n ? ` - name: Type check\n run: ${runCmd} typecheck\n\n`\n : \"\"\n} - name: Lint\n run: ${runCmd} lint\n\n - name: Format check\n run: ${runCmd} format:check || true\n\n - name: Test\n run: ${runCmd} test\n${\n isTypeScript && ![\"nextjs\", \"remix\", \"nuxt\"].includes(framework)\n ? `\n - name: Build\n run: ${runCmd} build\n`\n : \"\"\n}`;\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\nasync function readPackageJson(projectPath: string): Promise<PackageJson> {\n const pkgPath = join(projectPath, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n return JSON.parse(await readFile(pkgPath, \"utf-8\")) as PackageJson;\n}\n\nasync function readTSConfig(filePath: string): Promise<TSConfig> {\n if (!existsSync(filePath)) {\n return {};\n }\n return JSON.parse(await readFile(filePath, \"utf-8\")) as TSConfig;\n}\n\nasync function readJsonFile(\n filePath: string,\n): Promise<Record<string, unknown>> {\n if (!existsSync(filePath)) {\n return {};\n }\n return JSON.parse(await readFile(filePath, \"utf-8\"));\n}\n\nasync function readPrettierConfig(\n projectPath: string,\n): Promise<Record<string, unknown>> {\n const files = [\".prettierrc\", \".prettierrc.json\", \"prettier.config.js\"];\n\n for (const file of files) {\n const filePath = join(projectPath, file);\n if (existsSync(filePath)) {\n if (file.endsWith(\".js\")) {\n return {}; // Can't easily read JS config\n }\n try {\n return JSON.parse(await readFile(filePath, \"utf-8\"));\n } catch {\n return {};\n }\n }\n }\n\n return {};\n}\n","/**\n * Git repository utilities for detecting repository info,\n * package manager, monorepo setup, and GitHub remote\n */\n\nimport { execa } from \"execa\";\nimport { existsSync } from \"fs\";\nimport { readFile } from \"fs/promises\";\nimport { join } from \"path\";\n\nexport type PackageManager = \"npm\" | \"pnpm\" | \"yarn\" | \"bun\";\n\nexport interface GitHubInfo {\n owner: string;\n repo: string;\n}\n\nexport interface RepoInfo {\n isGitRepo: boolean;\n remoteUrl: string | null;\n isGitHub: boolean;\n github: GitHubInfo | null;\n defaultBranch: string | null;\n}\n\nexport interface ProjectInfo {\n packageManager: PackageManager;\n isMonorepo: boolean;\n hasLintScript: boolean;\n hasTypecheckScript: boolean;\n hasFormatScript: boolean;\n hasTestScript: boolean;\n hasBuildScript: boolean;\n}\n\n/**\n * Check if the current directory is a git repository\n */\nexport async function isGitRepo(\n projectPath: string = process.cwd(),\n): Promise<boolean> {\n try {\n await execa(\"git\", [\"rev-parse\", \"--git-dir\"], { cwd: projectPath });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get the git remote URL for origin\n */\nexport async function getGitRemoteUrl(\n projectPath: string = process.cwd(),\n): Promise<string | null> {\n try {\n const { stdout } = await execa(\"git\", [\"remote\", \"get-url\", \"origin\"], {\n cwd: projectPath,\n });\n return stdout.trim() || null;\n } catch {\n return null;\n }\n}\n\n/**\n * Check if the remote URL is a GitHub repository\n */\nexport function isGitHubRemote(remoteUrl: string | null): boolean {\n if (!remoteUrl) return false;\n return remoteUrl.includes(\"github.com\");\n}\n\n/**\n * Parse GitHub owner and repo from remote URL\n * Supports both SSH (git@github.com:owner/repo.git) and HTTPS (https://github.com/owner/repo.git)\n */\nexport function parseGitHubUrl(remoteUrl: string | null): GitHubInfo | null {\n if (!remoteUrl || !isGitHubRemote(remoteUrl)) return null;\n\n // Match: git@github.com:owner/repo.git or https://github.com/owner/repo.git\n const match = remoteUrl.match(/github\\.com[:/]([^/]+)\\/([^/.]+)/);\n\n if (match) {\n return {\n owner: match[1],\n repo: match[2].replace(/\\.git$/, \"\"),\n };\n }\n\n return null;\n}\n\n/**\n * Get the default branch name\n */\nexport async function getDefaultBranch(\n projectPath: string = process.cwd(),\n): Promise<string | null> {\n try {\n // Try to get from remote\n const { stdout } = await execa(\n \"git\",\n [\"symbolic-ref\", \"refs/remotes/origin/HEAD\"],\n {\n cwd: projectPath,\n },\n );\n return stdout.trim().replace(\"refs/remotes/origin/\", \"\") || \"main\";\n } catch {\n // Fallback: try HEAD\n try {\n const { stdout } = await execa(\n \"git\",\n [\"rev-parse\", \"--abbrev-ref\", \"HEAD\"],\n {\n cwd: projectPath,\n },\n );\n return stdout.trim() || \"main\";\n } catch {\n return \"main\";\n }\n }\n}\n\n/**\n * Get comprehensive repository information\n */\nexport async function getRepoInfo(\n projectPath: string = process.cwd(),\n): Promise<RepoInfo> {\n const isRepo = await isGitRepo(projectPath);\n\n if (!isRepo) {\n return {\n isGitRepo: false,\n remoteUrl: null,\n isGitHub: false,\n github: null,\n defaultBranch: null,\n };\n }\n\n const remoteUrl = await getGitRemoteUrl(projectPath);\n const isGitHub = isGitHubRemote(remoteUrl);\n const github = parseGitHubUrl(remoteUrl);\n const defaultBranch = await getDefaultBranch(projectPath);\n\n return {\n isGitRepo: true,\n remoteUrl,\n isGitHub,\n github,\n defaultBranch,\n };\n}\n\n/**\n * Detect the package manager used in the project\n */\nexport async function detectPackageManager(\n projectPath: string = process.cwd(),\n): Promise<PackageManager> {\n // Check for lockfiles in order of preference\n if (existsSync(join(projectPath, \"pnpm-lock.yaml\"))) {\n return \"pnpm\";\n }\n if (existsSync(join(projectPath, \"yarn.lock\"))) {\n return \"yarn\";\n }\n if (existsSync(join(projectPath, \"bun.lockb\"))) {\n return \"bun\";\n }\n if (existsSync(join(projectPath, \"package-lock.json\"))) {\n return \"npm\";\n }\n\n // Check packageManager field in package.json\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n if (pkg.packageManager) {\n if (pkg.packageManager.startsWith(\"pnpm\")) return \"pnpm\";\n if (pkg.packageManager.startsWith(\"yarn\")) return \"yarn\";\n if (pkg.packageManager.startsWith(\"bun\")) return \"bun\";\n }\n }\n } catch {\n // Ignore parse errors\n }\n\n // Default to npm\n return \"npm\";\n}\n\n/**\n * Check if the project is a monorepo\n */\nexport async function isMonorepo(\n projectPath: string = process.cwd(),\n): Promise<boolean> {\n // Check for pnpm workspace\n if (existsSync(join(projectPath, \"pnpm-workspace.yaml\"))) {\n return true;\n }\n\n // Check for yarn/npm workspaces in package.json\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n if (pkg.workspaces) {\n return true;\n }\n }\n } catch {\n // Ignore parse errors\n }\n\n // Check for lerna.json\n if (existsSync(join(projectPath, \"lerna.json\"))) {\n return true;\n }\n\n // Check for nx.json\n if (existsSync(join(projectPath, \"nx.json\"))) {\n return true;\n }\n\n // Check for turbo.json\n if (existsSync(join(projectPath, \"turbo.json\"))) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Get available scripts from package.json\n */\nexport async function getPackageScripts(\n projectPath: string = process.cwd(),\n): Promise<Record<string, string>> {\n try {\n const pkgPath = join(projectPath, \"package.json\");\n if (!existsSync(pkgPath)) {\n return {};\n }\n const pkg = JSON.parse(await readFile(pkgPath, \"utf-8\"));\n return pkg.scripts || {};\n } catch {\n return {};\n }\n}\n\n/**\n * Get comprehensive project information\n */\nexport async function getProjectInfo(\n projectPath: string = process.cwd(),\n): Promise<ProjectInfo> {\n const packageManager = await detectPackageManager(projectPath);\n const monorepo = await isMonorepo(projectPath);\n const scripts = await getPackageScripts(projectPath);\n\n return {\n packageManager,\n isMonorepo: monorepo,\n hasLintScript: \"lint\" in scripts,\n hasTypecheckScript: \"typecheck\" in scripts || \"type-check\" in scripts,\n hasFormatScript: \"format\" in scripts || \"format:check\" in scripts,\n hasTestScript: \"test\" in scripts,\n hasBuildScript: \"build\" in scripts,\n };\n}\n\n/**\n * Get the install command for a package manager\n */\nexport function getInstallCommand(packageManager: PackageManager): string {\n switch (packageManager) {\n case \"pnpm\":\n return \"pnpm install --frozen-lockfile\";\n case \"yarn\":\n return \"yarn install --frozen-lockfile\";\n case \"bun\":\n return \"bun install --frozen-lockfile\";\n case \"npm\":\n default:\n return \"npm ci\";\n }\n}\n\n/**\n * Get the run command for a package manager (handles monorepo -r flag for pnpm)\n */\nexport function getRunCommand(\n packageManager: PackageManager,\n script: string,\n isMonorepo: boolean = false,\n): string {\n switch (packageManager) {\n case \"pnpm\":\n return isMonorepo ? `pnpm -r run ${script}` : `pnpm run ${script}`;\n case \"yarn\":\n return isMonorepo\n ? `yarn workspaces run ${script}`\n : `yarn run ${script}`;\n case \"bun\":\n return `bun run ${script}`;\n case \"npm\":\n default:\n return isMonorepo\n ? `npm run ${script} --workspaces --if-present`\n : `npm run ${script}`;\n }\n}\n"],"mappings":";AAOA,SAAS,aAA8B;AACvC,OAAO,WAAW;AAkDX,IAAM,iBAAoC;AAAA,EAC/C;AAAA,IACE,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,MAAM,CAAC,WAAW;AAAA,IAClB,YAAY;AAAA;AAAA,EACd;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,MAAM,CAAC,MAAM;AAAA,IACb,YAAY;AAAA,IACZ,SAAS,CAAC,QAAQ,OAAO;AAAA,IACzB,YAAY;AAAA,EACd;AAAA,EACA;AAAA,IACE,MAAM;AAAA,IACN,aAAa;AAAA,IACb,SAAS;AAAA,IACT,MAAM,CAAC,UAAU,SAAS;AAAA,IAC1B,YAAY;AAAA,IACZ,SAAS,CAAC,QAAQ;AAAA,IAClB,YAAY;AAAA,EAC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isMonorepo","execa"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/scripts/copilot-instructions-generator.ts","../src/scripts/workflow-scripts.ts","../src/scripts/template-installer.ts","../src/templates/metadata.ts"],"sourcesContent":["/**\n * Copilot Instructions Generator\n *\n * Generates .github/copilot-instructions.md from the project's guidelines directory.\n * This file serves as the Single Source of Truth for AI agents (GitHub Copilot, Claude, etc.)\n * when working on the codebase.\n *\n * Features:\n * - Reads all markdown files from guidelines/\n * - Extracts key rules and summaries from each guideline\n * - Loads project config from workflow.config.json\n * - Preserves custom user content between markers\n * - Provides links to full guideline documents\n */\n\nimport { readFileSync, writeFileSync, existsSync, readdirSync, mkdirSync } from \"fs\";\nimport { join, basename } from \"path\";\n\n// Markers for custom user content that should be preserved on regeneration\nconst CUSTOM_START_MARKER = \"<!-- CUSTOM START -->\";\nconst CUSTOM_END_MARKER = \"<!-- CUSTOM END -->\";\nconst GENERATED_MARKER = \"<!-- AUTO-GENERATED BY WORKFLOW-AGENT - DO NOT EDIT ABOVE THIS LINE -->\";\n\ninterface WorkflowConfig {\n projectName?: string;\n scopes?: Array<{ name: string; description: string; emoji?: string }>;\n enforcement?: string;\n language?: string;\n}\n\ninterface GuidelineSummary {\n filename: string;\n title: string;\n description: string;\n keyRules: string[];\n}\n\n/**\n * Extract title from markdown content (first H1)\n */\nfunction extractTitle(content: string): string {\n const match = content.match(/^#\\s+(.+)$/m);\n return match ? match[1].trim() : \"Untitled\";\n}\n\n/**\n * Extract description from markdown content (first paragraph after title)\n */\nfunction extractDescription(content: string): string {\n // Look for content after the first heading, before the next heading or section\n const lines = content.split(\"\\n\");\n let foundTitle = false;\n let description = \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"# \")) {\n foundTitle = true;\n continue;\n }\n if (foundTitle) {\n // Skip empty lines and blockquotes at start\n if (line.trim() === \"\" || line.startsWith(\">\")) {\n if (description) break; // End if we already have content\n continue;\n }\n // Stop at next heading or horizontal rule\n if (line.startsWith(\"#\") || line.startsWith(\"---\") || line.startsWith(\"##\")) {\n break;\n }\n description += line.trim() + \" \";\n // Take only first meaningful paragraph\n if (description.length > 150) break;\n }\n }\n\n return description.trim().slice(0, 200) + (description.length > 200 ? \"...\" : \"\");\n}\n\n/**\n * Extract key rules from markdown content\n * Looks for lists, bold text, and important patterns\n */\nfunction extractKeyRules(content: string, maxRules: number = 5): string[] {\n const rules: string[] = [];\n\n // Pattern 1: Look for \"MUST\", \"NEVER\", \"ALWAYS\", \"REQUIRED\" in bold or emphasized\n const emphasisPatterns = [\n /\\*\\*(?:MUST|NEVER|ALWAYS|REQUIRED)[^*]+\\*\\*/gi,\n /(?:^|\\n)\\s*[-*]\\s+\\*\\*[^*]+\\*\\*/gm,\n ];\n\n for (const pattern of emphasisPatterns) {\n const matches = content.match(pattern);\n if (matches) {\n for (const match of matches.slice(0, 2)) {\n const cleaned = match.replace(/\\*\\*/g, \"\").replace(/^[-*]\\s*/, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n // Pattern 2: Look for numbered or bulleted rules under headings containing \"Rules\", \"Requirements\", \"Guidelines\"\n const rulesSectionMatch = content.match(/##\\s+(?:.*(?:Rules?|Requirements?|Guidelines?|Standards?)[^\\n]*)\\n([\\s\\S]*?)(?=\\n##|\\n#|$)/i);\n if (rulesSectionMatch) {\n const section = rulesSectionMatch[1];\n const listItems = section.match(/^\\s*[-*\\d.]+\\s+(.+)$/gm);\n if (listItems) {\n for (const item of listItems.slice(0, 3)) {\n const cleaned = item.replace(/^[-*\\d.]+\\s*/, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n // Pattern 3: Look for key points under \"Important\", \"Critical\", \"Key\"\n const importantMatch = content.match(/(?:Important|Critical|Key|Essential)[:\\s]+([^\\n]+)/gi);\n if (importantMatch) {\n for (const match of importantMatch.slice(0, 2)) {\n const cleaned = match.replace(/^(?:Important|Critical|Key|Essential)[:\\s]+/i, \"\").trim();\n if (cleaned.length > 10 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n\n // Fallback: Get first few list items if we don't have enough rules\n if (rules.length < 2) {\n const listItems = content.match(/^\\s*[-*]\\s+(.+)$/gm);\n if (listItems) {\n for (const item of listItems.slice(0, 3)) {\n const cleaned = item.replace(/^[-*]\\s*/, \"\").trim();\n if (cleaned.length > 15 && cleaned.length < 150 && !rules.includes(cleaned)) {\n rules.push(cleaned);\n }\n }\n }\n }\n\n return rules.slice(0, maxRules);\n}\n\n/**\n * Parse a guideline markdown file and extract summary\n */\nfunction parseGuideline(filePath: string): GuidelineSummary | null {\n try {\n const content = readFileSync(filePath, \"utf-8\");\n const filename = basename(filePath);\n\n // Skip template example and non-guideline files\n if (filename.startsWith(\"_\") || filename === \"Guidelines.md\") {\n return null;\n }\n\n return {\n filename,\n title: extractTitle(content),\n description: extractDescription(content),\n keyRules: extractKeyRules(content),\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Load workflow config from project root\n */\nfunction loadWorkflowConfig(projectRoot: string): WorkflowConfig | null {\n const configPath = join(projectRoot, \"workflow.config.json\");\n if (!existsSync(configPath)) {\n return null;\n }\n\n try {\n const content = readFileSync(configPath, \"utf-8\");\n return JSON.parse(content) as WorkflowConfig;\n } catch {\n return null;\n }\n}\n\n/**\n * Extract preserved custom content from existing file\n */\nfunction extractCustomContent(existingContent: string): string | null {\n const startIndex = existingContent.indexOf(CUSTOM_START_MARKER);\n const endIndex = existingContent.indexOf(CUSTOM_END_MARKER);\n\n if (startIndex !== -1 && endIndex !== -1 && endIndex > startIndex) {\n return existingContent.slice(\n startIndex + CUSTOM_START_MARKER.length,\n endIndex\n ).trim();\n }\n\n return null;\n}\n\n/**\n * Generate the copilot-instructions.md content\n */\nfunction generateInstructionsContent(\n config: WorkflowConfig | null,\n guidelines: GuidelineSummary[],\n customContent: string | null\n): string {\n const projectName = config?.projectName || \"this project\";\n const scopes = config?.scopes || [];\n\n let content = `# Copilot Instructions for ${projectName}\n\n> **This file is the Single Source of Truth for AI agents working on this codebase.**\n> It is auto-generated from the \\`guidelines/\\` directory by workflow-agent-cli.\n> Last generated: ${new Date().toISOString().split(\"T\")[0]}\n\n${GENERATED_MARKER}\n\n## Project Overview\n\n`;\n\n if (config) {\n content += `- **Project Name**: ${projectName}\\n`;\n content += `- **Enforcement Level**: ${config.enforcement || \"strict\"}\\n`;\n if (scopes.length > 0) {\n content += `- **Available Scopes**: ${scopes.map(s => `\\`${s.name}\\``).join(\", \")}\\n`;\n }\n content += \"\\n\";\n }\n\n // Add scope reference if available\n if (scopes.length > 0) {\n content += `### Valid Scopes for Commits and Branches\n\n| Scope | Description |\n|-------|-------------|\n`;\n for (const scope of scopes.slice(0, 15)) {\n content += `| \\`${scope.name}\\` | ${scope.description} |\\n`;\n }\n if (scopes.length > 15) {\n content += `| ... | See workflow.config.json for all ${scopes.length} scopes |\\n`;\n }\n content += \"\\n\";\n }\n\n // Add guidelines summaries\n if (guidelines.length > 0) {\n content += `## Guidelines Summary\n\nThe following guidelines govern development on this project. **Read the linked documents for full details.**\n\n`;\n\n // Group by importance (mandatory templates first)\n const mandatoryFiles = [\n \"AGENT_EDITING_INSTRUCTIONS.md\",\n \"BRANCHING_STRATEGY.md\",\n \"TESTING_STRATEGY.md\",\n \"SINGLE_SOURCE_OF_TRUTH.md\",\n \"PATTERN_ANALYSIS_WORKFLOW.md\",\n \"SELF_IMPROVEMENT_MANDATE.md\",\n ];\n\n const sortedGuidelines = [...guidelines].sort((a, b) => {\n const aIndex = mandatoryFiles.indexOf(a.filename);\n const bIndex = mandatoryFiles.indexOf(b.filename);\n if (aIndex !== -1 && bIndex !== -1) return aIndex - bIndex;\n if (aIndex !== -1) return -1;\n if (bIndex !== -1) return 1;\n return a.title.localeCompare(b.title);\n });\n\n for (const guideline of sortedGuidelines) {\n content += `### ${guideline.title}\n\n📄 [See full details](../guidelines/${guideline.filename})\n\n${guideline.description}\n\n`;\n if (guideline.keyRules.length > 0) {\n content += `**Key Rules:**\n`;\n for (const rule of guideline.keyRules) {\n content += `- ${rule}\\n`;\n }\n content += \"\\n\";\n }\n }\n }\n\n // Add quick reference section\n content += `## Quick Reference\n\n### Branch Naming Convention\n\\`\\`\\`\n<type>/<scope>/<short-description>\n\\`\\`\\`\n\n**Types**: \\`feature\\`, \\`fix\\`, \\`chore\\`, \\`docs\\`, \\`refactor\\`, \\`test\\`, \\`perf\\`\n\n### Commit Message Format\n\\`\\`\\`\n<type>(<scope>): <description>\n\n[optional body]\n\n[optional footer]\n\\`\\`\\`\n\n### Before Making Changes\n1. Read the relevant guideline document in \\`guidelines/\\`\n2. Check for existing patterns in \\`workflow:solution:search\\`\n3. Create an implementation plan for multi-file changes\n4. Ensure tests are added for new functionality\n\n### Before Committing\n1. Run \\`pnpm run workflow:verify\\` to validate all changes\n2. Ensure branch name follows convention\n3. Ensure commit message follows conventional commits format\n\n`;\n\n // Add custom content section\n content += `## Project-Specific Instructions\n\n${CUSTOM_START_MARKER}\n${customContent || `\n<!-- \nAdd your project-specific instructions here.\nThis section will be preserved when the file is regenerated.\n\nExamples:\n- Specific coding patterns unique to this project\n- Custom review requirements\n- Domain-specific terminology\n- Team-specific workflows\n-->\n`}\n${CUSTOM_END_MARKER}\n\n---\n\n*This file was generated by [workflow-agent-cli](https://www.npmjs.com/package/workflow-agent-cli). Run \\`pnpm run workflow:generate-instructions\\` to regenerate.*\n`;\n\n return content;\n}\n\n/**\n * Result of generating copilot instructions\n */\nexport interface GenerateResult {\n success: boolean;\n filePath: string | null;\n guidelinesCount: number;\n isNew: boolean;\n preservedCustomContent: boolean;\n error?: string;\n}\n\n/**\n * Generate .github/copilot-instructions.md from guidelines directory\n *\n * @param projectRoot - Root directory of the project\n * @param options - Generation options\n * @returns Result of the generation\n */\nexport function generateCopilotInstructions(\n projectRoot: string,\n options: { force?: boolean; silent?: boolean } = {}\n): GenerateResult {\n const { force: _force = false, silent = false } = options;\n\n const guidelinesDir = join(projectRoot, \"guidelines\");\n const githubDir = join(projectRoot, \".github\");\n const outputPath = join(githubDir, \"copilot-instructions.md\");\n\n // Check if guidelines directory exists\n if (!existsSync(guidelinesDir)) {\n if (!silent) {\n // Guidelines don't exist yet - skip silently during postinstall\n }\n return {\n success: false,\n filePath: null,\n guidelinesCount: 0,\n isNew: false,\n preservedCustomContent: false,\n error: \"No guidelines directory found. Run 'workflow init' first.\",\n };\n }\n\n // Read all markdown files from guidelines\n const files = readdirSync(guidelinesDir).filter(f => f.endsWith(\".md\"));\n if (files.length === 0) {\n return {\n success: false,\n filePath: null,\n guidelinesCount: 0,\n isNew: false,\n preservedCustomContent: false,\n error: \"No markdown files found in guidelines directory.\",\n };\n }\n\n // Parse each guideline\n const guidelines: GuidelineSummary[] = [];\n for (const file of files) {\n const summary = parseGuideline(join(guidelinesDir, file));\n if (summary) {\n guidelines.push(summary);\n }\n }\n\n // Load workflow config\n const config = loadWorkflowConfig(projectRoot);\n\n // Check for existing file and extract custom content\n let customContent: string | null = null;\n let isNew = true;\n\n if (existsSync(outputPath)) {\n isNew = false;\n const existingContent = readFileSync(outputPath, \"utf-8\");\n customContent = extractCustomContent(existingContent);\n }\n\n // Generate the content\n const content = generateInstructionsContent(config, guidelines, customContent);\n\n // Ensure .github directory exists\n if (!existsSync(githubDir)) {\n mkdirSync(githubDir, { recursive: true });\n }\n\n // Write the file\n writeFileSync(outputPath, content, \"utf-8\");\n\n return {\n success: true,\n filePath: outputPath,\n guidelinesCount: guidelines.length,\n isNew,\n preservedCustomContent: customContent !== null,\n };\n}\n\n/**\n * Check if copilot instructions need regeneration\n * (e.g., guidelines have been modified since last generation)\n */\nexport function needsRegeneration(projectRoot: string): boolean {\n const guidelinesDir = join(projectRoot, \"guidelines\");\n const outputPath = join(projectRoot, \".github\", \"copilot-instructions.md\");\n\n if (!existsSync(outputPath)) {\n return existsSync(guidelinesDir);\n }\n\n // For now, always regenerate to ensure latest content\n // Future: could compare file modification times\n return true;\n}\n","/**\n * Shared workflow scripts definition\n * Used by postinstall.ts and setup.ts to ensure consistency\n *\n * Version 2.19.0: CLI consolidation - commands now use subcommand syntax (space instead of colon)\n */\n\n/**\n * Current version of the workflow scripts schema\n * Used for tracking which version installed the scripts\n */\nexport const WORKFLOW_SCRIPTS_VERSION = \"2.19.0\";\n\n/**\n * Deprecated scripts that should be removed from package.json\n * These are old colon-style commands replaced by the new subcommand structure\n */\nexport const DEPRECATED_SCRIPTS = [\n // Old colon-style scope commands\n \"workflow:scope:create\",\n \"workflow:scope:migrate\",\n\n // Old colon-style learn commands\n \"workflow:learn\",\n \"workflow:learn:record\",\n \"workflow:learn:list\",\n \"workflow:learn:apply\",\n \"workflow:learn:publish\",\n \"workflow:learn:sync\",\n \"workflow:learn:sync:push\",\n \"workflow:learn:sync:pull\",\n \"workflow:learn:config\",\n \"workflow:learn:deprecate\",\n \"workflow:learn:stats\",\n\n // Old colon-style solution commands\n \"workflow:solution\",\n \"workflow:solution:capture\",\n \"workflow:solution:search\",\n \"workflow:solution:list\",\n \"workflow:solution:apply\",\n \"workflow:solution:deprecate\",\n \"workflow:solution:stats\",\n\n // Old advisory commands (now under docs)\n \"workflow:advisory\",\n \"workflow:advisory:quick\",\n \"workflow:advisory:standard\",\n \"workflow:advisory:comprehensive\",\n \"workflow:advisory:executive\",\n \"workflow:advisory:ci\",\n\n // Old standalone commands (now under docs)\n \"workflow:generate-instructions\",\n \"workflow:update-templates\",\n \"workflow:update-templates:force\",\n\n // Old colon-style docs commands\n \"workflow:docs:validate\",\n \"workflow:docs:validate:fix\",\n\n // Old verify shortcuts without prefix\n \"verify\",\n \"verify:fix\",\n \"pre-commit\",\n\n // Old colon-style verify\n \"workflow:verify:fix\",\n] as const;\n\nexport type DeprecatedScriptName = (typeof DEPRECATED_SCRIPTS)[number];\n\nexport const WORKFLOW_SCRIPTS = {\n // Version marker for tracking\n \"workflow:version\": `echo \"workflow-agent scripts v${WORKFLOW_SCRIPTS_VERSION}\"`,\n\n // Core Commands\n \"workflow:init\": \"workflow-agent init\",\n \"workflow:validate\": \"workflow-agent validate\",\n \"workflow:config\": \"workflow-agent config show\",\n \"workflow:config-show\": \"workflow-agent config show\",\n \"workflow:config-set\": \"workflow-agent config set\",\n \"workflow:suggest\": \"workflow-agent suggest\",\n \"workflow:setup\": \"workflow-agent setup\",\n \"workflow:doctor\": \"workflow-agent doctor\",\n\n // Scope Commands (new subcommand syntax)\n \"workflow:scope\": \"workflow-agent scope list\",\n \"workflow:scope-create\": \"workflow-agent scope create\",\n \"workflow:scope-migrate\": \"workflow-agent scope migrate\",\n \"workflow:scope-add\": \"workflow-agent scope add\",\n \"workflow:scope-remove\": \"workflow-agent scope remove\",\n \"workflow:scope-sync\": \"workflow-agent scope sync\",\n \"workflow:scope-analyze\": \"workflow-agent scope analyze\",\n\n // Verification & Auto-Setup\n \"workflow:verify\": \"workflow-agent verify\",\n \"workflow:verify-fix\": \"workflow-agent verify --fix\",\n \"workflow:pre-commit\": \"workflow-agent verify --fix\",\n \"workflow:auto-setup\": \"workflow-agent auto-setup\",\n\n // Hooks Commands (new subcommand syntax)\n \"workflow:hooks\": \"workflow-agent hooks status\",\n \"workflow:hooks-install\": \"workflow-agent hooks install\",\n \"workflow:hooks-uninstall\": \"workflow-agent hooks uninstall\",\n \"workflow:hooks-test\": \"workflow-agent hooks test\",\n\n // Learning System Commands (new subcommand syntax)\n \"workflow:learn-list\": \"workflow-agent learn list\",\n \"workflow:learn-analyze\": \"workflow-agent learn analyze\",\n \"workflow:learn-capture\": \"workflow-agent learn capture\",\n \"workflow:learn-apply\": \"workflow-agent learn apply\",\n \"workflow:learn-export\": \"workflow-agent learn export\",\n \"workflow:learn-import\": \"workflow-agent learn import\",\n \"workflow:learn-status\": \"workflow-agent learn status\",\n \"workflow:learn-stats\": \"workflow-agent learn stats\",\n \"workflow:learn-clean\": \"workflow-agent learn clean\",\n \"workflow:learn-config\": \"workflow-agent learn config --show\",\n \"workflow:learn-config-enable\": \"workflow-agent learn config --enable-sync\",\n \"workflow:learn-config-disable\": \"workflow-agent learn config --disable-sync\",\n \"workflow:learn-sync\": \"workflow-agent learn sync\",\n \"workflow:learn-sync-push\": \"workflow-agent learn sync --push\",\n \"workflow:learn-sync-pull\": \"workflow-agent learn sync --pull\",\n\n // Solution Pattern Commands (new subcommand syntax)\n \"workflow:solution-list\": \"workflow-agent solution list\",\n \"workflow:solution-create\": \"workflow-agent solution create\",\n \"workflow:solution-show\": \"workflow-agent solution show\",\n \"workflow:solution-search\": \"workflow-agent solution search\",\n \"workflow:solution-apply\": \"workflow-agent solution apply\",\n \"workflow:solution-export\": \"workflow-agent solution export\",\n \"workflow:solution-import\": \"workflow-agent solution import\",\n \"workflow:solution-analyze\": \"workflow-agent solution analyze\",\n\n // Sync Commands (new unified sync)\n \"workflow:sync\": \"workflow-agent sync status\",\n \"workflow:sync-push\": \"workflow-agent sync push\",\n \"workflow:sync-pull\": \"workflow-agent sync pull\",\n\n // Docs Commands (new subcommand syntax)\n \"workflow:docs\": \"workflow-agent docs validate\",\n \"workflow:docs-validate\": \"workflow-agent docs validate\",\n \"workflow:docs-validate-fix\": \"workflow-agent docs validate --fix\",\n \"workflow:docs-advisory\": \"workflow-agent docs advisory\",\n \"workflow:docs-advisory-quick\": \"workflow-agent docs advisory --depth quick\",\n \"workflow:docs-advisory-standard\": \"workflow-agent docs advisory --depth standard\",\n \"workflow:docs-advisory-comprehensive\": \"workflow-agent docs advisory --depth comprehensive\",\n \"workflow:docs-advisory-executive\": \"workflow-agent docs advisory --depth executive\",\n \"workflow:docs-advisory-ci\": \"workflow-agent docs advisory --ci\",\n \"workflow:docs-generate\": \"workflow-agent docs generate\",\n \"workflow:docs-update\": \"workflow-agent docs update\",\n \"workflow:docs-update-force\": \"workflow-agent docs update --force\",\n} as const;\n\nexport type WorkflowScriptName = keyof typeof WORKFLOW_SCRIPTS;\n\n/**\n * Script categories for organized console output\n */\nexport const SCRIPT_CATEGORIES = {\n \"Core Commands\": [\n \"workflow:init\",\n \"workflow:validate\",\n \"workflow:config\",\n \"workflow:config-show\",\n \"workflow:config-set\",\n \"workflow:suggest\",\n \"workflow:setup\",\n \"workflow:doctor\",\n ],\n \"Scope Commands\": [\n \"workflow:scope\",\n \"workflow:scope-create\",\n \"workflow:scope-migrate\",\n \"workflow:scope-add\",\n \"workflow:scope-remove\",\n \"workflow:scope-sync\",\n \"workflow:scope-analyze\",\n ],\n Verification: [\n \"workflow:verify\",\n \"workflow:verify-fix\",\n \"workflow:pre-commit\",\n \"workflow:auto-setup\",\n ],\n Hooks: [\n \"workflow:hooks\",\n \"workflow:hooks-install\",\n \"workflow:hooks-uninstall\",\n \"workflow:hooks-test\",\n ],\n \"Learning System\": [\n \"workflow:learn-list\",\n \"workflow:learn-analyze\",\n \"workflow:learn-capture\",\n \"workflow:learn-apply\",\n \"workflow:learn-export\",\n \"workflow:learn-import\",\n \"workflow:learn-status\",\n \"workflow:learn-stats\",\n \"workflow:learn-clean\",\n \"workflow:learn-config\",\n \"workflow:learn-config-enable\",\n \"workflow:learn-config-disable\",\n \"workflow:learn-sync\",\n \"workflow:learn-sync-push\",\n \"workflow:learn-sync-pull\",\n ],\n \"Solution Patterns\": [\n \"workflow:solution-list\",\n \"workflow:solution-create\",\n \"workflow:solution-show\",\n \"workflow:solution-search\",\n \"workflow:solution-apply\",\n \"workflow:solution-export\",\n \"workflow:solution-import\",\n \"workflow:solution-analyze\",\n ],\n Sync: [\"workflow:sync\", \"workflow:sync-push\", \"workflow:sync-pull\"],\n Documentation: [\n \"workflow:docs\",\n \"workflow:docs-validate\",\n \"workflow:docs-validate-fix\",\n \"workflow:docs-advisory\",\n \"workflow:docs-advisory-quick\",\n \"workflow:docs-advisory-standard\",\n \"workflow:docs-advisory-comprehensive\",\n \"workflow:docs-advisory-executive\",\n \"workflow:docs-advisory-ci\",\n \"workflow:docs-generate\",\n \"workflow:docs-update\",\n \"workflow:docs-update-force\",\n ],\n Meta: [\"workflow:version\"],\n} as const;\n\nexport const TOTAL_SCRIPTS = Object.keys(WORKFLOW_SCRIPTS).length;\n\n","/**\n * Silent template installer for postinstall and non-interactive contexts\n *\n * This module provides functions to copy mandatory templates without\n * user interaction, suitable for use in postinstall scripts.\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from \"fs\";\nimport { readdirSync } from \"fs\";\nimport { join, basename } from \"path\";\nimport { getMandatoryTemplateFilenames } from \"../templates/metadata.js\";\n\nexport interface InstallTemplatesOptions {\n /** Force overwrite existing files */\n force?: boolean;\n /** Skip if guidelines directory already exists */\n skipIfExists?: boolean;\n /** Silent mode - no console output */\n silent?: boolean;\n /** Only install mandatory templates (default: true) */\n mandatoryOnly?: boolean;\n}\n\nexport interface InstallTemplatesResult {\n success: boolean;\n installed: string[];\n skipped: string[];\n updated: string[];\n errors: string[];\n guidelinesExisted: boolean;\n}\n\n/**\n * Get project name from package.json or directory name\n */\nfunction getProjectName(projectRoot: string): string {\n try {\n const pkgPath = join(projectRoot, \"package.json\");\n if (existsSync(pkgPath)) {\n const pkg = JSON.parse(readFileSync(pkgPath, \"utf-8\"));\n return pkg.name || basename(projectRoot);\n }\n } catch {\n // Ignore errors, fall back to directory name\n }\n return basename(projectRoot);\n}\n\n/**\n * Simple template variable substitution using {{variable}} syntax\n */\nfunction renderTemplate(\n template: string,\n context: Record<string, string>,\n): string {\n return template.replace(/\\{\\{(\\w+)\\}\\}/g, (match, key) => {\n return context[key] ?? match;\n });\n}\n\n/**\n * Build default template context from project info\n * Uses generic defaults when no workflow.config.json exists\n */\nfunction buildDefaultContext(projectRoot: string): Record<string, string> {\n const projectName = getProjectName(projectRoot);\n\n return {\n projectName,\n framework: \"unknown\",\n scopes: \"feat, fix, docs, refactor, test, chore\",\n scopeList: `- **feat** - New features\n- **fix** - Bug fixes\n- **docs** - Documentation\n- **refactor** - Code refactoring\n- **test** - Testing\n- **chore** - Maintenance`,\n pathStructure: \"N/A\",\n enforcement: \"strict\",\n year: new Date().getFullYear().toString(),\n };\n}\n\n/**\n * Find the templates directory relative to this module\n * Works in both development and installed contexts\n */\nexport function findTemplatesDirectory(callerDirname: string): string | null {\n // When installed: dist/scripts/template-installer.js -> ../../templates\n // Try multiple possible locations\n const possiblePaths = [\n join(callerDirname, \"../../templates\"),\n join(callerDirname, \"../templates\"),\n join(callerDirname, \"templates\"),\n ];\n\n for (const templatePath of possiblePaths) {\n if (existsSync(templatePath)) {\n return templatePath;\n }\n }\n\n return null;\n}\n\n/**\n * Install mandatory templates to a project's guidelines directory\n * Designed for non-interactive use (postinstall, CI, etc.)\n */\nexport function installMandatoryTemplates(\n projectRoot: string,\n templatesDir: string,\n options: InstallTemplatesOptions = {},\n): InstallTemplatesResult {\n const {\n force = false,\n skipIfExists = true,\n silent = false,\n mandatoryOnly = true,\n } = options;\n\n const result: InstallTemplatesResult = {\n success: true,\n installed: [],\n skipped: [],\n updated: [],\n errors: [],\n guidelinesExisted: false,\n };\n\n const guidelinesDir = join(projectRoot, \"guidelines\");\n result.guidelinesExisted = existsSync(guidelinesDir);\n\n // Skip if guidelines exists and skipIfExists is true\n if (result.guidelinesExisted && skipIfExists && !force) {\n if (!silent) {\n console.log(\" Guidelines directory already exists, skipping templates\");\n }\n return result;\n }\n\n // Get list of templates to install\n const mandatoryFiles = getMandatoryTemplateFilenames();\n\n // Check templates directory exists\n if (!existsSync(templatesDir)) {\n result.success = false;\n result.errors.push(`Templates directory not found: ${templatesDir}`);\n return result;\n }\n\n // Get available template files\n let availableFiles: string[];\n try {\n availableFiles = readdirSync(templatesDir).filter((f) => f.endsWith(\".md\"));\n } catch (error) {\n result.success = false;\n result.errors.push(`Failed to read templates directory: ${error}`);\n return result;\n }\n\n // Determine which files to install\n const filesToInstall = mandatoryOnly\n ? availableFiles.filter((f) => mandatoryFiles.includes(f))\n : availableFiles;\n\n if (filesToInstall.length === 0) {\n result.success = false;\n result.errors.push(\"No template files found to install\");\n return result;\n }\n\n // Build template context\n const context = buildDefaultContext(projectRoot);\n\n // Create guidelines directory\n try {\n mkdirSync(guidelinesDir, { recursive: true });\n } catch (error) {\n result.success = false;\n result.errors.push(`Failed to create guidelines directory: ${error}`);\n return result;\n }\n\n // Copy each template\n for (const filename of filesToInstall) {\n const sourcePath = join(templatesDir, filename);\n const destPath = join(guidelinesDir, filename);\n\n const fileExists = existsSync(destPath);\n\n // Skip if file exists and not forcing\n if (fileExists && !force) {\n result.skipped.push(filename);\n continue;\n }\n\n try {\n const template = readFileSync(sourcePath, \"utf-8\");\n const rendered = renderTemplate(template, context);\n writeFileSync(destPath, rendered, \"utf-8\");\n\n if (fileExists) {\n result.updated.push(filename);\n } else {\n result.installed.push(filename);\n }\n } catch (error) {\n result.errors.push(`Failed to install ${filename}: ${error}`);\n }\n }\n\n // Log results if not silent\n if (!silent) {\n if (result.installed.length > 0) {\n console.log(\n `\\n✓ Installed ${result.installed.length} guideline templates:`,\n );\n for (const file of result.installed) {\n console.log(` - ${file}`);\n }\n }\n if (result.updated.length > 0) {\n console.log(`\\n✓ Updated ${result.updated.length} guideline templates:`);\n for (const file of result.updated) {\n console.log(` - ${file}`);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Update templates - reinstall templates with option to force or skip existing\n */\nexport function updateTemplates(\n projectRoot: string,\n templatesDir: string,\n options: { force?: boolean; silent?: boolean } = {},\n): InstallTemplatesResult {\n return installMandatoryTemplates(projectRoot, templatesDir, {\n ...options,\n skipIfExists: false, // Don't skip - we want to update\n mandatoryOnly: false, // Install all templates during update\n });\n}\n","/**\n * Template metadata defining mandatory vs optional guidelines\n * and their associated validators for enforcement\n *\n * @fileoverview This module defines which guidelines are mandatory for projects\n * using the workflow agent. Mandatory guidelines MUST be present and cannot be\n * skipped during project initialization.\n *\n * TODO: Ensure all new templates have associated unit tests in metadata.test.ts\n */\n\nexport type TemplateCategory = \"workflow\" | \"documentation\" | \"development\";\n\nexport type ValidatorType =\n | \"branch-name\"\n | \"commit-message\"\n | \"pr-title\"\n | \"implementation-plan\"\n | \"test-coverage\"\n | \"file-exists\";\n\nexport interface TemplateMetadata {\n /** Template filename */\n filename: string;\n /** Human-readable name */\n displayName: string;\n /** Whether this template is mandatory (cannot be skipped during init) */\n mandatory: boolean;\n /** Category for grouping */\n category: TemplateCategory;\n /** Associated validators that enforce this template's rules */\n validators: ValidatorType[];\n /** Brief description of what this template covers */\n description: string;\n}\n\n/**\n * Metadata for all available templates\n * Templates marked as mandatory will be auto-generated during init\n * and checked by the doctor command\n */\nexport const templateMetadata: Record<string, TemplateMetadata> = {\n \"AGENT_EDITING_INSTRUCTIONS.md\": {\n filename: \"AGENT_EDITING_INSTRUCTIONS.md\",\n displayName: \"Agent Editing Instructions\",\n mandatory: true,\n category: \"workflow\",\n validators: [\"implementation-plan\"],\n description:\n \"Core rules for AI agents: implementation plans, coding standards, architecture\",\n },\n \"BRANCHING_STRATEGY.md\": {\n filename: \"BRANCHING_STRATEGY.md\",\n displayName: \"Branching Strategy\",\n mandatory: true,\n category: \"workflow\",\n validators: [\"branch-name\", \"pr-title\"],\n description:\n \"Git branch naming conventions, PR requirements, merge policies\",\n },\n \"TESTING_STRATEGY.md\": {\n filename: \"TESTING_STRATEGY.md\",\n displayName: \"Testing Strategy\",\n mandatory: true,\n category: \"development\",\n validators: [\"test-coverage\"],\n description:\n \"Testing pyramid, Vitest/Playwright patterns, when tests are required\",\n },\n \"SELF_IMPROVEMENT_MANDATE.md\": {\n filename: \"SELF_IMPROVEMENT_MANDATE.md\",\n displayName: \"Self-Improvement Mandate\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description: \"Continuous improvement tracking, changelog requirements\",\n },\n \"PATTERN_ANALYSIS_WORKFLOW.md\": {\n filename: \"PATTERN_ANALYSIS_WORKFLOW.md\",\n displayName: \"Pattern Analysis Workflow\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description:\n \"AI agent workflow for analyzing codebases, extracting patterns, and updating the central pattern store\",\n },\n \"SINGLE_SOURCE_OF_TRUTH.md\": {\n filename: \"SINGLE_SOURCE_OF_TRUTH.md\",\n displayName: \"Single Source of Truth\",\n mandatory: true,\n category: \"workflow\",\n validators: [],\n description:\n \"Canonical code locations, service patterns, avoiding duplication\",\n },\n \"COMPONENT_LIBRARY.md\": {\n filename: \"COMPONENT_LIBRARY.md\",\n displayName: \"Component Library\",\n mandatory: false,\n category: \"development\",\n validators: [],\n description: \"UI component patterns, design tokens, decision tree\",\n },\n \"DEPLOYMENT_STRATEGY.md\": {\n filename: \"DEPLOYMENT_STRATEGY.md\",\n displayName: \"Deployment Strategy\",\n mandatory: false,\n category: \"development\",\n validators: [],\n description: \"Deployment workflow, environments, migrations, rollback\",\n },\n \"LIBRARY_INVENTORY.md\": {\n filename: \"LIBRARY_INVENTORY.md\",\n displayName: \"Library Inventory\",\n mandatory: true,\n category: \"development\",\n validators: [],\n description: \"Dependency catalog, approved libraries, new library process\",\n },\n \"SCOPE_CREATION_WORKFLOW.md\": {\n filename: \"SCOPE_CREATION_WORKFLOW.md\",\n displayName: \"Scope Creation Workflow\",\n mandatory: false,\n category: \"workflow\",\n validators: [],\n description: \"Workflow for AI agents creating custom scopes\",\n },\n \"CUSTOM_SCOPE_TEMPLATE.md\": {\n filename: \"CUSTOM_SCOPE_TEMPLATE.md\",\n displayName: \"Custom Scope Template\",\n mandatory: false,\n category: \"workflow\",\n validators: [],\n description: \"Template for defining custom scope packages\",\n },\n \"PROJECT_TEMPLATE_README.md\": {\n filename: \"PROJECT_TEMPLATE_README.md\",\n displayName: \"Project Template README\",\n mandatory: false,\n category: \"documentation\",\n validators: [],\n description: \"Meta-document describing project structure\",\n },\n \"Guidelines.md\": {\n filename: \"Guidelines.md\",\n displayName: \"Custom Guidelines\",\n mandatory: false,\n category: \"documentation\",\n validators: [],\n description: \"Placeholder for custom user guidelines\",\n },\n};\n\n/**\n * Get all mandatory templates\n */\nexport function getMandatoryTemplates(): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => t.mandatory);\n}\n\n/**\n * Get all optional templates\n */\nexport function getOptionalTemplates(): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => !t.mandatory);\n}\n\n/**\n * Get templates by category\n */\nexport function getTemplatesByCategory(\n category: TemplateCategory,\n): TemplateMetadata[] {\n return Object.values(templateMetadata).filter((t) => t.category === category);\n}\n\n/**\n * Get template metadata by filename\n */\nexport function getTemplateMetadata(\n filename: string,\n): TemplateMetadata | undefined {\n return templateMetadata[filename];\n}\n\n/**\n * Check if a template is mandatory\n */\nexport function isTemplateMandatory(filename: string): boolean {\n return templateMetadata[filename]?.mandatory ?? false;\n}\n\n/**\n * Get mandatory template filenames\n */\nexport function getMandatoryTemplateFilenames(): string[] {\n return getMandatoryTemplates().map((t) => t.filename);\n}\n"],"mappings":";AAeA,SAAS,cAAc,eAAe,YAAY,aAAa,iBAAiB;AAChF,SAAS,MAAM,gBAAgB;AAG/B,IAAM,sBAAsB;AAC5B,IAAM,oBAAoB;AAC1B,IAAM,mBAAmB;AAmBzB,SAAS,aAAa,SAAyB;AAC7C,QAAM,QAAQ,QAAQ,MAAM,aAAa;AACzC,SAAO,QAAQ,MAAM,CAAC,EAAE,KAAK,IAAI;AACnC;AAKA,SAAS,mBAAmB,SAAyB;AAEnD,QAAM,QAAQ,QAAQ,MAAM,IAAI;AAChC,MAAI,aAAa;AACjB,MAAI,cAAc;AAElB,aAAW,QAAQ,OAAO;AACxB,QAAI,KAAK,WAAW,IAAI,GAAG;AACzB,mBAAa;AACb;AAAA,IACF;AACA,QAAI,YAAY;AAEd,UAAI,KAAK,KAAK,MAAM,MAAM,KAAK,WAAW,GAAG,GAAG;AAC9C,YAAI,YAAa;AACjB;AAAA,MACF;AAEA,UAAI,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,KAAK,KAAK,KAAK,WAAW,IAAI,GAAG;AAC3E;AAAA,MACF;AACA,qBAAe,KAAK,KAAK,IAAI;AAE7B,UAAI,YAAY,SAAS,IAAK;AAAA,IAChC;AAAA,EACF;A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AY;AACd,eAAO,QAAQ,KAAK,QAAQ;AAAA,MAC9B,OAAO;AACL,eAAO,UAAU,KAAK,QAAQ;AAAA,MAChC;AAAA,IACF,SAAS,OAAO;AACd,aAAO,OAAO,KAAK,qBAAqB,QAAQ,KAAK,KAAK,EAAE;AAAA,IAC9D;AAAA,EACF;AAGA,MAAI,CAAC,QAAQ;AACX,QAAI,OAAO,UAAU,SAAS,GAAG;AAC/B,cAAQ;AAAA,QACN;AAAA,mBAAiB,OAAO,UAAU,MAAM;AAAA,MAC1C;AACA,iBAAW,QAAQ,OAAO,WAAW;AACnC,gBAAQ,IAAI,SAAS,IAAI,EAAE;AAAA,MAC7B;AAAA,IACF;AACA,QAAI,OAAO,QAAQ,SAAS,GAAG;AAC7B,cAAQ,IAAI;AAAA,iBAAe,OAAO,QAAQ,MAAM,uBAAuB;AACvE,iBAAW,QAAQ,OAAO,SAAS;AACjC,gBAAQ,IAAI,SAAS,IAAI,EAAE;AAAA,MAC7B;AAAA,IACF;AAAA,EACF;AAEA,SAAO;AACT;AAKO,SAAS,gBACd,aACA,cACA,UAAiD,CAAC,GAC1B;AACxB,SAAO,0BAA0B,aAAa,cAAc;AAAA,IAC1D,GAAG;AAAA,IACH,cAAc;AAAA;AAAA,IACd,eAAe;AAAA;AAAA,EACjB,CAAC;AACH;","names":["existsSync","readFileSync","writeFileSync","mkdirSync","readdirSync","join","basename","join","existsSync","readFileSync","basename","readdirSync","mkdirSync","writeFileSync"]}
|