iosm-cli 0.2.3 → 0.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/README.md +43 -10
  3. package/dist/cli/args.d.ts +1 -1
  4. package/dist/cli/args.d.ts.map +1 -1
  5. package/dist/cli/args.js +1 -1
  6. package/dist/cli/args.js.map +1 -1
  7. package/dist/core/agent-profiles.d.ts +2 -1
  8. package/dist/core/agent-profiles.d.ts.map +1 -1
  9. package/dist/core/agent-profiles.js +18 -5
  10. package/dist/core/agent-profiles.js.map +1 -1
  11. package/dist/core/agent-session.d.ts +7 -0
  12. package/dist/core/agent-session.d.ts.map +1 -1
  13. package/dist/core/agent-session.js +64 -15
  14. package/dist/core/agent-session.js.map +1 -1
  15. package/dist/core/agent-teams.d.ts.map +1 -1
  16. package/dist/core/agent-teams.js +90 -19
  17. package/dist/core/agent-teams.js.map +1 -1
  18. package/dist/core/extensions/types.d.ts +1 -1
  19. package/dist/core/extensions/types.d.ts.map +1 -1
  20. package/dist/core/extensions/types.js.map +1 -1
  21. package/dist/core/footer-data-provider.d.ts +6 -1
  22. package/dist/core/footer-data-provider.d.ts.map +1 -1
  23. package/dist/core/footer-data-provider.js +9 -0
  24. package/dist/core/footer-data-provider.js.map +1 -1
  25. package/dist/core/orchestration-limits.d.ts +6 -0
  26. package/dist/core/orchestration-limits.d.ts.map +1 -0
  27. package/dist/core/orchestration-limits.js +6 -0
  28. package/dist/core/orchestration-limits.js.map +1 -0
  29. package/dist/core/parallel-task-agent.d.ts +23 -1
  30. package/dist/core/parallel-task-agent.d.ts.map +1 -1
  31. package/dist/core/parallel-task-agent.js +110 -20
  32. package/dist/core/parallel-task-agent.js.map +1 -1
  33. package/dist/core/sdk.d.ts +6 -1
  34. package/dist/core/sdk.d.ts.map +1 -1
  35. package/dist/core/sdk.js +34 -6
  36. package/dist/core/sdk.js.map +1 -1
  37. package/dist/core/shared-memory.d.ts +2 -2
  38. package/dist/core/shared-memory.d.ts.map +1 -1
  39. package/dist/core/shared-memory.js +220 -91
  40. package/dist/core/shared-memory.js.map +1 -1
  41. package/dist/core/singular.d.ts.map +1 -1
  42. package/dist/core/singular.js +3 -1
  43. package/dist/core/singular.js.map +1 -1
  44. package/dist/core/subagents.d.ts +1 -1
  45. package/dist/core/subagents.d.ts.map +1 -1
  46. package/dist/core/subagents.js +32 -10
  47. package/dist/core/subagents.js.map +1 -1
  48. package/dist/core/swarm/planner.d.ts.map +1 -1
  49. package/dist/core/swarm/planner.js +200 -12
  50. package/dist/core/swarm/planner.js.map +1 -1
  51. package/dist/core/swarm/scheduler.d.ts +2 -0
  52. package/dist/core/swarm/scheduler.d.ts.map +1 -1
  53. package/dist/core/swarm/scheduler.js +87 -6
  54. package/dist/core/swarm/scheduler.js.map +1 -1
  55. package/dist/core/system-prompt.d.ts.map +1 -1
  56. package/dist/core/system-prompt.js +1 -0
  57. package/dist/core/system-prompt.js.map +1 -1
  58. package/dist/core/tools/ast-grep.d.ts.map +1 -1
  59. package/dist/core/tools/ast-grep.js +2 -0
  60. package/dist/core/tools/ast-grep.js.map +1 -1
  61. package/dist/core/tools/edit.d.ts +8 -4
  62. package/dist/core/tools/edit.d.ts.map +1 -1
  63. package/dist/core/tools/edit.js +18 -3
  64. package/dist/core/tools/edit.js.map +1 -1
  65. package/dist/core/tools/index.d.ts +9 -7
  66. package/dist/core/tools/index.d.ts.map +1 -1
  67. package/dist/core/tools/shared-memory.d.ts.map +1 -1
  68. package/dist/core/tools/shared-memory.js +34 -6
  69. package/dist/core/tools/shared-memory.js.map +1 -1
  70. package/dist/core/tools/task.d.ts +10 -3
  71. package/dist/core/tools/task.d.ts.map +1 -1
  72. package/dist/core/tools/task.js +830 -184
  73. package/dist/core/tools/task.js.map +1 -1
  74. package/dist/core/tools/todo.d.ts +10 -10
  75. package/dist/core/tools/todo.d.ts.map +1 -1
  76. package/dist/core/tools/todo.js +135 -17
  77. package/dist/core/tools/todo.js.map +1 -1
  78. package/dist/core/tools/yq.d.ts.map +1 -1
  79. package/dist/core/tools/yq.js +2 -0
  80. package/dist/core/tools/yq.js.map +1 -1
  81. package/dist/modes/interactive/components/footer.d.ts +1 -1
  82. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  83. package/dist/modes/interactive/components/footer.js +10 -9
  84. package/dist/modes/interactive/components/footer.js.map +1 -1
  85. package/dist/modes/interactive/interactive-mode.d.ts +22 -0
  86. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  87. package/dist/modes/interactive/interactive-mode.js +957 -75
  88. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  89. package/docs/cli-reference.md +8 -0
  90. package/docs/configuration.md +5 -1
  91. package/docs/interactive-mode.md +7 -1
  92. package/docs/orchestration-and-subagents.md +5 -0
  93. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"singular.js","sourceRoot":"","sources":["../../src/core/singular.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpG,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAkE1D,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACpC,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,OAAO;IACP,OAAO;IACP,OAAO;IACP,MAAM;IACN,OAAO;IACP,KAAK;IACL,KAAK;IACL,MAAM;IACN,OAAO;IACP,MAAM;CACN,CAAC,CAAC;AAEH,MAAM,kBAAkB,GAAG,IAAI,GAAG,CAAC,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,UAAU,CAAC,CAAC,CAAC;AAE5G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AAsB;gBAC7B,OAAO,EAAE,sEAAsE;gBAC/E,UAAU,EAAE,KAAK;gBACjB,YAAY,EAAE,KAAK;gBACnB,eAAe,EAAE,EAAE;gBACnB,IAAI,EAAE;oBACL,iDAAiD;oBACjD,qDAAqD;oBACrD,uDAAuD;iBACvD;gBACD,IAAI,EAAE,CAAC,wBAAwB,EAAE,0BAA0B,CAAC;gBAC5D,IAAI,EAAE,CAAC,oDAAoD,CAAC;gBAC5D,cAAc,EAAE,uEAAuE;aACvF;SACD,CAAC;IACH,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { basename, join, relative, sep } from \"node:path\";\nimport type { EngineeringContract } from \"./contract.js\";\n\nexport type SingularComplexity = \"low\" | \"medium\" | \"high\";\nexport type SingularBlastRadius = \"low\" | \"medium\" | \"high\";\nexport type SingularRecommendation = \"implement_now\" | \"implement_incrementally\" | \"defer\";\nexport type SingularStageFit = \"needed_now\" | \"optional_now\" | \"later\";\n\nexport interface SingularImpactAnalysis {\n\tcodebase: string;\n\tdelivery: string;\n\trisks: string;\n\toperations: string;\n}\n\nexport interface SingularOption {\n\tid: string;\n\ttitle: string;\n\tsummary: string;\n\tcomplexity: SingularComplexity;\n\tblast_radius: SingularBlastRadius;\n\tsuggested_files: string[];\n\tplan: string[];\n\tpros: string[];\n\tcons: string[];\n\twhen_to_choose?: string;\n}\n\nexport interface SingularAnalysisResult {\n\trunId: string;\n\trequest: string;\n\tgeneratedAt: string;\n\tscannedFiles: number;\n\tsourceFiles: number;\n\ttestFiles: number;\n\tmatchedFiles: string[];\n\tbaselineComplexity: SingularComplexity;\n\tbaselineBlastRadius: SingularBlastRadius;\n\trecommendation: SingularRecommendation;\n\trecommendationReason: string;\n\tstageFit?: SingularStageFit;\n\tstageFitReason?: string;\n\timpactAnalysis?: SingularImpactAnalysis;\n\tcontractSignals: string[];\n\toptions: SingularOption[];\n}\n\nexport interface SingularLastRun {\n\trunId: string;\n\tanalysisPath: string;\n\tmetaPath?: string;\n\trequest?: string;\n\trecommendation?: SingularRecommendation;\n\tgeneratedAt?: string;\n}\n\nexport interface SingularAnalyzeOptions {\n\trequest: string;\n\tcontract?: EngineeringContract;\n\tautosave?: boolean;\n}\n\nexport interface SingularServiceOptions {\n\tcwd: string;\n}\n\nconst SCAN_TEXT_EXTENSIONS = new Set([\n\t\".ts\",\n\t\".tsx\",\n\t\".js\",\n\t\".jsx\",\n\t\".mjs\",\n\t\".cjs\",\n\t\".py\",\n\t\".go\",\n\t\".rs\",\n\t\".java\",\n\t\".json\",\n\t\".yaml\",\n\t\".yml\",\n\t\".toml\",\n\t\".md\",\n\t\".sh\",\n\t\".sql\",\n\t\".html\",\n\t\".css\",\n]);\n\nconst EXCLUDED_DIR_NAMES = new Set([\".git\", \"node_modules\", \"dist\", \"build\", \".iosm\", \".next\", \"coverage\"]);\n\nconst STOP_WORDS = new Set([\n\t\"a\",\n\t\"an\",\n\t\"the\",\n\t\"and\",\n\t\"or\",\n\t\"for\",\n\t\"with\",\n\t\"from\",\n\t\"into\",\n\t\"about\",\n\t\"что\",\n\t\"как\",\n\t\"для\",\n\t\"это\",\n\t\"надо\",\n\t\"нужно\",\n\t\"добавить\",\n\t\"сделать\",\n\t\"функционал\",\n\t\"feature\",\n\t\"implement\",\n\t\"add\",\n]);\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(sep).join(\"/\");\n}\n\nfunction getExtension(filePath: string): string {\n\tconst normalized = filePath.toLowerCase();\n\tconst index = normalized.lastIndexOf(\".\");\n\treturn index >= 0 ? normalized.slice(index) : \"\";\n}\n\nfunction nowIso(): string {\n\treturn new Date().toISOString();\n}\n\nfunction buildRunId(date = new Date()): string {\n\tconst year = date.getUTCFullYear();\n\tconst month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n\tconst day = String(date.getUTCDate()).padStart(2, \"0\");\n\tconst hours = String(date.getUTCHours()).padStart(2, \"0\");\n\tconst minutes = String(date.getUTCMinutes()).padStart(2, \"0\");\n\tconst seconds = String(date.getUTCSeconds()).padStart(2, \"0\");\n\treturn `${year}-${month}-${day}-${hours}${minutes}${seconds}`;\n}\n\nfunction normalizeRequestTokens(request: string): string[] {\n\treturn request\n\t\t.toLowerCase()\n\t\t.split(/[^\\p{L}\\p{N}]+/u)\n\t\t.map((token) => token.trim())\n\t\t.filter((token) => token.length >= 3 && !STOP_WORDS.has(token));\n}\n\nfunction scoreToComplexity(score: number): SingularComplexity {\n\tif (score >= 4) return \"high\";\n\tif (score >= 2) return \"medium\";\n\treturn \"low\";\n}\n\nfunction scoreToBlastRadius(score: number): SingularBlastRadius {\n\tif (score >= 4) return \"high\";\n\tif (score >= 2) return \"medium\";\n\treturn \"low\";\n}\n\nfunction defaultSuggestedFiles(matches: string[]): string[] {\n\tif (matches.length > 0) return matches.slice(0, 6);\n\treturn [\"src/**/*\", \"test/**/*\"];\n}\n\nexport class SingularService {\n\tprivate readonly cwd: string;\n\n\tconstructor(options: SingularServiceOptions) {\n\t\tthis.cwd = options.cwd;\n\t}\n\n\tgetAnalysesRoot(): string {\n\t\treturn join(this.cwd, \".iosm\", \"singular\");\n\t}\n\n\tgetLastRun(): SingularLastRun | undefined {\n\t\tconst root = this.getAnalysesRoot();\n\t\tif (!existsSync(root)) return undefined;\n\t\tconst candidates = readdirSync(root, { withFileTypes: true })\n\t\t\t.filter((entry) => entry.isDirectory())\n\t\t\t.map((entry) => entry.name)\n\t\t\t.sort((a, b) => a.localeCompare(b));\n\t\tconst runId = candidates[candidates.length - 1];\n\t\tif (!runId) return undefined;\n\n\t\tconst runDir = join(root, runId);\n\t\tconst analysisPath = join(runDir, \"analysis.json\");\n\t\tif (!existsSync(analysisPath)) return undefined;\n\t\tconst metaPath = join(runDir, \"meta.json\");\n\n\t\tlet request: string | undefined;\n\t\tlet recommendation: SingularRecommendation | undefined;\n\t\tlet generatedAt: string | undefined;\n\t\tif (existsSync(metaPath)) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(readFileSync(metaPath, \"utf8\")) as Record<string, unknown>;\n\t\t\t\trequest = typeof parsed.request === \"string\" ? parsed.request : undefined;\n\t\t\t\trecommendation =\n\t\t\t\t\tparsed.recommendation === \"implement_now\" ||\n\t\t\t\t\tparsed.recommendation === \"implement_incrementally\" ||\n\t\t\t\t\tparsed.recommendation === \"defer\"\n\t\t\t\t\t\t? (parsed.recommendation as SingularRecommendation)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tgeneratedAt = typeof parsed.generatedAt === \"string\" ? parsed.generatedAt : undefined;\n\t\t\t} catch {\n\t\t\t\t// metadata is optional\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\trunId,\n\t\t\tanalysisPath,\n\t\t\tmetaPath: existsSync(metaPath) ? metaPath : undefined,\n\t\t\trequest,\n\t\t\trecommendation,\n\t\t\tgeneratedAt,\n\t\t};\n\t}\n\n\tasync analyze(options: SingularAnalyzeOptions): Promise<SingularAnalysisResult> {\n\t\tconst request = options.request.trim();\n\t\tconst contract = options.contract ?? {};\n\t\tconst autosave = options.autosave !== false;\n\t\tconst runId = buildRunId();\n\t\tconst generatedAt = nowIso();\n\n\t\tconst scan = this.scanRepository(request);\n\t\tconst contractSignals = this.collectContractSignals(contract);\n\t\tconst baselineScore = this.estimateComplexityScore(request, scan.matchedFiles.length, scan.testFiles, contractSignals.length);\n\t\tconst baselineComplexity = scoreToComplexity(baselineScore);\n\t\tconst baselineBlastRadius = scoreToBlastRadius(baselineScore + (scan.matchedFiles.length >= 5 ? 1 : 0));\n\n\t\tconst recommendation = this.buildRecommendation({\n\t\t\trequest,\n\t\t\tbaselineComplexity,\n\t\t\ttestFiles: scan.testFiles,\n\t\t\tmatchedFiles: scan.matchedFiles.length,\n\t\t});\n\n\t\tconst suggestedFiles = defaultSuggestedFiles(scan.matchedFiles);\n\t\tconst optionsList = this.buildOptions({\n\t\t\trequest,\n\t\t\tbaselineComplexity,\n\t\t\tbaselineBlastRadius,\n\t\t\tsuggestedFiles,\n\t\t\tcontractSignals,\n\t\t});\n\n\t\tconst result: SingularAnalysisResult = {\n\t\t\trunId,\n\t\t\trequest,\n\t\t\tgeneratedAt,\n\t\t\tscannedFiles: scan.scannedFiles,\n\t\t\tsourceFiles: scan.sourceFiles,\n\t\t\ttestFiles: scan.testFiles,\n\t\t\tmatchedFiles: scan.matchedFiles,\n\t\t\tbaselineComplexity,\n\t\t\tbaselineBlastRadius,\n\t\t\trecommendation: recommendation.value,\n\t\t\trecommendationReason: recommendation.reason,\n\t\t\tcontractSignals,\n\t\t\toptions: optionsList,\n\t\t};\n\n\t\tif (autosave) {\n\t\t\tthis.saveRunArtifacts(result);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tsaveAnalysis(result: SingularAnalysisResult): void {\n\t\tthis.saveRunArtifacts(result);\n\t}\n\n\tprivate saveRunArtifacts(result: SingularAnalysisResult): void {\n\t\tconst runDir = join(this.getAnalysesRoot(), result.runId);\n\t\tmkdirSync(runDir, { recursive: true });\n\n\t\tconst analysisPath = join(runDir, \"analysis.json\");\n\t\tconst metaPath = join(runDir, \"meta.json\");\n\n\t\twriteFileSync(analysisPath, `${JSON.stringify(result, null, 2)}\\n`, \"utf8\");\n\t\twriteFileSync(\n\t\t\tmetaPath,\n\t\t\t`${JSON.stringify(\n\t\t\t\t{\n\t\t\t\t\trunId: result.runId,\n\t\t\t\t\tgeneratedAt: result.generatedAt,\n\t\t\t\t\trequest: result.request,\n\t\t\t\t\trecommendation: result.recommendation,\n\t\t\t\t\tstageFit: result.stageFit,\n\t\t\t\t\tbaselineComplexity: result.baselineComplexity,\n\t\t\t\t\tbaselineBlastRadius: result.baselineBlastRadius,\n\t\t\t\t},\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t)}\\n`,\n\t\t\t\"utf8\",\n\t\t);\n\t}\n\n\tprivate scanRepository(request: string): {\n\t\tscannedFiles: number;\n\t\tsourceFiles: number;\n\t\ttestFiles: number;\n\t\tmatchedFiles: string[];\n\t} {\n\t\tconst files = this.walkFiles();\n\t\tconst tokens = normalizeRequestTokens(request);\n\t\tconst scored = files\n\t\t\t.map((absolutePath) => {\n\t\t\t\tconst relativePath = toPosixPath(relative(this.cwd, absolutePath));\n\t\t\t\tconst normalizedPath = relativePath.toLowerCase();\n\t\t\t\tconst fileName = basename(relativePath).toLowerCase();\n\n\t\t\t\tlet score = 0;\n\t\t\t\tfor (const token of tokens) {\n\t\t\t\t\tif (normalizedPath.includes(token)) score += 1;\n\t\t\t\t\tif (fileName.includes(token)) score += 2;\n\t\t\t\t}\n\n\t\t\t\tif (/auth|account|profile|cabinet|dashboard|billing|payment/i.test(request) && /auth|user|account|profile|billing|payment|dashboard/i.test(normalizedPath)) {\n\t\t\t\t\tscore += 1;\n\t\t\t\t}\n\n\t\t\t\treturn { relativePath, score };\n\t\t\t})\n\t\t\t.filter((item) => item.score > 0)\n\t\t\t.sort((a, b) => b.score - a.score || a.relativePath.localeCompare(b.relativePath));\n\n\t\tconst matchedFiles = scored.slice(0, 10).map((item) => item.relativePath);\n\t\tconst sourceFiles = files.filter((absolutePath) => {\n\t\t\tconst rel = toPosixPath(relative(this.cwd, absolutePath));\n\t\t\treturn rel.startsWith(\"src/\") || rel.startsWith(\"app/\") || rel.startsWith(\"packages/\");\n\t\t}).length;\n\t\tconst testFiles = files.filter((absolutePath) => {\n\t\t\tconst rel = toPosixPath(relative(this.cwd, absolutePath)).toLowerCase();\n\t\t\treturn /(^|\\/)(test|tests|__tests__)\\//.test(rel) || /\\.test\\./.test(rel) || /\\.spec\\./.test(rel);\n\t\t}).length;\n\n\t\treturn {\n\t\t\tscannedFiles: files.length,\n\t\t\tsourceFiles,\n\t\t\ttestFiles,\n\t\t\tmatchedFiles,\n\t\t};\n\t}\n\n\tprivate walkFiles(): string[] {\n\t\tconst maxFiles = 12_000;\n\t\tconst stack = [this.cwd];\n\t\tconst files: string[] = [];\n\n\t\twhile (stack.length > 0 && files.length < maxFiles) {\n\t\t\tconst dir = stack.pop();\n\t\t\tif (!dir) break;\n\n\t\t\tlet entries;\n\t\t\ttry {\n\t\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst absolutePath = join(dir, entry.name);\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tif (EXCLUDED_DIR_NAMES.has(entry.name)) continue;\n\t\t\t\t\tstack.push(absolutePath);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!entry.isFile()) continue;\n\t\t\t\tif (!SCAN_TEXT_EXTENSIONS.has(getExtension(entry.name))) continue;\n\t\t\t\ttry {\n\t\t\t\t\tif (statSync(absolutePath).size > 800_000) continue;\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfiles.push(absolutePath);\n\t\t\t\tif (files.length >= maxFiles) break;\n\t\t\t}\n\t\t}\n\n\t\treturn files.sort((a, b) => a.localeCompare(b));\n\t}\n\n\tprivate collectContractSignals(contract: EngineeringContract): string[] {\n\t\tconst signals: string[] = [];\n\t\tif (contract.goal) signals.push(`goal=${contract.goal}`);\n\t\tif ((contract.constraints ?? []).length > 0) signals.push(`constraints=${contract.constraints?.length ?? 0}`);\n\t\tif ((contract.quality_gates ?? []).length > 0) signals.push(`quality_gates=${contract.quality_gates?.length ?? 0}`);\n\t\tif ((contract.definition_of_done ?? []).length > 0) {\n\t\t\tsignals.push(`definition_of_done=${contract.definition_of_done?.length ?? 0}`);\n\t\t}\n\t\tif ((contract.non_goals ?? []).length > 0) signals.push(`non_goals=${contract.non_goals?.length ?? 0}`);\n\t\tif ((contract.risks ?? []).length > 0) signals.push(`risks=${contract.risks?.length ?? 0}`);\n\t\treturn signals.slice(0, 8);\n\t}\n\n\tprivate estimateComplexityScore(\n\t\trequest: string,\n\t\tmatchedFiles: number,\n\t\ttestFiles: number,\n\t\tcontractSignalCount: number,\n\t): number {\n\t\tlet score = 1;\n\t\tconst normalized = request.toLowerCase();\n\n\t\tif (request.length > 70) score += 1;\n\t\tif (matchedFiles >= 5) score += 1;\n\t\tif (matchedFiles >= 8) score += 1;\n\t\tif (testFiles === 0) score += 1;\n\t\tif (contractSignalCount >= 3) score += 1;\n\n\t\tif (\n\t\t\t/(migration|refactor|rewrite|billing|payment|security|permission|rbac|role|distributed|event|queue|microservice|oauth|sso|регресс|миграц|рефактор|безопасност|права|роли)/.test(\n\t\t\t\tnormalized,\n\t\t\t)\n\t\t) {\n\t\t\tscore += 1;\n\t\t}\n\n\t\tif (/(asap|urgent|критично|срочно|немедленно)/.test(normalized)) {\n\t\t\tscore += 1;\n\t\t}\n\n\t\treturn Math.min(6, score);\n\t}\n\n\tprivate buildRecommendation(payload: {\n\t\trequest: string;\n\t\tbaselineComplexity: SingularComplexity;\n\t\ttestFiles: number;\n\t\tmatchedFiles: number;\n\t}): { value: SingularRecommendation; reason: string } {\n\t\tconst normalized = payload.request.toLowerCase();\n\t\tconst urgent = /(asap|urgent|критично|срочно|немедленно)/.test(normalized);\n\n\t\tif (payload.baselineComplexity === \"high\" && payload.testFiles === 0) {\n\t\t\treturn {\n\t\t\t\tvalue: \"defer\",\n\t\t\t\treason: \"High complexity with no tests in place. Build a safety net and design first.\",\n\t\t\t};\n\t\t}\n\t\tif (payload.baselineComplexity === \"high\" || payload.matchedFiles >= 7) {\n\t\t\treturn {\n\t\t\t\tvalue: \"implement_incrementally\",\n\t\t\t\treason: \"The change touches multiple areas. Prefer incremental rollout via an MVP slice.\",\n\t\t\t};\n\t\t}\n\t\tif (urgent) {\n\t\t\treturn {\n\t\t\t\tvalue: \"implement_now\",\n\t\t\t\treason: \"The request is urgent and risk appears manageable. Implement now with a constrained scope.\",\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tvalue: \"implement_now\",\n\t\t\treason: \"Complexity is manageable. Implement now while enforcing quality gates.\",\n\t\t};\n\t}\n\n\tprivate buildOptions(payload: {\n\t\trequest: string;\n\t\tbaselineComplexity: SingularComplexity;\n\t\tbaselineBlastRadius: SingularBlastRadius;\n\t\tsuggestedFiles: string[];\n\t\tcontractSignals: string[];\n\t}): SingularOption[] {\n\t\tconst compactFiles = payload.suggestedFiles.slice(0, 6);\n\t\tconst broadFiles = payload.suggestedFiles.length > 0 ? payload.suggestedFiles : [\"src/**/*\", \"test/**/*\"];\n\t\tconst contractGateStep =\n\t\t\tpayload.contractSignals.length > 0\n\t\t\t\t? \"Validate contract constraints and quality gates before merge.\"\n\t\t\t\t: \"Define explicit quality gates and Definition of Done before rollout.\";\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: \"1\",\n\t\t\t\ttitle: \"Incremental MVP\",\n\t\t\t\tsummary: \"Deliver a minimal usable feature slice quickly with measurable outcomes.\",\n\t\t\t\tcomplexity: payload.baselineComplexity === \"high\" ? \"medium\" : payload.baselineComplexity,\n\t\t\t\tblast_radius: payload.baselineBlastRadius === \"high\" ? \"medium\" : payload.baselineBlastRadius,\n\t\t\t\tsuggested_files: compactFiles,\n\t\t\t\tplan: [\n\t\t\t\t\t\"Lock the minimum scope and explicitly exclude non-goals.\",\n\t\t\t\t\t\"Implement in 1-2 target areas without cascading refactors.\",\n\t\t\t\t\t\"Add smoke/regression tests for the new flow.\",\n\t\t\t\t\tcontractGateStep,\n\t\t\t\t],\n\t\t\t\tpros: [\"Fast time-to-value\", \"Controlled risk\", \"Easy rollback\"],\n\t\t\t\tcons: [\"Some UX/infrastructure remains for the next phase\"],\n\t\t\t\twhen_to_choose: \"Choose when you need delivery this sprint with controlled blast radius.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"2\",\n\t\t\t\ttitle: \"Comprehensive implementation\",\n\t\t\t\tsummary: \"Ship the full feature with infrastructure, edge cases, and API expansion.\",\n\t\t\t\tcomplexity: \"high\",\n\t\t\t\tblast_radius: \"high\",\n\t\t\t\tsuggested_files: broadFiles,\n\t\t\t\tplan: [\n\t\t\t\t\t\"Design architecture and module boundaries before coding.\",\n\t\t\t\t\t\"Implement domain logic, API/UI layers, and persistence.\",\n\t\t\t\t\t\"Cover behavior with integration and contract tests.\",\n\t\t\t\t\t\"Roll out in stages with feature flags and metrics.\",\n\t\t\t\t],\n\t\t\t\tpros: [\"Delivers the full capability\", \"Lower technical debt after release\"],\n\t\t\t\tcons: [\"Higher cost and regression risk\", \"Requires longer review and test cycle\"],\n\t\t\t\twhen_to_choose: \"Choose when this is a strategic milestone and you can afford larger scope.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"3\",\n\t\t\t\ttitle: \"Defer implementation\",\n\t\t\t\tsummary: \"Do not code now; prepare design, risk map, and migration plan first.\",\n\t\t\t\tcomplexity: \"low\",\n\t\t\t\tblast_radius: \"low\",\n\t\t\t\tsuggested_files: [],\n\t\t\t\tplan: [\n\t\t\t\t\t\"Prepare technical design and impacted-area map.\",\n\t\t\t\t\t\"Define readiness criteria and implementation risks.\",\n\t\t\t\t\t\"Resume implementation after dependencies are cleared.\",\n\t\t\t\t],\n\t\t\t\tpros: [\"Minimal immediate risk\", \"Clear plan before coding\"],\n\t\t\t\tcons: [\"Feature is not delivered in current release window\"],\n\t\t\t\twhen_to_choose: \"Choose when prerequisites are missing or risk is too high this cycle.\",\n\t\t\t},\n\t\t];\n\t}\n}\n"]}
1
+ {"version":3,"file":"singular.js","sourceRoot":"","sources":["../../src/core/singular.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACpG,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,QAAQ,EAAE,GAAG,EAAE,MAAM,WAAW,CAAC;AAkE1D,MAAM,oBAAoB,GAAG,IAAI,GAAG,CAAC;IACpC,KAAK;IACL,MAAM;IACN,KAAK;IACL,MAAM;IACN,MAAM;IACN,MAAM;IACN,KAAK;IACL,KAAK;IACL,KAAK;IACL,OAAO;IACP,OAAO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Ae,CAAC;gBAChE,IAAI,EAAE,CAAC,mDAAmD,CAAC;gBAC3D,cAAc,EAAE,yEAAyE;aACzF;YACD;gBACC,EAAE,EAAE,GAAG;gBACP,KAAK,EAAE,8BAA8B;gBACrC,OAAO,EAAE,2EAA2E;gBACpF,UAAU,EAAE,MAAM;gBAClB,YAAY,EAAE,MAAM;gBACpB,eAAe,EAAE,UAAU;gBAC3B,IAAI,EAAE;oBACL,0DAA0D;oBAC1D,yDAAyD;oBACzD,qDAAqD;oBACrD,oDAAoD;iBACpD;gBACD,IAAI,EAAE,CAAC,8BAA8B,EAAE,oCAAoC,CAAC;gBAC5E,IAAI,EAAE,CAAC,iCAAiC,EAAE,uCAAuC,CAAC;gBAClF,cAAc,EAAE,4EAA4E;aAC5F;YACD;gBACC,EAAE,EAAE,GAAG;gBACP,KAAK,EAAE,sBAAsB;gBAC7B,OAAO,EAAE,sEAAsE;gBAC/E,UAAU,EAAE,KAAK;gBACjB,YAAY,EAAE,KAAK;gBACnB,eAAe,EAAE,EAAE;gBACnB,IAAI,EAAE;oBACL,iDAAiD;oBACjD,qDAAqD;oBACrD,uDAAuD;iBACvD;gBACD,IAAI,EAAE,CAAC,wBAAwB,EAAE,0BAA0B,CAAC;gBAC5D,IAAI,EAAE,CAAC,oDAAoD,CAAC;gBAC5D,cAAc,EAAE,uEAAuE;aACvF;SACD,CAAC;IACH,CAAC;CACD","sourcesContent":["import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from \"node:fs\";\nimport { basename, join, relative, sep } from \"node:path\";\nimport type { EngineeringContract } from \"./contract.js\";\n\nexport type SingularComplexity = \"low\" | \"medium\" | \"high\";\nexport type SingularBlastRadius = \"low\" | \"medium\" | \"high\";\nexport type SingularRecommendation = \"implement_now\" | \"implement_incrementally\" | \"defer\";\nexport type SingularStageFit = \"needed_now\" | \"optional_now\" | \"later\";\n\nexport interface SingularImpactAnalysis {\n\tcodebase: string;\n\tdelivery: string;\n\trisks: string;\n\toperations: string;\n}\n\nexport interface SingularOption {\n\tid: string;\n\ttitle: string;\n\tsummary: string;\n\tcomplexity: SingularComplexity;\n\tblast_radius: SingularBlastRadius;\n\tsuggested_files: string[];\n\tplan: string[];\n\tpros: string[];\n\tcons: string[];\n\twhen_to_choose?: string;\n}\n\nexport interface SingularAnalysisResult {\n\trunId: string;\n\trequest: string;\n\tgeneratedAt: string;\n\tscannedFiles: number;\n\tsourceFiles: number;\n\ttestFiles: number;\n\tmatchedFiles: string[];\n\tbaselineComplexity: SingularComplexity;\n\tbaselineBlastRadius: SingularBlastRadius;\n\trecommendation: SingularRecommendation;\n\trecommendationReason: string;\n\tstageFit?: SingularStageFit;\n\tstageFitReason?: string;\n\timpactAnalysis?: SingularImpactAnalysis;\n\tcontractSignals: string[];\n\toptions: SingularOption[];\n}\n\nexport interface SingularLastRun {\n\trunId: string;\n\tanalysisPath: string;\n\tmetaPath?: string;\n\trequest?: string;\n\trecommendation?: SingularRecommendation;\n\tgeneratedAt?: string;\n}\n\nexport interface SingularAnalyzeOptions {\n\trequest: string;\n\tcontract?: EngineeringContract;\n\tautosave?: boolean;\n}\n\nexport interface SingularServiceOptions {\n\tcwd: string;\n}\n\nconst SCAN_TEXT_EXTENSIONS = new Set([\n\t\".ts\",\n\t\".tsx\",\n\t\".js\",\n\t\".jsx\",\n\t\".mjs\",\n\t\".cjs\",\n\t\".py\",\n\t\".go\",\n\t\".rs\",\n\t\".java\",\n\t\".json\",\n\t\".yaml\",\n\t\".yml\",\n\t\".toml\",\n\t\".md\",\n\t\".sh\",\n\t\".sql\",\n\t\".html\",\n\t\".css\",\n]);\n\nconst EXCLUDED_DIR_NAMES = new Set([\".git\", \"node_modules\", \"dist\", \"build\", \".iosm\", \".next\", \"coverage\"]);\n\nconst STOP_WORDS = new Set([\n\t\"a\",\n\t\"an\",\n\t\"the\",\n\t\"and\",\n\t\"or\",\n\t\"for\",\n\t\"with\",\n\t\"from\",\n\t\"into\",\n\t\"about\",\n\t\"что\",\n\t\"как\",\n\t\"для\",\n\t\"это\",\n\t\"надо\",\n\t\"нужно\",\n\t\"добавить\",\n\t\"сделать\",\n\t\"функционал\",\n\t\"feature\",\n\t\"implement\",\n\t\"add\",\n]);\n\nfunction toPosixPath(value: string): string {\n\treturn value.split(sep).join(\"/\");\n}\n\nfunction getExtension(filePath: string): string {\n\tconst normalized = filePath.toLowerCase();\n\tconst index = normalized.lastIndexOf(\".\");\n\treturn index >= 0 ? normalized.slice(index) : \"\";\n}\n\nfunction nowIso(): string {\n\treturn new Date().toISOString();\n}\n\nfunction buildRunId(date = new Date()): string {\n\tconst year = date.getUTCFullYear();\n\tconst month = String(date.getUTCMonth() + 1).padStart(2, \"0\");\n\tconst day = String(date.getUTCDate()).padStart(2, \"0\");\n\tconst hours = String(date.getUTCHours()).padStart(2, \"0\");\n\tconst minutes = String(date.getUTCMinutes()).padStart(2, \"0\");\n\tconst seconds = String(date.getUTCSeconds()).padStart(2, \"0\");\n\tconst millis = String(date.getUTCMilliseconds()).padStart(3, \"0\");\n\tconst suffix = Math.random().toString(36).slice(2, 6);\n\treturn `${year}-${month}-${day}-${hours}${minutes}${seconds}-${millis}-${suffix}`;\n}\n\nfunction normalizeRequestTokens(request: string): string[] {\n\treturn request\n\t\t.toLowerCase()\n\t\t.split(/[^\\p{L}\\p{N}]+/u)\n\t\t.map((token) => token.trim())\n\t\t.filter((token) => token.length >= 3 && !STOP_WORDS.has(token));\n}\n\nfunction scoreToComplexity(score: number): SingularComplexity {\n\tif (score >= 4) return \"high\";\n\tif (score >= 2) return \"medium\";\n\treturn \"low\";\n}\n\nfunction scoreToBlastRadius(score: number): SingularBlastRadius {\n\tif (score >= 4) return \"high\";\n\tif (score >= 2) return \"medium\";\n\treturn \"low\";\n}\n\nfunction defaultSuggestedFiles(matches: string[]): string[] {\n\tif (matches.length > 0) return matches.slice(0, 6);\n\treturn [\"src/**/*\", \"test/**/*\"];\n}\n\nexport class SingularService {\n\tprivate readonly cwd: string;\n\n\tconstructor(options: SingularServiceOptions) {\n\t\tthis.cwd = options.cwd;\n\t}\n\n\tgetAnalysesRoot(): string {\n\t\treturn join(this.cwd, \".iosm\", \"singular\");\n\t}\n\n\tgetLastRun(): SingularLastRun | undefined {\n\t\tconst root = this.getAnalysesRoot();\n\t\tif (!existsSync(root)) return undefined;\n\t\tconst candidates = readdirSync(root, { withFileTypes: true })\n\t\t\t.filter((entry) => entry.isDirectory())\n\t\t\t.map((entry) => entry.name)\n\t\t\t.sort((a, b) => a.localeCompare(b));\n\t\tconst runId = candidates[candidates.length - 1];\n\t\tif (!runId) return undefined;\n\n\t\tconst runDir = join(root, runId);\n\t\tconst analysisPath = join(runDir, \"analysis.json\");\n\t\tif (!existsSync(analysisPath)) return undefined;\n\t\tconst metaPath = join(runDir, \"meta.json\");\n\n\t\tlet request: string | undefined;\n\t\tlet recommendation: SingularRecommendation | undefined;\n\t\tlet generatedAt: string | undefined;\n\t\tif (existsSync(metaPath)) {\n\t\t\ttry {\n\t\t\t\tconst parsed = JSON.parse(readFileSync(metaPath, \"utf8\")) as Record<string, unknown>;\n\t\t\t\trequest = typeof parsed.request === \"string\" ? parsed.request : undefined;\n\t\t\t\trecommendation =\n\t\t\t\t\tparsed.recommendation === \"implement_now\" ||\n\t\t\t\t\tparsed.recommendation === \"implement_incrementally\" ||\n\t\t\t\t\tparsed.recommendation === \"defer\"\n\t\t\t\t\t\t? (parsed.recommendation as SingularRecommendation)\n\t\t\t\t\t\t: undefined;\n\t\t\t\tgeneratedAt = typeof parsed.generatedAt === \"string\" ? parsed.generatedAt : undefined;\n\t\t\t} catch {\n\t\t\t\t// metadata is optional\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\trunId,\n\t\t\tanalysisPath,\n\t\t\tmetaPath: existsSync(metaPath) ? metaPath : undefined,\n\t\t\trequest,\n\t\t\trecommendation,\n\t\t\tgeneratedAt,\n\t\t};\n\t}\n\n\tasync analyze(options: SingularAnalyzeOptions): Promise<SingularAnalysisResult> {\n\t\tconst request = options.request.trim();\n\t\tconst contract = options.contract ?? {};\n\t\tconst autosave = options.autosave !== false;\n\t\tconst runId = buildRunId();\n\t\tconst generatedAt = nowIso();\n\n\t\tconst scan = this.scanRepository(request);\n\t\tconst contractSignals = this.collectContractSignals(contract);\n\t\tconst baselineScore = this.estimateComplexityScore(request, scan.matchedFiles.length, scan.testFiles, contractSignals.length);\n\t\tconst baselineComplexity = scoreToComplexity(baselineScore);\n\t\tconst baselineBlastRadius = scoreToBlastRadius(baselineScore + (scan.matchedFiles.length >= 5 ? 1 : 0));\n\n\t\tconst recommendation = this.buildRecommendation({\n\t\t\trequest,\n\t\t\tbaselineComplexity,\n\t\t\ttestFiles: scan.testFiles,\n\t\t\tmatchedFiles: scan.matchedFiles.length,\n\t\t});\n\n\t\tconst suggestedFiles = defaultSuggestedFiles(scan.matchedFiles);\n\t\tconst optionsList = this.buildOptions({\n\t\t\trequest,\n\t\t\tbaselineComplexity,\n\t\t\tbaselineBlastRadius,\n\t\t\tsuggestedFiles,\n\t\t\tcontractSignals,\n\t\t});\n\n\t\tconst result: SingularAnalysisResult = {\n\t\t\trunId,\n\t\t\trequest,\n\t\t\tgeneratedAt,\n\t\t\tscannedFiles: scan.scannedFiles,\n\t\t\tsourceFiles: scan.sourceFiles,\n\t\t\ttestFiles: scan.testFiles,\n\t\t\tmatchedFiles: scan.matchedFiles,\n\t\t\tbaselineComplexity,\n\t\t\tbaselineBlastRadius,\n\t\t\trecommendation: recommendation.value,\n\t\t\trecommendationReason: recommendation.reason,\n\t\t\tcontractSignals,\n\t\t\toptions: optionsList,\n\t\t};\n\n\t\tif (autosave) {\n\t\t\tthis.saveRunArtifacts(result);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\tsaveAnalysis(result: SingularAnalysisResult): void {\n\t\tthis.saveRunArtifacts(result);\n\t}\n\n\tprivate saveRunArtifacts(result: SingularAnalysisResult): void {\n\t\tconst runDir = join(this.getAnalysesRoot(), result.runId);\n\t\tmkdirSync(runDir, { recursive: true });\n\n\t\tconst analysisPath = join(runDir, \"analysis.json\");\n\t\tconst metaPath = join(runDir, \"meta.json\");\n\n\t\twriteFileSync(analysisPath, `${JSON.stringify(result, null, 2)}\\n`, \"utf8\");\n\t\twriteFileSync(\n\t\t\tmetaPath,\n\t\t\t`${JSON.stringify(\n\t\t\t\t{\n\t\t\t\t\trunId: result.runId,\n\t\t\t\t\tgeneratedAt: result.generatedAt,\n\t\t\t\t\trequest: result.request,\n\t\t\t\t\trecommendation: result.recommendation,\n\t\t\t\t\tstageFit: result.stageFit,\n\t\t\t\t\tbaselineComplexity: result.baselineComplexity,\n\t\t\t\t\tbaselineBlastRadius: result.baselineBlastRadius,\n\t\t\t\t},\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t)}\\n`,\n\t\t\t\"utf8\",\n\t\t);\n\t}\n\n\tprivate scanRepository(request: string): {\n\t\tscannedFiles: number;\n\t\tsourceFiles: number;\n\t\ttestFiles: number;\n\t\tmatchedFiles: string[];\n\t} {\n\t\tconst files = this.walkFiles();\n\t\tconst tokens = normalizeRequestTokens(request);\n\t\tconst scored = files\n\t\t\t.map((absolutePath) => {\n\t\t\t\tconst relativePath = toPosixPath(relative(this.cwd, absolutePath));\n\t\t\t\tconst normalizedPath = relativePath.toLowerCase();\n\t\t\t\tconst fileName = basename(relativePath).toLowerCase();\n\n\t\t\t\tlet score = 0;\n\t\t\t\tfor (const token of tokens) {\n\t\t\t\t\tif (normalizedPath.includes(token)) score += 1;\n\t\t\t\t\tif (fileName.includes(token)) score += 2;\n\t\t\t\t}\n\n\t\t\t\tif (/auth|account|profile|cabinet|dashboard|billing|payment/i.test(request) && /auth|user|account|profile|billing|payment|dashboard/i.test(normalizedPath)) {\n\t\t\t\t\tscore += 1;\n\t\t\t\t}\n\n\t\t\t\treturn { relativePath, score };\n\t\t\t})\n\t\t\t.filter((item) => item.score > 0)\n\t\t\t.sort((a, b) => b.score - a.score || a.relativePath.localeCompare(b.relativePath));\n\n\t\tconst matchedFiles = scored.slice(0, 10).map((item) => item.relativePath);\n\t\tconst sourceFiles = files.filter((absolutePath) => {\n\t\t\tconst rel = toPosixPath(relative(this.cwd, absolutePath));\n\t\t\treturn rel.startsWith(\"src/\") || rel.startsWith(\"app/\") || rel.startsWith(\"packages/\");\n\t\t}).length;\n\t\tconst testFiles = files.filter((absolutePath) => {\n\t\t\tconst rel = toPosixPath(relative(this.cwd, absolutePath)).toLowerCase();\n\t\t\treturn /(^|\\/)(test|tests|__tests__)\\//.test(rel) || /\\.test\\./.test(rel) || /\\.spec\\./.test(rel);\n\t\t}).length;\n\n\t\treturn {\n\t\t\tscannedFiles: files.length,\n\t\t\tsourceFiles,\n\t\t\ttestFiles,\n\t\t\tmatchedFiles,\n\t\t};\n\t}\n\n\tprivate walkFiles(): string[] {\n\t\tconst maxFiles = 12_000;\n\t\tconst stack = [this.cwd];\n\t\tconst files: string[] = [];\n\n\t\twhile (stack.length > 0 && files.length < maxFiles) {\n\t\t\tconst dir = stack.pop();\n\t\t\tif (!dir) break;\n\n\t\t\tlet entries;\n\t\t\ttry {\n\t\t\t\tentries = readdirSync(dir, { withFileTypes: true });\n\t\t\t} catch {\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (const entry of entries) {\n\t\t\t\tconst absolutePath = join(dir, entry.name);\n\t\t\t\tif (entry.isDirectory()) {\n\t\t\t\t\tif (EXCLUDED_DIR_NAMES.has(entry.name)) continue;\n\t\t\t\t\tstack.push(absolutePath);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tif (!entry.isFile()) continue;\n\t\t\t\tif (!SCAN_TEXT_EXTENSIONS.has(getExtension(entry.name))) continue;\n\t\t\t\ttry {\n\t\t\t\t\tif (statSync(absolutePath).size > 800_000) continue;\n\t\t\t\t} catch {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tfiles.push(absolutePath);\n\t\t\t\tif (files.length >= maxFiles) break;\n\t\t\t}\n\t\t}\n\n\t\treturn files.sort((a, b) => a.localeCompare(b));\n\t}\n\n\tprivate collectContractSignals(contract: EngineeringContract): string[] {\n\t\tconst signals: string[] = [];\n\t\tif (contract.goal) signals.push(`goal=${contract.goal}`);\n\t\tif ((contract.constraints ?? []).length > 0) signals.push(`constraints=${contract.constraints?.length ?? 0}`);\n\t\tif ((contract.quality_gates ?? []).length > 0) signals.push(`quality_gates=${contract.quality_gates?.length ?? 0}`);\n\t\tif ((contract.definition_of_done ?? []).length > 0) {\n\t\t\tsignals.push(`definition_of_done=${contract.definition_of_done?.length ?? 0}`);\n\t\t}\n\t\tif ((contract.non_goals ?? []).length > 0) signals.push(`non_goals=${contract.non_goals?.length ?? 0}`);\n\t\tif ((contract.risks ?? []).length > 0) signals.push(`risks=${contract.risks?.length ?? 0}`);\n\t\treturn signals.slice(0, 8);\n\t}\n\n\tprivate estimateComplexityScore(\n\t\trequest: string,\n\t\tmatchedFiles: number,\n\t\ttestFiles: number,\n\t\tcontractSignalCount: number,\n\t): number {\n\t\tlet score = 1;\n\t\tconst normalized = request.toLowerCase();\n\n\t\tif (request.length > 70) score += 1;\n\t\tif (matchedFiles >= 5) score += 1;\n\t\tif (matchedFiles >= 8) score += 1;\n\t\tif (testFiles === 0) score += 1;\n\t\tif (contractSignalCount >= 3) score += 1;\n\n\t\tif (\n\t\t\t/(migration|refactor|rewrite|billing|payment|security|permission|rbac|role|distributed|event|queue|microservice|oauth|sso|регресс|миграц|рефактор|безопасност|права|роли)/.test(\n\t\t\t\tnormalized,\n\t\t\t)\n\t\t) {\n\t\t\tscore += 1;\n\t\t}\n\n\t\tif (/(asap|urgent|критично|срочно|немедленно)/.test(normalized)) {\n\t\t\tscore += 1;\n\t\t}\n\n\t\treturn Math.min(6, score);\n\t}\n\n\tprivate buildRecommendation(payload: {\n\t\trequest: string;\n\t\tbaselineComplexity: SingularComplexity;\n\t\ttestFiles: number;\n\t\tmatchedFiles: number;\n\t}): { value: SingularRecommendation; reason: string } {\n\t\tconst normalized = payload.request.toLowerCase();\n\t\tconst urgent = /(asap|urgent|критично|срочно|немедленно)/.test(normalized);\n\n\t\tif (payload.baselineComplexity === \"high\" && payload.testFiles === 0) {\n\t\t\treturn {\n\t\t\t\tvalue: \"defer\",\n\t\t\t\treason: \"High complexity with no tests in place. Build a safety net and design first.\",\n\t\t\t};\n\t\t}\n\t\tif (payload.baselineComplexity === \"high\" || payload.matchedFiles >= 7) {\n\t\t\treturn {\n\t\t\t\tvalue: \"implement_incrementally\",\n\t\t\t\treason: \"The change touches multiple areas. Prefer incremental rollout via an MVP slice.\",\n\t\t\t};\n\t\t}\n\t\tif (urgent) {\n\t\t\treturn {\n\t\t\t\tvalue: \"implement_now\",\n\t\t\t\treason: \"The request is urgent and risk appears manageable. Implement now with a constrained scope.\",\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tvalue: \"implement_now\",\n\t\t\treason: \"Complexity is manageable. Implement now while enforcing quality gates.\",\n\t\t};\n\t}\n\n\tprivate buildOptions(payload: {\n\t\trequest: string;\n\t\tbaselineComplexity: SingularComplexity;\n\t\tbaselineBlastRadius: SingularBlastRadius;\n\t\tsuggestedFiles: string[];\n\t\tcontractSignals: string[];\n\t}): SingularOption[] {\n\t\tconst compactFiles = payload.suggestedFiles.slice(0, 6);\n\t\tconst broadFiles = payload.suggestedFiles.length > 0 ? payload.suggestedFiles : [\"src/**/*\", \"test/**/*\"];\n\t\tconst contractGateStep =\n\t\t\tpayload.contractSignals.length > 0\n\t\t\t\t? \"Validate contract constraints and quality gates before merge.\"\n\t\t\t\t: \"Define explicit quality gates and Definition of Done before rollout.\";\n\n\t\treturn [\n\t\t\t{\n\t\t\t\tid: \"1\",\n\t\t\t\ttitle: \"Incremental MVP\",\n\t\t\t\tsummary: \"Deliver a minimal usable feature slice quickly with measurable outcomes.\",\n\t\t\t\tcomplexity: payload.baselineComplexity === \"high\" ? \"medium\" : payload.baselineComplexity,\n\t\t\t\tblast_radius: payload.baselineBlastRadius === \"high\" ? \"medium\" : payload.baselineBlastRadius,\n\t\t\t\tsuggested_files: compactFiles,\n\t\t\t\tplan: [\n\t\t\t\t\t\"Lock the minimum scope and explicitly exclude non-goals.\",\n\t\t\t\t\t\"Implement in 1-2 target areas without cascading refactors.\",\n\t\t\t\t\t\"Add smoke/regression tests for the new flow.\",\n\t\t\t\t\tcontractGateStep,\n\t\t\t\t],\n\t\t\t\tpros: [\"Fast time-to-value\", \"Controlled risk\", \"Easy rollback\"],\n\t\t\t\tcons: [\"Some UX/infrastructure remains for the next phase\"],\n\t\t\t\twhen_to_choose: \"Choose when you need delivery this sprint with controlled blast radius.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"2\",\n\t\t\t\ttitle: \"Comprehensive implementation\",\n\t\t\t\tsummary: \"Ship the full feature with infrastructure, edge cases, and API expansion.\",\n\t\t\t\tcomplexity: \"high\",\n\t\t\t\tblast_radius: \"high\",\n\t\t\t\tsuggested_files: broadFiles,\n\t\t\t\tplan: [\n\t\t\t\t\t\"Design architecture and module boundaries before coding.\",\n\t\t\t\t\t\"Implement domain logic, API/UI layers, and persistence.\",\n\t\t\t\t\t\"Cover behavior with integration and contract tests.\",\n\t\t\t\t\t\"Roll out in stages with feature flags and metrics.\",\n\t\t\t\t],\n\t\t\t\tpros: [\"Delivers the full capability\", \"Lower technical debt after release\"],\n\t\t\t\tcons: [\"Higher cost and regression risk\", \"Requires longer review and test cycle\"],\n\t\t\t\twhen_to_choose: \"Choose when this is a strategic milestone and you can afford larger scope.\",\n\t\t\t},\n\t\t\t{\n\t\t\t\tid: \"3\",\n\t\t\t\ttitle: \"Defer implementation\",\n\t\t\t\tsummary: \"Do not code now; prepare design, risk map, and migration plan first.\",\n\t\t\t\tcomplexity: \"low\",\n\t\t\t\tblast_radius: \"low\",\n\t\t\t\tsuggested_files: [],\n\t\t\t\tplan: [\n\t\t\t\t\t\"Prepare technical design and impacted-area map.\",\n\t\t\t\t\t\"Define readiness criteria and implementation risks.\",\n\t\t\t\t\t\"Resume implementation after dependencies are cleared.\",\n\t\t\t\t],\n\t\t\t\tpros: [\"Minimal immediate risk\", \"Clear plan before coding\"],\n\t\t\t\tcons: [\"Feature is not delivered in current release window\"],\n\t\t\t\twhen_to_choose: \"Choose when prerequisites are missing or risk is too high this cycle.\",\n\t\t\t},\n\t\t];\n\t}\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { AgentProfileName } from "./agent-profiles.js";
1
+ import { type AgentProfileName } from "./agent-profiles.js";
2
2
  export type CustomSubagentSourceScope = "builtin" | "global" | "project";
3
3
  export interface CustomSubagentDefinition {
4
4
  name: string;
@@ -1 +1 @@
1
- {"version":3,"file":"subagents.d.ts","sourceRoot":"","sources":["../../src/core/subagents.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,MAAM,yBAAyB,GAAG,SAAS,GAAG,QAAQ,GAAG,SAAS,CAAC;AAEzE,MAAM,WAAW,wBAAwB;IACxC,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,EAAE,MAAM,CAAC;IACpB,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,gBAAgB,CAAC;IAC3B,KAAK,CAAC,EAAE,MAAM,EAAE,CAAC;IACjB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,UAAU,CAAC,EAAE,OAAO,CAAC;CACrB;AAED,MAAM,WAAW,mBAAoB,SAAQ,wBAAwB;IACpE,WAAW,EAAE,yBAAyB,CAAC;IACvC,cAAc,EAAE,MAAM,CAAC;IACvB,SAAS,EAAE,OAAO,CAAC;IACnB,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED,MAAM,WAAW,oBAAoB;IACpC,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,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, statSync } from "node:fs";
2
2
  import { basename, join, resolve } from "node:path";
3
3
  import { parseFrontmatter } from "../utils/frontmatter.js";
4
+ import { isValidProfileName } from "./agent-profiles.js";
4
5
  const BUILTIN_SUBAGENT_PRIORITY = -1;
5
6
  const BUILTIN_SUBAGENTS = [
6
7
  {
@@ -18,6 +19,7 @@ const BUILTIN_SUBAGENTS = [
18
19
  "- Read-only operation. Never edit files.",
19
20
  "- Make claims only with direct repository evidence.",
20
21
  "- Prioritize by user impact and likelihood (P0..P3).",
22
+ "- If the assigned audit still spans multiple independent subsystems and delegation protocol is available, split it with nested delegates instead of producing one monolithic audit.",
21
23
  "",
22
24
  "Required output:",
23
25
  "1) Findings (ordered by severity)",
@@ -168,29 +170,40 @@ const BUILTIN_SUBAGENTS = [
168
170
  name: "meta_orchestrator",
169
171
  description: "Autonomous orchestration lead: audits, plans, and delegates parallel specialists safely.",
170
172
  sourcePath: "builtin://meta_orchestrator.md",
171
- profile: "full",
173
+ profile: "meta",
172
174
  instructions: [
173
175
  "You are the main orchestration agent for complex engineering tasks.",
174
176
  "",
175
177
  "Goal:",
176
178
  "- Drive tasks end-to-end with dynamic delegation: audit -> plan -> execution -> verification.",
179
+ "- Act as the lead orchestrator, not as a substitute for the parent session runtime.",
177
180
  "",
178
181
  "Required operating phases:",
179
- "1) Recon: inspect repository context and constraints.",
180
- "2) Plan: split work into independent chunks and dependency chains.",
181
- "3) Delegate: emit specialist <delegate_task> blocks for chunks that benefit from parallel execution.",
182
- "4) Synthesize: provide integrated results, unresolved risks, and next actions.",
182
+ "1) Recon: do bounded read-only inspection to identify repository context, constraints, and relevant files.",
183
+ "2) Plan: split work into an explicit execution graph of tasks/delegates, including dependencies and lock domains where needed.",
184
+ "3) Execute adaptively: trivial tasks may stay single-agent; medium/complex tasks should maximize safe parallelism via <delegate_task> and multiple focused workstreams.",
185
+ "4) Verify: for any code or test changes, add/update tests and run targeted verification before closure.",
186
+ "5) Synthesize: provide integrated results, unresolved risks, and next actions only after all launched delegates are resolved.",
183
187
  "",
184
188
  "Delegation policy:",
185
- "- Decide number of delegates based on task complexity (usually 1-10).",
189
+ "- Main emphasis in META orchestration is parallelism: use as many focused agents and delegates as the task can support safely, rather than defaulting to one broad worker.",
190
+ "- Recon is only preparation; once you can name the workstreams, stop exploring and delegate.",
191
+ "- For non-trivial work, assume multi-agent parallel fan-out is required unless you can justify why it is not useful.",
192
+ "- Decide number of delegates based on task complexity (usually 1-10), and prefer higher fan-out when the work naturally splits.",
193
+ "- For medium/complex work, target aggressive safe parallel fan-out (commonly >=3 delegates) when independent slices exist.",
194
+ "- If the user asked for N parallel agents, match that fan-out when feasible or explain the exact blocker.",
195
+ "- If a delegate owns a task that still contains multiple independent slices, that delegate should split again with nested delegates instead of executing everything alone.",
186
196
  "- Run independent read-heavy work in parallel by emitting multiple delegate blocks.",
187
197
  "- For write-capable delegates touching overlapping areas, provide lock_key to avoid edit collisions.",
188
198
  "- Use depends_on to enforce ordering for dependent steps (for example verification after implementation).",
189
199
  "- Use clear description values and focused prompts per delegate.",
200
+ "- Do not keep doing direct implementation in the orchestrator after recon for non-trivial work; delegate first.",
201
+ "- Do not collapse the whole implementation into one specialist delegate when multiple independent workstreams exist.",
202
+ "- If you keep any non-trivial work single-agent or undelegated, include one line: DELEGATION_IMPOSSIBLE: <reason>.",
190
203
  "",
191
204
  "Suggested specialist mapping:",
192
205
  "- architecture/recon -> profile=explore or plan",
193
- "- implementation -> profile=full or iosm",
206
+ "- implementation -> profile=meta or full or iosm",
194
207
  "- iosm artifact validation -> profile=iosm_verifier",
195
208
  "- test creation/fixes -> profile=full (or qa_test_engineer when referenced)",
196
209
  "",
@@ -198,6 +211,8 @@ const BUILTIN_SUBAGENTS = [
198
211
  "- Avoid broad overlapping writes without lock separation.",
199
212
  "- If requirements are ambiguous and risky, ask for minimal clarification before destructive changes.",
200
213
  "- Keep all delegated prompts concrete and scoped to specific files/behaviors.",
214
+ "- Do not claim completion while any launched delegate remains pending/running.",
215
+ "- If no code changed and tests were skipped, include an explicit safety justification.",
201
216
  "",
202
217
  "Output requirements:",
203
218
  "- concise execution summary",
@@ -337,9 +352,16 @@ function parseSubagentFile(filePath, cwd) {
337
352
  const defaultName = filePath.split("/").pop()?.replace(/\.md$/i, "") ?? "subagent";
338
353
  const name = (nameRaw || defaultName).trim();
339
354
  const description = typeof frontmatter.description === "string" ? frontmatter.description.trim() : "";
340
- const profile = typeof frontmatter.profile === "string" && frontmatter.profile.trim().length > 0
341
- ? frontmatter.profile.trim()
342
- : undefined;
355
+ const profileRaw = typeof frontmatter.profile === "string" ? frontmatter.profile.trim() : "";
356
+ if (profileRaw.length > 0 && !isValidProfileName(profileRaw.toLowerCase())) {
357
+ return {
358
+ diagnostic: {
359
+ path: filePath,
360
+ message: `Invalid profile "${profileRaw}". Valid profiles: explore, plan, iosm, iosm_analyst, iosm_verifier, cycle_planner, meta, full.`,
361
+ },
362
+ };
363
+ }
364
+ const profile = profileRaw.length > 0 ? profileRaw.toLowerCase() : undefined;
343
365
  const tools = asStringArray(frontmatter.tools);
344
366
  const disallowedTools = asStringArray(frontmatter.disallowed_tools);
345
367
  const systemPrompt = typeof frontmatter.system_prompt === "string" && frontmatter.system_prompt.trim().length > 0
@@ -1 +1 @@
1
- {"version":3,"file":"subagents.js","sourceRoot":"","sources":["../../src/core/subagents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AA8C3D,MAAM,yBAAyB,GAAG,CAAC,CAAC,CAAC;AAErC,MAAM,iBAAiB,GAA+B;IACrD;QACC,IAAI,EAAE,kBAAkB;QACxB,WAAW,EAAE,mFAAmF;QAChG,UAAU,EAAE,+BAA+B;QAC3C,OAAO,EAAE,SAA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MAAM,MAAM,GAAG,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACtG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QAC9B,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,WAAW,KAAK,CAAC;YAAE,OAAO,WAAW,CAAC;QAC1C,OAAO,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport type { AgentProfileName } from \"./agent-profiles.js\";\n\nexport type CustomSubagentSourceScope = \"builtin\" | \"global\" | \"project\";\n\nexport interface CustomSubagentDefinition {\n\tname: string;\n\tdescription: string;\n\tsourcePath: string;\n\tprofile?: AgentProfileName;\n\ttools?: string[];\n\tdisallowedTools?: string[];\n\tsystemPrompt?: string;\n\tinstructions: string;\n\tcwd?: string;\n\tmodel?: string;\n\tbackground?: boolean;\n}\n\nexport interface CustomSubagentEntry extends CustomSubagentDefinition {\n\tsourceScope: CustomSubagentSourceScope;\n\tsourcePriority: number;\n\teffective: boolean;\n\toverriddenByPath?: string;\n}\n\nexport interface SubagentOverrideInfo {\n\tname: string;\n\twinnerPath: string;\n\twinnerScope: CustomSubagentSourceScope;\n\toverriddenPath: string;\n\toverriddenScope: CustomSubagentSourceScope;\n}\n\nexport interface SubagentDiagnostic {\n\tpath: string;\n\tmessage: string;\n}\n\nexport interface LoadCustomSubagentsResult {\n\tagents: CustomSubagentEntry[];\n\tallAgents: CustomSubagentEntry[];\n\toverrides: SubagentOverrideInfo[];\n\tdiagnostics: SubagentDiagnostic[];\n}\n\nconst BUILTIN_SUBAGENT_PRIORITY = -1;\n\nconst BUILTIN_SUBAGENTS: CustomSubagentDefinition[] = [\n\t{\n\t\tname: \"codebase_auditor\",\n\t\tdescription: \"Structured codebase audit for architecture, reliability, security, and test gaps.\",\n\t\tsourcePath: \"builtin://codebase_auditor.md\",\n\t\tprofile: \"explore\",\n\t\tinstructions: [\n\t\t\t\"You are a codebase auditor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Produce an evidence-based audit of architecture, defect risks, and maintainability hotspots.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read-only operation. Never edit files.\",\n\t\t\t\"- Make claims only with direct repository evidence.\",\n\t\t\t\"- Prioritize by user impact and likelihood (P0..P3).\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Findings (ordered by severity)\",\n\t\t\t\"2) Open questions/unknowns\",\n\t\t\t\"3) Recommended next actions\",\n\t\t\t\"\",\n\t\t\t\"For each finding include:\",\n\t\t\t\"- file path + line reference (when available)\",\n\t\t\t\"- risk/impact\",\n\t\t\t\"- concrete fix direction\",\n\t\t\t\"\",\n\t\t\t\"If no issues are found, explicitly state 'No findings' and list residual risks/testing gaps.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"system_error_analyst\",\n\t\tdescription: \"Diagnoses system/runtime failures and produces root-cause + fix plan.\",\n\t\tsourcePath: \"builtin://system_error_analyst.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a system error analyst.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Triage failures, identify probable root cause, and propose a minimal, testable fix plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Do not modify files.\",\n\t\t\t\"- Use deterministic evidence (logs, stack traces, tests, configs).\",\n\t\t\t\"- Distinguish facts vs hypotheses explicitly.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Incident summary\",\n\t\t\t\"2) Root-cause analysis (ranked hypotheses with evidence)\",\n\t\t\t\"3) Minimal patch plan\",\n\t\t\t\"4) Verification plan (commands + expected signals)\",\n\t\t\t\"5) Regression risks\",\n\t\t\t\"\",\n\t\t\t\"Escalation guidance:\",\n\t\t\t\"- If data is insufficient, request the minimum missing evidence instead of guessing.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_change_executor\",\n\t\tdescription: \"Implements repository changes under IOSM methodology and keeps artifacts aligned.\",\n\t\tsourcePath: \"builtin://iosm_change_executor.md\",\n\t\tprofile: \"iosm\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM change executor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze, implement, and verify changes while preserving IOSM methodology and artifact consistency.\",\n\t\t\t\"\",\n\t\t\t\"Execution policy:\",\n\t\t\t\"- Inspect relevant code and .iosm artifacts before edits.\",\n\t\t\t\"- Make minimal, targeted changes with clear rationale.\",\n\t\t\t\"- Run focused verification after each meaningful change.\",\n\t\t\t\"- Keep IOSM artifacts in sync when behavior/metrics assumptions change.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) What changed and why\",\n\t\t\t\"2) Files changed\",\n\t\t\t\"3) Verification executed and results\",\n\t\t\t\"4) Remaining risks/assumptions\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Do not introduce speculative changes.\",\n\t\t\t\"- If requirements are ambiguous, ask a concise clarification before risky edits.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_postchange_verifier\",\n\t\tdescription: \"Post-change IOSM verifier for metric/artifact integrity and regression checks.\",\n\t\tsourcePath: \"builtin://iosm_postchange_verifier.md\",\n\t\tprofile: \"iosm_verifier\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM post-change verifier.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Validate that implemented changes are correctly reflected in IOSM metrics/artifacts.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Restrict edits to .iosm artifacts unless explicitly instructed otherwise.\",\n\t\t\t\"- Prefer deterministic checks and reproducible commands.\",\n\t\t\t\"- Report mismatches and exact remediation steps.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Checks performed\",\n\t\t\t\"2) Pass/fail per check\",\n\t\t\t\"3) Artifact updates applied (if any)\",\n\t\t\t\"4) Remaining discrepancies and follow-ups\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"qa_test_engineer\",\n\t\tdescription: \"Writes tests, runs verification, and fixes regressions with evidence-driven workflow.\",\n\t\tsourcePath: \"builtin://qa_test_engineer.md\",\n\t\tprofile: \"full\",\n\t\tinstructions: [\n\t\t\t\"You are a QA test engineer and regression fixer.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Increase confidence by adding/updating tests, reproducing failures, and fixing root causes.\",\n\t\t\t\"\",\n\t\t\t\"Workflow:\",\n\t\t\t\"1) Reproduce failure (or define expected behavior if bug is not reproducible yet).\",\n\t\t\t\"2) Add/update focused tests that capture expected behavior.\",\n\t\t\t\"3) Run targeted tests first, then broader suite if needed.\",\n\t\t\t\"4) Implement minimal fix in production code.\",\n\t\t\t\"5) Re-run tests and report outcomes.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Never hide failures by removing assertions or disabling tests unless explicitly requested.\",\n\t\t\t\"- Prefer deterministic tests; avoid flaky timing assumptions.\",\n\t\t\t\"- Keep patch size minimal and localized.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Root cause summary\",\n\t\t\t\"2) Tests added/updated\",\n\t\t\t\"3) Code fixes applied\",\n\t\t\t\"4) Commands executed + pass/fail results\",\n\t\t\t\"5) Residual risk\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"test_failure_triager\",\n\t\tdescription: \"Analyzes failing/flaky tests and proposes a ranked remediation plan.\",\n\t\tsourcePath: \"builtin://test_failure_triager.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a test-failure triage specialist.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze failures quickly and produce a ranked, actionable remediation plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read/analyze only; do not edit files.\",\n\t\t\t\"- Separate infra/environment issues from product-code defects.\",\n\t\t\t\"- Label confidence for each hypothesis.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Failure classification (deterministic, flaky, environment, unknown)\",\n\t\t\t\"2) Ranked hypotheses with evidence\",\n\t\t\t\"3) Minimal next steps to verify each hypothesis\",\n\t\t\t\"4) Recommended owner/agent to execute fixes\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"meta_orchestrator\",\n\t\tdescription: \"Autonomous orchestration lead: audits, plans, and delegates parallel specialists safely.\",\n\t\tsourcePath: \"builtin://meta_orchestrator.md\",\n\t\tprofile: \"full\",\n\t\tinstructions: [\n\t\t\t\"You are the main orchestration agent for complex engineering tasks.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Drive tasks end-to-end with dynamic delegation: audit -> plan -> execution -> verification.\",\n\t\t\t\"\",\n\t\t\t\"Required operating phases:\",\n\t\t\t\"1) Recon: inspect repository context and constraints.\",\n\t\t\t\"2) Plan: split work into independent chunks and dependency chains.\",\n\t\t\t\"3) Delegate: emit specialist <delegate_task> blocks for chunks that benefit from parallel execution.\",\n\t\t\t\"4) Synthesize: provide integrated results, unresolved risks, and next actions.\",\n\t\t\t\"\",\n\t\t\t\"Delegation policy:\",\n\t\t\t\"- Decide number of delegates based on task complexity (usually 1-10).\",\n\t\t\t\"- Run independent read-heavy work in parallel by emitting multiple delegate blocks.\",\n\t\t\t\"- For write-capable delegates touching overlapping areas, provide lock_key to avoid edit collisions.\",\n\t\t\t\"- Use depends_on to enforce ordering for dependent steps (for example verification after implementation).\",\n\t\t\t\"- Use clear description values and focused prompts per delegate.\",\n\t\t\t\"\",\n\t\t\t\"Suggested specialist mapping:\",\n\t\t\t\"- architecture/recon -> profile=explore or plan\",\n\t\t\t\"- implementation -> profile=full or iosm\",\n\t\t\t\"- iosm artifact validation -> profile=iosm_verifier\",\n\t\t\t\"- test creation/fixes -> profile=full (or qa_test_engineer when referenced)\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Avoid broad overlapping writes without lock separation.\",\n\t\t\t\"- If requirements are ambiguous and risky, ask for minimal clarification before destructive changes.\",\n\t\t\t\"- Keep all delegated prompts concrete and scoped to specific files/behaviors.\",\n\t\t\t\"\",\n\t\t\t\"Output requirements:\",\n\t\t\t\"- concise execution summary\",\n\t\t\t\"- delegated work breakdown\",\n\t\t\t\"- verification status\",\n\t\t\t\"- residual risks/assumptions\",\n\t\t].join(\"\\n\"),\n\t},\n];\n\nfunction trimWrappingChars(value: string): string {\n\tlet next = value.trim();\n\tnext = next.replace(/^@+/, \"\");\n\tnext = next.replace(/^[`\"'“”‘’]+/, \"\");\n\tnext = next.replace(/[`\"'“”‘’]+$/, \"\");\n\tnext = next.replace(/[),;:!?]+$/, \"\");\n\treturn next.trim();\n}\n\nfunction pushCandidate(set: Set<string>, value: string): void {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return;\n\tset.add(trimmed);\n}\n\nexport function getSubagentLookupCandidates(reference: string): string[] {\n\tconst cleaned = trimWrappingChars(reference);\n\tif (!cleaned) return [];\n\tconst normalized = cleaned.replace(/\\\\/g, \"/\");\n\tconst lowerNormalized = normalized.toLowerCase();\n\tconst candidates = new Set<string>();\n\n\tpushCandidate(candidates, cleaned);\n\tpushCandidate(candidates, cleaned.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, normalized);\n\tpushCandidate(candidates, normalized.replace(/\\.md$/i, \"\"));\n\n\tconst pathMarkers = [\"/.iosm/agents/\", \".iosm/agents/\", \"/agents/\", \"agents/\"];\n\tfor (const marker of pathMarkers) {\n\t\tconst markerIndex = lowerNormalized.lastIndexOf(marker.toLowerCase());\n\t\tif (markerIndex === -1) continue;\n\t\tconst suffix = normalized.slice(markerIndex + marker.length);\n\t\tpushCandidate(candidates, suffix);\n\t\tpushCandidate(candidates, suffix.replace(/\\.md$/i, \"\"));\n\t}\n\n\tconst baseFromNormalized = normalized.split(\"/\").filter(Boolean).pop() ?? \"\";\n\tconst baseFromPath = basename(cleaned);\n\tpushCandidate(candidates, baseFromNormalized);\n\tpushCandidate(candidates, baseFromNormalized.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, baseFromPath);\n\tpushCandidate(candidates, baseFromPath.replace(/\\.md$/i, \"\"));\n\n\treturn Array.from(candidates);\n}\n\nexport function resolveCustomSubagentReference(\n\treference: string,\n\tagents: ReadonlyArray<Pick<CustomSubagentDefinition, \"name\" | \"sourcePath\">>,\n): string | undefined {\n\tif (agents.length === 0) return undefined;\n\tconst byName = new Map<string, string>();\n\tconst byNameLower = new Map<string, string>();\n\tconst bySourceBaseLower = new Map<string, string>();\n\n\tfor (const agent of agents) {\n\t\tbyName.set(agent.name, agent.name);\n\t\tbyNameLower.set(agent.name.toLowerCase(), agent.name);\n\n\t\tconst sourceBase = basename(agent.sourcePath);\n\t\tif (sourceBase) {\n\t\t\tconst sourceBaseLower = sourceBase.toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseLower, agent.name);\n\t\t\t}\n\t\t\tconst sourceBaseNoMdLower = sourceBase.replace(/\\.md$/i, \"\").toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseNoMdLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseNoMdLower, agent.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const candidate of getSubagentLookupCandidates(reference)) {\n\t\tconst exact = byName.get(candidate);\n\t\tif (exact) return exact;\n\n\t\tconst lower = candidate.toLowerCase();\n\t\tconst byLower = byNameLower.get(lower);\n\t\tif (byLower) return byLower;\n\t\tconst withoutMd = lower.replace(/\\.md$/i, \"\");\n\t\tconst byWithoutMd = byNameLower.get(withoutMd);\n\t\tif (byWithoutMd) return byWithoutMd;\n\n\t\tconst byBase = bySourceBaseLower.get(lower) ?? bySourceBaseLower.get(withoutMd);\n\t\tif (byBase) return byBase;\n\t}\n\n\treturn undefined;\n}\n\ntype ParsedFrontmatter = {\n\tname?: unknown;\n\tdescription?: unknown;\n\tprofile?: unknown;\n\ttools?: unknown;\n\tdisallowed_tools?: unknown;\n\tsystem_prompt?: unknown;\n\tcwd?: unknown;\n\tmodel?: unknown;\n\tbackground?: unknown;\n};\n\nfunction readMarkdownFilesRecursive(root: string): string[] {\n\tif (!existsSync(root)) return [];\n\tconst files: string[] = [];\n\tconst walk = (dir: string): void => {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true }).sort((left, right) =>\n\t\t\tleft.name.localeCompare(right.name),\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\twalk(full);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.isFile() && entry.name.toLowerCase().endsWith(\".md\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t};\n\twalk(root);\n\treturn files;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (Array.isArray(value)) {\n\t\tconst normalized = value.map((item) => String(item).trim()).filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\treturn undefined;\n}\n\nfunction parseSubagentFile(filePath: string, cwd: string): { agent?: CustomSubagentDefinition; diagnostic?: SubagentDiagnostic } {\n\tlet content: string;\n\ttry {\n\t\tcontent = readFileSync(filePath, \"utf8\");\n\t} catch (error) {\n\t\treturn {\n\t\t\tdiagnostic: { path: filePath, message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}` },\n\t\t};\n\t}\n\n\tconst { frontmatter, body } = parseFrontmatter<ParsedFrontmatter>(content);\n\tconst nameRaw = typeof frontmatter.name === \"string\" ? frontmatter.name.trim() : \"\";\n\tconst defaultName = filePath.split(\"/\").pop()?.replace(/\\.md$/i, \"\") ?? \"subagent\";\n\tconst name = (nameRaw || defaultName).trim();\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tconst profile =\n\t\ttypeof frontmatter.profile === \"string\" && frontmatter.profile.trim().length > 0\n\t\t\t? (frontmatter.profile.trim() as AgentProfileName)\n\t\t\t: undefined;\n\tconst tools = asStringArray(frontmatter.tools);\n\tconst disallowedTools = asStringArray(frontmatter.disallowed_tools);\n\tconst systemPrompt =\n\t\ttypeof frontmatter.system_prompt === \"string\" && frontmatter.system_prompt.trim().length > 0\n\t\t\t? frontmatter.system_prompt.trim()\n\t\t\t: undefined;\n\tconst configuredCwd =\n\t\ttypeof frontmatter.cwd === \"string\" && frontmatter.cwd.trim().length > 0\n\t\t\t? resolve(cwd, frontmatter.cwd.trim())\n\t\t\t: undefined;\n\n\tif (configuredCwd) {\n\t\ttry {\n\t\t\tif (!existsSync(configuredCwd) || !statSync(configuredCwd).isDirectory()) {\n\t\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t}\n\t}\n\n\tconst instructions = body.trim();\n\tif (!instructions) {\n\t\treturn { diagnostic: { path: filePath, message: \"Subagent instructions are empty.\" } };\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription: description || `Custom subagent ${name}`,\n\t\t\tsourcePath: filePath,\n\t\t\tprofile,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tsystemPrompt,\n\t\t\tinstructions,\n\t\t\tcwd: configuredCwd,\n\t\t\tmodel: typeof frontmatter.model === \"string\" ? frontmatter.model.trim() : undefined,\n\t\t\tbackground: frontmatter.background === true,\n\t\t},\n\t};\n}\n\nexport function loadCustomSubagents(options: { cwd: string; agentDir: string }): LoadCustomSubagentsResult {\n\tconst roots: Array<{ path: string; scope: CustomSubagentSourceScope; priority: number }> = [\n\t\t{ path: join(options.agentDir, \"agents\"), scope: \"global\", priority: 0 },\n\t\t{ path: join(options.cwd, \".iosm\", \"agents\"), scope: \"project\", priority: 1 },\n\t];\n\tconst diagnostics: SubagentDiagnostic[] = [];\n\tconst overrides: SubagentOverrideInfo[] = [];\n\tconst allAgents: CustomSubagentEntry[] = [];\n\tconst byName = new Map<string, CustomSubagentEntry>();\n\n\tconst registerEntry = (entry: CustomSubagentEntry): void => {\n\t\tconst existing = byName.get(entry.name);\n\t\tif (!existing) {\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\tallAgents.push(entry);\n\t\t\treturn;\n\t\t}\n\n\t\tconst shouldReplace =\n\t\t\tentry.sourcePriority > existing.sourcePriority ||\n\t\t\t(entry.sourcePriority === existing.sourcePriority &&\n\t\t\t\tentry.sourcePath.localeCompare(existing.sourcePath) > 0);\n\n\t\tif (entry.sourcePriority === existing.sourcePriority) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: entry.sourcePath,\n\t\t\t\tmessage: `Duplicate agent \"${entry.name}\" in ${entry.sourceScope} scope; ${\n\t\t\t\t\tshouldReplace ? \"this file takes precedence\" : \"existing file keeps precedence\"\n\t\t\t\t}.`,\n\t\t\t});\n\t\t}\n\n\t\tif (shouldReplace) {\n\t\t\texisting.effective = false;\n\t\t\texisting.overriddenByPath = entry.sourcePath;\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: entry.sourcePath,\n\t\t\t\twinnerScope: entry.sourceScope,\n\t\t\t\toverriddenPath: existing.sourcePath,\n\t\t\t\toverriddenScope: existing.sourceScope,\n\t\t\t});\n\t\t} else {\n\t\t\tentry.overriddenByPath = existing.sourcePath;\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: existing.sourcePath,\n\t\t\t\twinnerScope: existing.sourceScope,\n\t\t\t\toverriddenPath: entry.sourcePath,\n\t\t\t\toverriddenScope: entry.sourceScope,\n\t\t\t});\n\t\t}\n\n\t\tallAgents.push(entry);\n\t};\n\n\tfor (const builtin of BUILTIN_SUBAGENTS) {\n\t\tregisterEntry({\n\t\t\t...builtin,\n\t\t\tsourceScope: \"builtin\",\n\t\t\tsourcePriority: BUILTIN_SUBAGENT_PRIORITY,\n\t\t\teffective: false,\n\t\t});\n\t}\n\n\tfor (const root of roots) {\n\t\tfor (const file of readMarkdownFilesRecursive(root.path)) {\n\t\t\tconst parsed = parseSubagentFile(file, options.cwd);\n\t\t\tif (parsed.diagnostic) {\n\t\t\t\tdiagnostics.push(parsed.diagnostic);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!parsed.agent) continue;\n\t\t\tconst entry: CustomSubagentEntry = {\n\t\t\t\t...parsed.agent,\n\t\t\t\tsourceScope: root.scope,\n\t\t\t\tsourcePriority: root.priority,\n\t\t\t\teffective: false,\n\t\t\t};\n\t\t\tregisterEntry(entry);\n\t\t}\n\t}\n\n\tconst agents = Array.from(byName.values()).sort((left, right) => left.name.localeCompare(right.name));\n\tallAgents.sort((left, right) => {\n\t\tconst nameCompare = left.name.localeCompare(right.name);\n\t\tif (nameCompare !== 0) return nameCompare;\n\t\treturn right.sourcePriority - left.sourcePriority;\n\t});\n\treturn { agents, allAgents, overrides, diagnostics };\n}\n"]}
1
+ {"version":3,"file":"subagents.js","sourceRoot":"","sources":["../../src/core/subagents.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AAC1E,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACpD,OAAO,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAC3D,OAAO,EAAE,kBAAkB,EAAyB,MAAM,qBAAqB,CAAC;AA6ChF,MAAM,yBAAyB,GAAG,CAAC,CAAC,CAAC;AAErC,MAAM,iBAAiB,GAA+B;IACrD;QACC,IAAI,EAAE,kBAAkB;QACxB,WAAW,EAAE,mFAAmF;QAChG,UAAU,EAAE,+BAA+B;QAC3C,OAAO,EAAE,SAAS;QAClB,YAAY,EAAE;YACb,6BAA6B;YAC7B,EAAE;YACF,OAAO;YACP,gGAAgG;YAChG,EAAE;YACF,QAAQ;YACR,0CAA0C;YAC1C,qDAAqD;YACrD,sDAAsD;YACtD,qLAAqL;YACrL,EAAE;YACF,kBAAkB;YAClB,mCAAmC;YACnC,4BAA4B;YAC5B,6BAA6B;YAC7B,EAAE;YACF,2BAA2B;YAC3B,+CAA+C;YAC/C,eAAe;YACf,0BAA0B;YAC1B,EAAE;YACF,8FAA8F;SAC9F,CAAC,IAAI,CAAC,IAAI,CAAC;KACZ;IACD;QACC,IAAI,EAAE,sBAAsB;QAC5B,WAAW,EAAE,uEAAuE;QACpF,UAAU,EAAE,mCAAmC;QAC/C,OAAO,EAAE,MAAM;QACf,YAAY,EAAE;YACb,iCAAiC;YACjC,EAAE;YACF,OAAO;YACP,4FAA4F;YAC5F,EAAE;YACF,QAAQ;YACR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AAE,CAAC,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC;IACtG,SAAS,CAAC,IAAI,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE;QAC9B,MAAM,WAAW,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QACxD,IAAI,WAAW,KAAK,CAAC;YAAE,OAAO,WAAW,CAAC;QAC1C,OAAO,KAAK,CAAC,cAAc,GAAG,IAAI,CAAC,cAAc,CAAC;IACnD,CAAC,CAAC,CAAC;IACH,OAAO,EAAE,MAAM,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,CAAC;AACtD,CAAC","sourcesContent":["import { existsSync, readdirSync, readFileSync, statSync } from \"node:fs\";\nimport { basename, join, resolve } from \"node:path\";\nimport { parseFrontmatter } from \"../utils/frontmatter.js\";\nimport { isValidProfileName, type AgentProfileName } from \"./agent-profiles.js\";\n\nexport type CustomSubagentSourceScope = \"builtin\" | \"global\" | \"project\";\n\nexport interface CustomSubagentDefinition {\n\tname: string;\n\tdescription: string;\n\tsourcePath: string;\n\tprofile?: AgentProfileName;\n\ttools?: string[];\n\tdisallowedTools?: string[];\n\tsystemPrompt?: string;\n\tinstructions: string;\n\tcwd?: string;\n\tmodel?: string;\n\tbackground?: boolean;\n}\n\nexport interface CustomSubagentEntry extends CustomSubagentDefinition {\n\tsourceScope: CustomSubagentSourceScope;\n\tsourcePriority: number;\n\teffective: boolean;\n\toverriddenByPath?: string;\n}\n\nexport interface SubagentOverrideInfo {\n\tname: string;\n\twinnerPath: string;\n\twinnerScope: CustomSubagentSourceScope;\n\toverriddenPath: string;\n\toverriddenScope: CustomSubagentSourceScope;\n}\n\nexport interface SubagentDiagnostic {\n\tpath: string;\n\tmessage: string;\n}\n\nexport interface LoadCustomSubagentsResult {\n\tagents: CustomSubagentEntry[];\n\tallAgents: CustomSubagentEntry[];\n\toverrides: SubagentOverrideInfo[];\n\tdiagnostics: SubagentDiagnostic[];\n}\n\nconst BUILTIN_SUBAGENT_PRIORITY = -1;\n\nconst BUILTIN_SUBAGENTS: CustomSubagentDefinition[] = [\n\t{\n\t\tname: \"codebase_auditor\",\n\t\tdescription: \"Structured codebase audit for architecture, reliability, security, and test gaps.\",\n\t\tsourcePath: \"builtin://codebase_auditor.md\",\n\t\tprofile: \"explore\",\n\t\tinstructions: [\n\t\t\t\"You are a codebase auditor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Produce an evidence-based audit of architecture, defect risks, and maintainability hotspots.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read-only operation. Never edit files.\",\n\t\t\t\"- Make claims only with direct repository evidence.\",\n\t\t\t\"- Prioritize by user impact and likelihood (P0..P3).\",\n\t\t\t\"- If the assigned audit still spans multiple independent subsystems and delegation protocol is available, split it with nested delegates instead of producing one monolithic audit.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Findings (ordered by severity)\",\n\t\t\t\"2) Open questions/unknowns\",\n\t\t\t\"3) Recommended next actions\",\n\t\t\t\"\",\n\t\t\t\"For each finding include:\",\n\t\t\t\"- file path + line reference (when available)\",\n\t\t\t\"- risk/impact\",\n\t\t\t\"- concrete fix direction\",\n\t\t\t\"\",\n\t\t\t\"If no issues are found, explicitly state 'No findings' and list residual risks/testing gaps.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"system_error_analyst\",\n\t\tdescription: \"Diagnoses system/runtime failures and produces root-cause + fix plan.\",\n\t\tsourcePath: \"builtin://system_error_analyst.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a system error analyst.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Triage failures, identify probable root cause, and propose a minimal, testable fix plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Do not modify files.\",\n\t\t\t\"- Use deterministic evidence (logs, stack traces, tests, configs).\",\n\t\t\t\"- Distinguish facts vs hypotheses explicitly.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Incident summary\",\n\t\t\t\"2) Root-cause analysis (ranked hypotheses with evidence)\",\n\t\t\t\"3) Minimal patch plan\",\n\t\t\t\"4) Verification plan (commands + expected signals)\",\n\t\t\t\"5) Regression risks\",\n\t\t\t\"\",\n\t\t\t\"Escalation guidance:\",\n\t\t\t\"- If data is insufficient, request the minimum missing evidence instead of guessing.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_change_executor\",\n\t\tdescription: \"Implements repository changes under IOSM methodology and keeps artifacts aligned.\",\n\t\tsourcePath: \"builtin://iosm_change_executor.md\",\n\t\tprofile: \"iosm\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM change executor.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze, implement, and verify changes while preserving IOSM methodology and artifact consistency.\",\n\t\t\t\"\",\n\t\t\t\"Execution policy:\",\n\t\t\t\"- Inspect relevant code and .iosm artifacts before edits.\",\n\t\t\t\"- Make minimal, targeted changes with clear rationale.\",\n\t\t\t\"- Run focused verification after each meaningful change.\",\n\t\t\t\"- Keep IOSM artifacts in sync when behavior/metrics assumptions change.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) What changed and why\",\n\t\t\t\"2) Files changed\",\n\t\t\t\"3) Verification executed and results\",\n\t\t\t\"4) Remaining risks/assumptions\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Do not introduce speculative changes.\",\n\t\t\t\"- If requirements are ambiguous, ask a concise clarification before risky edits.\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"iosm_postchange_verifier\",\n\t\tdescription: \"Post-change IOSM verifier for metric/artifact integrity and regression checks.\",\n\t\tsourcePath: \"builtin://iosm_postchange_verifier.md\",\n\t\tprofile: \"iosm_verifier\",\n\t\tinstructions: [\n\t\t\t\"You are an IOSM post-change verifier.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Validate that implemented changes are correctly reflected in IOSM metrics/artifacts.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Restrict edits to .iosm artifacts unless explicitly instructed otherwise.\",\n\t\t\t\"- Prefer deterministic checks and reproducible commands.\",\n\t\t\t\"- Report mismatches and exact remediation steps.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Checks performed\",\n\t\t\t\"2) Pass/fail per check\",\n\t\t\t\"3) Artifact updates applied (if any)\",\n\t\t\t\"4) Remaining discrepancies and follow-ups\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"qa_test_engineer\",\n\t\tdescription: \"Writes tests, runs verification, and fixes regressions with evidence-driven workflow.\",\n\t\tsourcePath: \"builtin://qa_test_engineer.md\",\n\t\tprofile: \"full\",\n\t\tinstructions: [\n\t\t\t\"You are a QA test engineer and regression fixer.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Increase confidence by adding/updating tests, reproducing failures, and fixing root causes.\",\n\t\t\t\"\",\n\t\t\t\"Workflow:\",\n\t\t\t\"1) Reproduce failure (or define expected behavior if bug is not reproducible yet).\",\n\t\t\t\"2) Add/update focused tests that capture expected behavior.\",\n\t\t\t\"3) Run targeted tests first, then broader suite if needed.\",\n\t\t\t\"4) Implement minimal fix in production code.\",\n\t\t\t\"5) Re-run tests and report outcomes.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Never hide failures by removing assertions or disabling tests unless explicitly requested.\",\n\t\t\t\"- Prefer deterministic tests; avoid flaky timing assumptions.\",\n\t\t\t\"- Keep patch size minimal and localized.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Root cause summary\",\n\t\t\t\"2) Tests added/updated\",\n\t\t\t\"3) Code fixes applied\",\n\t\t\t\"4) Commands executed + pass/fail results\",\n\t\t\t\"5) Residual risk\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"test_failure_triager\",\n\t\tdescription: \"Analyzes failing/flaky tests and proposes a ranked remediation plan.\",\n\t\tsourcePath: \"builtin://test_failure_triager.md\",\n\t\tprofile: \"plan\",\n\t\tinstructions: [\n\t\t\t\"You are a test-failure triage specialist.\",\n\t\t\t\"\",\n\t\t\t\"Goal:\",\n\t\t\t\"- Analyze failures quickly and produce a ranked, actionable remediation plan.\",\n\t\t\t\"\",\n\t\t\t\"Rules:\",\n\t\t\t\"- Read/analyze only; do not edit files.\",\n\t\t\t\"- Separate infra/environment issues from product-code defects.\",\n\t\t\t\"- Label confidence for each hypothesis.\",\n\t\t\t\"\",\n\t\t\t\"Required output:\",\n\t\t\t\"1) Failure classification (deterministic, flaky, environment, unknown)\",\n\t\t\t\"2) Ranked hypotheses with evidence\",\n\t\t\t\"3) Minimal next steps to verify each hypothesis\",\n\t\t\t\"4) Recommended owner/agent to execute fixes\",\n\t\t].join(\"\\n\"),\n\t},\n\t{\n\t\tname: \"meta_orchestrator\",\n\t\tdescription: \"Autonomous orchestration lead: audits, plans, and delegates parallel specialists safely.\",\n\t\tsourcePath: \"builtin://meta_orchestrator.md\",\n\t\tprofile: \"meta\",\n\t\t\tinstructions: [\n\t\t\t\t\"You are the main orchestration agent for complex engineering tasks.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Goal:\",\n\t\t\t\t\"- Drive tasks end-to-end with dynamic delegation: audit -> plan -> execution -> verification.\",\n\t\t\t\t\"- Act as the lead orchestrator, not as a substitute for the parent session runtime.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Required operating phases:\",\n\t\t\t\t\"1) Recon: do bounded read-only inspection to identify repository context, constraints, and relevant files.\",\n\t\t\t\t\"2) Plan: split work into an explicit execution graph of tasks/delegates, including dependencies and lock domains where needed.\",\n\t\t\t\t\"3) Execute adaptively: trivial tasks may stay single-agent; medium/complex tasks should maximize safe parallelism via <delegate_task> and multiple focused workstreams.\",\n\t\t\t\t\"4) Verify: for any code or test changes, add/update tests and run targeted verification before closure.\",\n\t\t\t\t\"5) Synthesize: provide integrated results, unresolved risks, and next actions only after all launched delegates are resolved.\",\n\t\t\t\t\"\",\n\t\t\t\t\"Delegation policy:\",\n\t\t\t\t\"- Main emphasis in META orchestration is parallelism: use as many focused agents and delegates as the task can support safely, rather than defaulting to one broad worker.\",\n\t\t\t\t\"- Recon is only preparation; once you can name the workstreams, stop exploring and delegate.\",\n\t\t\t\t\"- For non-trivial work, assume multi-agent parallel fan-out is required unless you can justify why it is not useful.\",\n\t\t\t\t\"- Decide number of delegates based on task complexity (usually 1-10), and prefer higher fan-out when the work naturally splits.\",\n\t\t\t\t\"- For medium/complex work, target aggressive safe parallel fan-out (commonly >=3 delegates) when independent slices exist.\",\n\t\t\t\t\"- If the user asked for N parallel agents, match that fan-out when feasible or explain the exact blocker.\",\n\t\t\t\t\"- If a delegate owns a task that still contains multiple independent slices, that delegate should split again with nested delegates instead of executing everything alone.\",\n\t\t\t\t\"- Run independent read-heavy work in parallel by emitting multiple delegate blocks.\",\n\t\t\t\t\"- For write-capable delegates touching overlapping areas, provide lock_key to avoid edit collisions.\",\n\t\t\t\t\"- Use depends_on to enforce ordering for dependent steps (for example verification after implementation).\",\n\t\t\t\t\"- Use clear description values and focused prompts per delegate.\",\n\t\t\t\t\"- Do not keep doing direct implementation in the orchestrator after recon for non-trivial work; delegate first.\",\n\t\t\t\t\"- Do not collapse the whole implementation into one specialist delegate when multiple independent workstreams exist.\",\n\t\t\t\t\"- If you keep any non-trivial work single-agent or undelegated, include one line: DELEGATION_IMPOSSIBLE: <reason>.\",\n\t\t\t\"\",\n\t\t\t\"Suggested specialist mapping:\",\n\t\t\t\"- architecture/recon -> profile=explore or plan\",\n\t\t\t\"- implementation -> profile=meta or full or iosm\",\n\t\t\t\"- iosm artifact validation -> profile=iosm_verifier\",\n\t\t\t\"- test creation/fixes -> profile=full (or qa_test_engineer when referenced)\",\n\t\t\t\"\",\n\t\t\t\"Safety rules:\",\n\t\t\t\"- Avoid broad overlapping writes without lock separation.\",\n\t\t\t\"- If requirements are ambiguous and risky, ask for minimal clarification before destructive changes.\",\n\t\t\t\"- Keep all delegated prompts concrete and scoped to specific files/behaviors.\",\n\t\t\t\"- Do not claim completion while any launched delegate remains pending/running.\",\n\t\t\t\"- If no code changed and tests were skipped, include an explicit safety justification.\",\n\t\t\t\"\",\n\t\t\t\"Output requirements:\",\n\t\t\t\"- concise execution summary\",\n\t\t\t\"- delegated work breakdown\",\n\t\t\t\"- verification status\",\n\t\t\t\"- residual risks/assumptions\",\n\t\t].join(\"\\n\"),\n\t},\n];\n\nfunction trimWrappingChars(value: string): string {\n\tlet next = value.trim();\n\tnext = next.replace(/^@+/, \"\");\n\tnext = next.replace(/^[`\"'“”‘’]+/, \"\");\n\tnext = next.replace(/[`\"'“”‘’]+$/, \"\");\n\tnext = next.replace(/[),;:!?]+$/, \"\");\n\treturn next.trim();\n}\n\nfunction pushCandidate(set: Set<string>, value: string): void {\n\tconst trimmed = value.trim();\n\tif (!trimmed) return;\n\tset.add(trimmed);\n}\n\nexport function getSubagentLookupCandidates(reference: string): string[] {\n\tconst cleaned = trimWrappingChars(reference);\n\tif (!cleaned) return [];\n\tconst normalized = cleaned.replace(/\\\\/g, \"/\");\n\tconst lowerNormalized = normalized.toLowerCase();\n\tconst candidates = new Set<string>();\n\n\tpushCandidate(candidates, cleaned);\n\tpushCandidate(candidates, cleaned.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, normalized);\n\tpushCandidate(candidates, normalized.replace(/\\.md$/i, \"\"));\n\n\tconst pathMarkers = [\"/.iosm/agents/\", \".iosm/agents/\", \"/agents/\", \"agents/\"];\n\tfor (const marker of pathMarkers) {\n\t\tconst markerIndex = lowerNormalized.lastIndexOf(marker.toLowerCase());\n\t\tif (markerIndex === -1) continue;\n\t\tconst suffix = normalized.slice(markerIndex + marker.length);\n\t\tpushCandidate(candidates, suffix);\n\t\tpushCandidate(candidates, suffix.replace(/\\.md$/i, \"\"));\n\t}\n\n\tconst baseFromNormalized = normalized.split(\"/\").filter(Boolean).pop() ?? \"\";\n\tconst baseFromPath = basename(cleaned);\n\tpushCandidate(candidates, baseFromNormalized);\n\tpushCandidate(candidates, baseFromNormalized.replace(/\\.md$/i, \"\"));\n\tpushCandidate(candidates, baseFromPath);\n\tpushCandidate(candidates, baseFromPath.replace(/\\.md$/i, \"\"));\n\n\treturn Array.from(candidates);\n}\n\nexport function resolveCustomSubagentReference(\n\treference: string,\n\tagents: ReadonlyArray<Pick<CustomSubagentDefinition, \"name\" | \"sourcePath\">>,\n): string | undefined {\n\tif (agents.length === 0) return undefined;\n\tconst byName = new Map<string, string>();\n\tconst byNameLower = new Map<string, string>();\n\tconst bySourceBaseLower = new Map<string, string>();\n\n\tfor (const agent of agents) {\n\t\tbyName.set(agent.name, agent.name);\n\t\tbyNameLower.set(agent.name.toLowerCase(), agent.name);\n\n\t\tconst sourceBase = basename(agent.sourcePath);\n\t\tif (sourceBase) {\n\t\t\tconst sourceBaseLower = sourceBase.toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseLower, agent.name);\n\t\t\t}\n\t\t\tconst sourceBaseNoMdLower = sourceBase.replace(/\\.md$/i, \"\").toLowerCase();\n\t\t\tif (!bySourceBaseLower.has(sourceBaseNoMdLower)) {\n\t\t\t\tbySourceBaseLower.set(sourceBaseNoMdLower, agent.name);\n\t\t\t}\n\t\t}\n\t}\n\n\tfor (const candidate of getSubagentLookupCandidates(reference)) {\n\t\tconst exact = byName.get(candidate);\n\t\tif (exact) return exact;\n\n\t\tconst lower = candidate.toLowerCase();\n\t\tconst byLower = byNameLower.get(lower);\n\t\tif (byLower) return byLower;\n\t\tconst withoutMd = lower.replace(/\\.md$/i, \"\");\n\t\tconst byWithoutMd = byNameLower.get(withoutMd);\n\t\tif (byWithoutMd) return byWithoutMd;\n\n\t\tconst byBase = bySourceBaseLower.get(lower) ?? bySourceBaseLower.get(withoutMd);\n\t\tif (byBase) return byBase;\n\t}\n\n\treturn undefined;\n}\n\ntype ParsedFrontmatter = {\n\tname?: unknown;\n\tdescription?: unknown;\n\tprofile?: unknown;\n\ttools?: unknown;\n\tdisallowed_tools?: unknown;\n\tsystem_prompt?: unknown;\n\tcwd?: unknown;\n\tmodel?: unknown;\n\tbackground?: unknown;\n};\n\nfunction readMarkdownFilesRecursive(root: string): string[] {\n\tif (!existsSync(root)) return [];\n\tconst files: string[] = [];\n\tconst walk = (dir: string): void => {\n\t\tconst entries = readdirSync(dir, { withFileTypes: true }).sort((left, right) =>\n\t\t\tleft.name.localeCompare(right.name),\n\t\t);\n\t\tfor (const entry of entries) {\n\t\t\tconst full = join(dir, entry.name);\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\twalk(full);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (entry.isFile() && entry.name.toLowerCase().endsWith(\".md\")) {\n\t\t\t\tfiles.push(full);\n\t\t\t}\n\t\t}\n\t};\n\twalk(root);\n\treturn files;\n}\n\nfunction asStringArray(value: unknown): string[] | undefined {\n\tif (Array.isArray(value)) {\n\t\tconst normalized = value.map((item) => String(item).trim()).filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\tif (typeof value === \"string\") {\n\t\tconst normalized = value\n\t\t\t.split(\",\")\n\t\t\t.map((item) => item.trim())\n\t\t\t.filter(Boolean);\n\t\treturn normalized.length > 0 ? normalized : undefined;\n\t}\n\treturn undefined;\n}\n\nfunction parseSubagentFile(filePath: string, cwd: string): { agent?: CustomSubagentDefinition; diagnostic?: SubagentDiagnostic } {\n\tlet content: string;\n\ttry {\n\t\tcontent = readFileSync(filePath, \"utf8\");\n\t} catch (error) {\n\t\treturn {\n\t\t\tdiagnostic: { path: filePath, message: `Failed to read file: ${error instanceof Error ? error.message : String(error)}` },\n\t\t};\n\t}\n\n\tconst { frontmatter, body } = parseFrontmatter<ParsedFrontmatter>(content);\n\tconst nameRaw = typeof frontmatter.name === \"string\" ? frontmatter.name.trim() : \"\";\n\tconst defaultName = filePath.split(\"/\").pop()?.replace(/\\.md$/i, \"\") ?? \"subagent\";\n\tconst name = (nameRaw || defaultName).trim();\n\tconst description = typeof frontmatter.description === \"string\" ? frontmatter.description.trim() : \"\";\n\tconst profileRaw = typeof frontmatter.profile === \"string\" ? frontmatter.profile.trim() : \"\";\n\tif (profileRaw.length > 0 && !isValidProfileName(profileRaw.toLowerCase())) {\n\t\treturn {\n\t\t\tdiagnostic: {\n\t\t\t\tpath: filePath,\n\t\t\t\tmessage: `Invalid profile \"${profileRaw}\". Valid profiles: explore, plan, iosm, iosm_analyst, iosm_verifier, cycle_planner, meta, full.`,\n\t\t\t},\n\t\t};\n\t}\n\tconst profile =\n\t\tprofileRaw.length > 0 ? (profileRaw.toLowerCase() as AgentProfileName) : undefined;\n\tconst tools = asStringArray(frontmatter.tools);\n\tconst disallowedTools = asStringArray(frontmatter.disallowed_tools);\n\tconst systemPrompt =\n\t\ttypeof frontmatter.system_prompt === \"string\" && frontmatter.system_prompt.trim().length > 0\n\t\t\t? frontmatter.system_prompt.trim()\n\t\t\t: undefined;\n\tconst configuredCwd =\n\t\ttypeof frontmatter.cwd === \"string\" && frontmatter.cwd.trim().length > 0\n\t\t\t? resolve(cwd, frontmatter.cwd.trim())\n\t\t\t: undefined;\n\n\tif (configuredCwd) {\n\t\ttry {\n\t\t\tif (!existsSync(configuredCwd) || !statSync(configuredCwd).isDirectory()) {\n\t\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t\t}\n\t\t} catch {\n\t\t\treturn { diagnostic: { path: filePath, message: `Configured cwd is invalid: ${configuredCwd}` } };\n\t\t}\n\t}\n\n\tconst instructions = body.trim();\n\tif (!instructions) {\n\t\treturn { diagnostic: { path: filePath, message: \"Subagent instructions are empty.\" } };\n\t}\n\n\treturn {\n\t\tagent: {\n\t\t\tname,\n\t\t\tdescription: description || `Custom subagent ${name}`,\n\t\t\tsourcePath: filePath,\n\t\t\tprofile,\n\t\t\ttools,\n\t\t\tdisallowedTools,\n\t\t\tsystemPrompt,\n\t\t\tinstructions,\n\t\t\tcwd: configuredCwd,\n\t\t\tmodel: typeof frontmatter.model === \"string\" ? frontmatter.model.trim() : undefined,\n\t\t\tbackground: frontmatter.background === true,\n\t\t},\n\t};\n}\n\nexport function loadCustomSubagents(options: { cwd: string; agentDir: string }): LoadCustomSubagentsResult {\n\tconst roots: Array<{ path: string; scope: CustomSubagentSourceScope; priority: number }> = [\n\t\t{ path: join(options.agentDir, \"agents\"), scope: \"global\", priority: 0 },\n\t\t{ path: join(options.cwd, \".iosm\", \"agents\"), scope: \"project\", priority: 1 },\n\t];\n\tconst diagnostics: SubagentDiagnostic[] = [];\n\tconst overrides: SubagentOverrideInfo[] = [];\n\tconst allAgents: CustomSubagentEntry[] = [];\n\tconst byName = new Map<string, CustomSubagentEntry>();\n\n\tconst registerEntry = (entry: CustomSubagentEntry): void => {\n\t\tconst existing = byName.get(entry.name);\n\t\tif (!existing) {\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\tallAgents.push(entry);\n\t\t\treturn;\n\t\t}\n\n\t\tconst shouldReplace =\n\t\t\tentry.sourcePriority > existing.sourcePriority ||\n\t\t\t(entry.sourcePriority === existing.sourcePriority &&\n\t\t\t\tentry.sourcePath.localeCompare(existing.sourcePath) > 0);\n\n\t\tif (entry.sourcePriority === existing.sourcePriority) {\n\t\t\tdiagnostics.push({\n\t\t\t\tpath: entry.sourcePath,\n\t\t\t\tmessage: `Duplicate agent \"${entry.name}\" in ${entry.sourceScope} scope; ${\n\t\t\t\t\tshouldReplace ? \"this file takes precedence\" : \"existing file keeps precedence\"\n\t\t\t\t}.`,\n\t\t\t});\n\t\t}\n\n\t\tif (shouldReplace) {\n\t\t\texisting.effective = false;\n\t\t\texisting.overriddenByPath = entry.sourcePath;\n\t\t\tentry.effective = true;\n\t\t\tbyName.set(entry.name, entry);\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: entry.sourcePath,\n\t\t\t\twinnerScope: entry.sourceScope,\n\t\t\t\toverriddenPath: existing.sourcePath,\n\t\t\t\toverriddenScope: existing.sourceScope,\n\t\t\t});\n\t\t} else {\n\t\t\tentry.overriddenByPath = existing.sourcePath;\n\t\t\toverrides.push({\n\t\t\t\tname: entry.name,\n\t\t\t\twinnerPath: existing.sourcePath,\n\t\t\t\twinnerScope: existing.sourceScope,\n\t\t\t\toverriddenPath: entry.sourcePath,\n\t\t\t\toverriddenScope: entry.sourceScope,\n\t\t\t});\n\t\t}\n\n\t\tallAgents.push(entry);\n\t};\n\n\tfor (const builtin of BUILTIN_SUBAGENTS) {\n\t\tregisterEntry({\n\t\t\t...builtin,\n\t\t\tsourceScope: \"builtin\",\n\t\t\tsourcePriority: BUILTIN_SUBAGENT_PRIORITY,\n\t\t\teffective: false,\n\t\t});\n\t}\n\n\tfor (const root of roots) {\n\t\tfor (const file of readMarkdownFilesRecursive(root.path)) {\n\t\t\tconst parsed = parseSubagentFile(file, options.cwd);\n\t\t\tif (parsed.diagnostic) {\n\t\t\t\tdiagnostics.push(parsed.diagnostic);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!parsed.agent) continue;\n\t\t\tconst entry: CustomSubagentEntry = {\n\t\t\t\t...parsed.agent,\n\t\t\t\tsourceScope: root.scope,\n\t\t\t\tsourcePriority: root.priority,\n\t\t\t\teffective: false,\n\t\t\t};\n\t\t\tregisterEntry(entry);\n\t\t}\n\t}\n\n\tconst agents = Array.from(byName.values()).sort((left, right) => left.name.localeCompare(right.name));\n\tallAgents.sort((left, right) => {\n\t\tconst nameCompare = left.name.localeCompare(right.name);\n\t\tif (nameCompare !== 0) return nameCompare;\n\t\treturn right.sourcePriority - left.sourcePriority;\n\t});\n\treturn { agents, allAgents, overrides, diagnostics };\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"planner.d.ts","sourceRoot":"","sources":["../../../src/core/swarm/planner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAE9D,OAAO,KAAK,EAAE,SAAS,EAAiB,MAAM,YAAY,CAAC;AA8E3D,wBAAgB,sBAAsB,CAAC,KAAK,EAAE;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,YAAY,CAAC;CACpB,GAAG,SAAS,CAwCZ;AAED,wBAAgB,0BAA0B,CAAC,KAAK,EAAE;IACjD,QAAQ,EAAE,sBAAsB,CAAC;IACjC,MAAM,EAAE,cAAc,CAAC;IACvB,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,KAAK,EAAE,YAAY,CAAC;CACpB,GAAG,SAAS,CAkEZ"}
1
+ {"version":3,"file":"planner.d.ts","sourceRoot":"","sources":["../../../src/core/swarm/planner.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAC1D,OAAO,KAAK,EAAE,sBAAsB,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAC7E,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,2BAA2B,CAAC;AAE9D,OAAO,KAAK,EAAE,SAAS,EAAiB,MAAM,YAAY,CAAC;AAyL3D,wBAAgB,sBAAsB,CAAC,KAAK,EAAE;IAC7C,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,mBAAmB,CAAC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