zone-ai-agent 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (301) hide show
  1. package/.gittignore +4 -0
  2. package/README.md +36 -0
  3. package/dist/api/server.js +136 -0
  4. package/dist/api/server.js.map +1 -0
  5. package/dist/apply/applyPatchPlan.js +17 -0
  6. package/dist/apply/applyPatchPlan.js.map +1 -0
  7. package/dist/apply/canApplyDecision.js +26 -0
  8. package/dist/apply/canApplyDecision.js.map +1 -0
  9. package/dist/apply/patchPlan.js +3 -0
  10. package/dist/apply/patchPlan.js.map +1 -0
  11. package/dist/apply/renderApplyResult.js +18 -0
  12. package/dist/apply/renderApplyResult.js.map +1 -0
  13. package/dist/apply/runApplyFlow.js +40 -0
  14. package/dist/apply/runApplyFlow.js.map +1 -0
  15. package/dist/apply/types.js +3 -0
  16. package/dist/apply/types.js.map +1 -0
  17. package/dist/audit/auditDiffIntelligence.js +3 -0
  18. package/dist/audit/auditDiffIntelligence.js.map +1 -0
  19. package/dist/audit/auditSnapshot.js +87 -0
  20. package/dist/audit/auditSnapshot.js.map +1 -0
  21. package/dist/audit/renderAuditDiff.js +64 -0
  22. package/dist/audit/renderAuditDiff.js.map +1 -0
  23. package/dist/audit/snapshotDiff.js +53 -0
  24. package/dist/audit/snapshotDiff.js.map +1 -0
  25. package/dist/audit/snapshotReader.js +31 -0
  26. package/dist/audit/snapshotReader.js.map +1 -0
  27. package/dist/audit/snapshotWriter.js +59 -0
  28. package/dist/audit/snapshotWriter.js.map +1 -0
  29. package/dist/ci/evaluateCiResult.js +142 -0
  30. package/dist/ci/evaluateCiResult.js.map +1 -0
  31. package/dist/cli/buildGeneratedPatchPlanPreview.js +65 -0
  32. package/dist/cli/buildGeneratedPatchPlanPreview.js.map +1 -0
  33. package/dist/cli/colors.js +28 -0
  34. package/dist/cli/colors.js.map +1 -0
  35. package/dist/cli/diffOutput.js +37 -0
  36. package/dist/cli/diffOutput.js.map +1 -0
  37. package/dist/cli/index.js +850 -0
  38. package/dist/cli/index.js.map +1 -0
  39. package/dist/cli/loadPatchPlan.js +52 -0
  40. package/dist/cli/loadPatchPlan.js.map +1 -0
  41. package/dist/cli/output.js +34 -0
  42. package/dist/cli/output.js.map +1 -0
  43. package/dist/cli/parseCliArgs.js +3 -0
  44. package/dist/cli/parseCliArgs.js.map +1 -0
  45. package/dist/cli/runGeneratedPatchPlanFlow.js +23 -0
  46. package/dist/cli/runGeneratedPatchPlanFlow.js.map +1 -0
  47. package/dist/components/LoginForm.js +64 -0
  48. package/dist/components/LoginForm.js.map +1 -0
  49. package/dist/core/analyzeCodePatterns.js +3 -0
  50. package/dist/core/analyzeCodePatterns.js.map +1 -0
  51. package/dist/core/applyLlmPatches.js +43 -0
  52. package/dist/core/applyLlmPatches.js.map +1 -0
  53. package/dist/core/buildConfidenceBreakdownFromSignals.js +33 -0
  54. package/dist/core/buildConfidenceBreakdownFromSignals.js.map +1 -0
  55. package/dist/core/buildDecisionAuditSnapshot.js +18 -0
  56. package/dist/core/buildDecisionAuditSnapshot.js.map +1 -0
  57. package/dist/core/buildDecisionTrace.js +113 -0
  58. package/dist/core/buildDecisionTrace.js.map +1 -0
  59. package/dist/core/buildFallbackPatchPlan.js +23 -0
  60. package/dist/core/buildFallbackPatchPlan.js.map +1 -0
  61. package/dist/core/buildFallbackPlan.js +25 -0
  62. package/dist/core/buildFallbackPlan.js.map +1 -0
  63. package/dist/core/buildSchemaAwareContext.js +49 -0
  64. package/dist/core/buildSchemaAwareContext.js.map +1 -0
  65. package/dist/core/buildTaskExecutionContext.js +70 -0
  66. package/dist/core/buildTaskExecutionContext.js.map +1 -0
  67. package/dist/core/ciEvaluator.js +83 -0
  68. package/dist/core/ciEvaluator.js.map +1 -0
  69. package/dist/core/computeRiskScore.js +43 -0
  70. package/dist/core/computeRiskScore.js.map +1 -0
  71. package/dist/core/computeRiskScoreDetails.js +106 -0
  72. package/dist/core/computeRiskScoreDetails.js.map +1 -0
  73. package/dist/core/confidenceGate.js +83 -0
  74. package/dist/core/confidenceGate.js.map +1 -0
  75. package/dist/core/decision/buildDecisionExplanation.js +91 -0
  76. package/dist/core/decision/buildDecisionExplanation.js.map +1 -0
  77. package/dist/core/decision/buildDecisionReasonCodes.js +65 -0
  78. package/dist/core/decision/buildDecisionReasonCodes.js.map +1 -0
  79. package/dist/core/decision/buildReasonSummaryLine.js +24 -0
  80. package/dist/core/decision/buildReasonSummaryLine.js.map +1 -0
  81. package/dist/core/decision/buildRecommendation.js +43 -0
  82. package/dist/core/decision/buildRecommendation.js.map +1 -0
  83. package/dist/core/decision/decideExecutionMode.js +125 -0
  84. package/dist/core/decision/decideExecutionMode.js.map +1 -0
  85. package/dist/core/decision/decisionReasonCodeMeta.js +91 -0
  86. package/dist/core/decision/decisionReasonCodeMeta.js.map +1 -0
  87. package/dist/core/decision/renderDecisionSummary.js +115 -0
  88. package/dist/core/decision/renderDecisionSummary.js.map +1 -0
  89. package/dist/core/detectResourceStorage.js +78 -0
  90. package/dist/core/detectResourceStorage.js.map +1 -0
  91. package/dist/core/formatOutput.js +53 -0
  92. package/dist/core/formatOutput.js.map +1 -0
  93. package/dist/core/intentAwareScore.js +35 -0
  94. package/dist/core/intentAwareScore.js.map +1 -0
  95. package/dist/core/loadSavedAgentResult.js +18 -0
  96. package/dist/core/loadSavedAgentResult.js.map +1 -0
  97. package/dist/core/normalizeIssues.js +50 -0
  98. package/dist/core/normalizeIssues.js.map +1 -0
  99. package/dist/core/normalizeSignals.js +40 -0
  100. package/dist/core/normalizeSignals.js.map +1 -0
  101. package/dist/core/output/zoneStageTypes.js +3 -0
  102. package/dist/core/output/zoneStageTypes.js.map +1 -0
  103. package/dist/core/patchRiskAnalyzer.js +50 -0
  104. package/dist/core/patchRiskAnalyzer.js.map +1 -0
  105. package/dist/core/renderRunAgentResult.js +77 -0
  106. package/dist/core/renderRunAgentResult.js.map +1 -0
  107. package/dist/core/result/buildApplyStageResult.js +61 -0
  108. package/dist/core/result/buildApplyStageResult.js.map +1 -0
  109. package/dist/core/result/buildCliViewModel.js +79 -0
  110. package/dist/core/result/buildCliViewModel.js.map +1 -0
  111. package/dist/core/result/buildConversionStageResult.js +62 -0
  112. package/dist/core/result/buildConversionStageResult.js.map +1 -0
  113. package/dist/core/result/buildDecisionStageResult.js +61 -0
  114. package/dist/core/result/buildDecisionStageResult.js.map +1 -0
  115. package/dist/core/result/buildExecutionResult.js +148 -0
  116. package/dist/core/result/buildExecutionResult.js.map +1 -0
  117. package/dist/core/result/buildPreviewStageResult.js +47 -0
  118. package/dist/core/result/buildPreviewStageResult.js.map +1 -0
  119. package/dist/core/result/buildSavedDecisionExplanation.js +52 -0
  120. package/dist/core/result/buildSavedDecisionExplanation.js.map +1 -0
  121. package/dist/core/result/buildSavedRecommendation.js +39 -0
  122. package/dist/core/result/buildSavedRecommendation.js.map +1 -0
  123. package/dist/core/result/buildStageResultV2.js +52 -0
  124. package/dist/core/result/buildStageResultV2.js.map +1 -0
  125. package/dist/core/result/renderBundledResult.js +47 -0
  126. package/dist/core/result/renderBundledResult.js.map +1 -0
  127. package/dist/core/result/renderCliResult.js +93 -0
  128. package/dist/core/result/renderCliResult.js.map +1 -0
  129. package/dist/core/result/scoreTopRisks.js +205 -0
  130. package/dist/core/result/scoreTopRisks.js.map +1 -0
  131. package/dist/core/runAgent.js +210 -0
  132. package/dist/core/runAgent.js.map +1 -0
  133. package/dist/core/runFeatureAgent.js +684 -0
  134. package/dist/core/runFeatureAgent.js.map +1 -0
  135. package/dist/core/runLlmPatchFlow.js +522 -0
  136. package/dist/core/runLlmPatchFlow.js.map +1 -0
  137. package/dist/core/saveAgentResult.js +234 -0
  138. package/dist/core/saveAgentResult.js.map +1 -0
  139. package/dist/core/scoring/computeConfidenceBreakdown.js +130 -0
  140. package/dist/core/scoring/computeConfidenceBreakdown.js.map +1 -0
  141. package/dist/core/scoring/computeConfidenceScore.js +37 -0
  142. package/dist/core/scoring/computeConfidenceScore.js.map +1 -0
  143. package/dist/core/scoring/confidenceRules.js +58 -0
  144. package/dist/core/scoring/confidenceRules.js.map +1 -0
  145. package/dist/core/scoring/confidenceScore.js +8 -0
  146. package/dist/core/scoring/confidenceScore.js.map +1 -0
  147. package/dist/core/selectRelevantBlocks.js +58 -0
  148. package/dist/core/selectRelevantBlocks.js.map +1 -0
  149. package/dist/core/selfHealingLoop.js +209 -0
  150. package/dist/core/selfHealingLoop.js.map +1 -0
  151. package/dist/core/taskIntentParser.js +165 -0
  152. package/dist/core/taskIntentParser.js.map +1 -0
  153. package/dist/core/types/agentResult.js +3 -0
  154. package/dist/core/types/agentResult.js.map +1 -0
  155. package/dist/core/types/risk.js +3 -0
  156. package/dist/core/types/risk.js.map +1 -0
  157. package/dist/core/validatePatchAgainstSchema.js +100 -0
  158. package/dist/core/validatePatchAgainstSchema.js.map +1 -0
  159. package/dist/core/validateSuggestedArchitecture.js +24 -0
  160. package/dist/core/validateSuggestedArchitecture.js.map +1 -0
  161. package/dist/engine/buildDecisionExplanation.js +114 -0
  162. package/dist/engine/buildDecisionExplanation.js.map +1 -0
  163. package/dist/engine/contradictionDetector.js +40 -0
  164. package/dist/engine/contradictionDetector.js.map +1 -0
  165. package/dist/engine/decisionEngine.js +19 -0
  166. package/dist/engine/decisionEngine.js.map +1 -0
  167. package/dist/llm/openaiClient.js +19 -0
  168. package/dist/llm/openaiClient.js.map +1 -0
  169. package/dist/llm/planFeature.js +57 -0
  170. package/dist/llm/planFeature.js.map +1 -0
  171. package/dist/llm/planFix.js +3 -0
  172. package/dist/llm/planFix.js.map +1 -0
  173. package/dist/llm/planFullPatch.js +62 -0
  174. package/dist/llm/planFullPatch.js.map +1 -0
  175. package/dist/llm/planPatchPreview.js +60 -0
  176. package/dist/llm/planPatchPreview.js.map +1 -0
  177. package/dist/llm/prompts.js +131 -0
  178. package/dist/llm/prompts.js.map +1 -0
  179. package/dist/llm/schemas.js +28 -0
  180. package/dist/llm/schemas.js.map +1 -0
  181. package/dist/patch/apply/formatApplyFlowResult.js +23 -0
  182. package/dist/patch/apply/formatApplyFlowResult.js.map +1 -0
  183. package/dist/patch/apply/renderApplyFlowResult.js +15 -0
  184. package/dist/patch/apply/renderApplyFlowResult.js.map +1 -0
  185. package/dist/patch/apply/runApplyFlow.js +88 -0
  186. package/dist/patch/apply/runApplyFlow.js.map +1 -0
  187. package/dist/patch/applyFlowTypes.js +3 -0
  188. package/dist/patch/applyFlowTypes.js.map +1 -0
  189. package/dist/patch/applyPatchPlan.js +117 -0
  190. package/dist/patch/applyPatchPlan.js.map +1 -0
  191. package/dist/patch/backupFile.js +23 -0
  192. package/dist/patch/backupFile.js.map +1 -0
  193. package/dist/patch/conversion/canConvertGeneratedPlanToPatchPlan.js +57 -0
  194. package/dist/patch/conversion/canConvertGeneratedPlanToPatchPlan.js.map +1 -0
  195. package/dist/patch/conversion/convertGeneratedPlanToPatchPlan.js +38 -0
  196. package/dist/patch/conversion/convertGeneratedPlanToPatchPlan.js.map +1 -0
  197. package/dist/patch/conversion/formatGeneratedPlanConversionFailure.js +17 -0
  198. package/dist/patch/conversion/formatGeneratedPlanConversionFailure.js.map +1 -0
  199. package/dist/patch/conversion/generatedPlanConversionFailureMeta.js +40 -0
  200. package/dist/patch/conversion/generatedPlanConversionFailureMeta.js.map +1 -0
  201. package/dist/patch/conversion/generatedPlanConversionTypes.js +3 -0
  202. package/dist/patch/conversion/generatedPlanConversionTypes.js.map +1 -0
  203. package/dist/patch/conversion/renderGeneratedPlanConversionFailure.js +16 -0
  204. package/dist/patch/conversion/renderGeneratedPlanConversionFailure.js.map +1 -0
  205. package/dist/patch/generatedPlanConversion.js +96 -0
  206. package/dist/patch/generatedPlanConversion.js.map +1 -0
  207. package/dist/patch/patchAnchors.js +3 -0
  208. package/dist/patch/patchAnchors.js.map +1 -0
  209. package/dist/patch/patchValidationRules.js +116 -0
  210. package/dist/patch/patchValidationRules.js.map +1 -0
  211. package/dist/patch/patchValidationTypes.js +3 -0
  212. package/dist/patch/patchValidationTypes.js.map +1 -0
  213. package/dist/patch/renderApplyFlowResult.js +26 -0
  214. package/dist/patch/renderApplyFlowResult.js.map +1 -0
  215. package/dist/patch/validatePatchPlan.js +148 -0
  216. package/dist/patch/validatePatchPlan.js.map +1 -0
  217. package/dist/patch-generation/buildGeneratedPatchPlan.js +94 -0
  218. package/dist/patch-generation/buildGeneratedPatchPlan.js.map +1 -0
  219. package/dist/patch-generation/buildPatchOperations.js +41 -0
  220. package/dist/patch-generation/buildPatchOperations.js.map +1 -0
  221. package/dist/patch-generation/classifyPatchIntent.js +62 -0
  222. package/dist/patch-generation/classifyPatchIntent.js.map +1 -0
  223. package/dist/patch-generation/formatGeneratedPatchPlanPreview.js +25 -0
  224. package/dist/patch-generation/formatGeneratedPatchPlanPreview.js.map +1 -0
  225. package/dist/patch-generation/generatePatchPlan.js +74 -0
  226. package/dist/patch-generation/generatePatchPlan.js.map +1 -0
  227. package/dist/patch-generation/generatedPatchPlanTypes.js +3 -0
  228. package/dist/patch-generation/generatedPatchPlanTypes.js.map +1 -0
  229. package/dist/patch-generation/isIntentAllowed.js +15 -0
  230. package/dist/patch-generation/isIntentAllowed.js.map +1 -0
  231. package/dist/patch-generation/renderGeneratedPatchPlan.js +62 -0
  232. package/dist/patch-generation/renderGeneratedPatchPlan.js.map +1 -0
  233. package/dist/prompts/developerPrompt.js +213 -0
  234. package/dist/prompts/developerPrompt.js.map +1 -0
  235. package/dist/prompts/fullPatchPrompt.js +82 -0
  236. package/dist/prompts/fullPatchPrompt.js.map +1 -0
  237. package/dist/prompts/patchPreviewPrompt.js +83 -0
  238. package/dist/prompts/patchPreviewPrompt.js.map +1 -0
  239. package/dist/prompts/planFeaturePrompt.js +73 -0
  240. package/dist/prompts/planFeaturePrompt.js.map +1 -0
  241. package/dist/prompts/testEngineerContext.js +184 -0
  242. package/dist/prompts/testEngineerContext.js.map +1 -0
  243. package/dist/prompts/testEngineerPrompt.js +135 -0
  244. package/dist/prompts/testEngineerPrompt.js.map +1 -0
  245. package/dist/repo/analyzeProjectPatterns.js +46 -0
  246. package/dist/repo/analyzeProjectPatterns.js.map +1 -0
  247. package/dist/repo/detectProjectStructure.js +45 -0
  248. package/dist/repo/detectProjectStructure.js.map +1 -0
  249. package/dist/repo/getGitChangedFiles.js +96 -0
  250. package/dist/repo/getGitChangedFiles.js.map +1 -0
  251. package/dist/repo/loadSchemaSnapshot.js +29 -0
  252. package/dist/repo/loadSchemaSnapshot.js.map +1 -0
  253. package/dist/repo/rankRelevantFiles.js +306 -0
  254. package/dist/repo/rankRelevantFiles.js.map +1 -0
  255. package/dist/repo/readProjectFiles.js +27 -0
  256. package/dist/repo/readProjectFiles.js.map +1 -0
  257. package/dist/repo/scanRepo.js +93 -0
  258. package/dist/repo/scanRepo.js.map +1 -0
  259. package/dist/repo/validateSuggestedFiles.js +66 -0
  260. package/dist/repo/validateSuggestedFiles.js.map +1 -0
  261. package/dist/roles/dataAnalystContext.js +155 -0
  262. package/dist/roles/dataAnalystContext.js.map +1 -0
  263. package/dist/roles/detectDataSchema.js +152 -0
  264. package/dist/roles/detectDataSchema.js.map +1 -0
  265. package/dist/roles/detectTestComplexity.js +74 -0
  266. package/dist/roles/detectTestComplexity.js.map +1 -0
  267. package/dist/roles/detectTestFramework.js +166 -0
  268. package/dist/roles/detectTestFramework.js.map +1 -0
  269. package/dist/roles/runDataAnalystFlow.js +221 -0
  270. package/dist/roles/runDataAnalystFlow.js.map +1 -0
  271. package/dist/roles/runTestEngineerFlow.js +266 -0
  272. package/dist/roles/runTestEngineerFlow.js.map +1 -0
  273. package/dist/roles/testEngineerContext.js +282 -0
  274. package/dist/roles/testEngineerContext.js.map +1 -0
  275. package/dist/roles/testOutputValidator.js +474 -0
  276. package/dist/roles/testOutputValidator.js.map +1 -0
  277. package/dist/types/agent.js +3 -0
  278. package/dist/types/agent.js.map +1 -0
  279. package/dist/types/analysis.js +3 -0
  280. package/dist/types/analysis.js.map +1 -0
  281. package/dist/types/patch.js +3 -0
  282. package/dist/types/patch.js.map +1 -0
  283. package/dist/types/project.js +3 -0
  284. package/dist/types/project.js.map +1 -0
  285. package/dist/types/schema.js +3 -0
  286. package/dist/types/schema.js.map +1 -0
  287. package/dist/utils/executionTracker.js +33 -0
  288. package/dist/utils/executionTracker.js.map +1 -0
  289. package/dist/utils/files.js +35 -0
  290. package/dist/utils/files.js.map +1 -0
  291. package/dist/utils/logger.js +179 -0
  292. package/dist/utils/logger.js.map +1 -0
  293. package/dist/utils/paths.js +14 -0
  294. package/dist/utils/paths.js.map +1 -0
  295. package/dist/utils/trace.js +10 -0
  296. package/dist/utils/trace.js.map +1 -0
  297. package/dist/utils/validation.js +24 -0
  298. package/dist/utils/validation.js.map +1 -0
  299. package/package.json +53 -0
  300. package/tsconfig.json +17 -0
  301. package/vitest.config.ts +21 -0
@@ -0,0 +1,850 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ var __importDefault = (this && this.__importDefault) || function (mod) {
4
+ return (mod && mod.__esModule) ? mod : { "default": mod };
5
+ };
6
+ Object.defineProperty(exports, "__esModule", { value: true });
7
+ exports.resolveAuditFlag = resolveAuditFlag;
8
+ exports.runCliWithOptions = runCliWithOptions;
9
+ exports.run = run;
10
+ const commander_1 = require("commander");
11
+ const node_path_1 = __importDefault(require("node:path"));
12
+ const node_process_1 = __importDefault(require("node:process"));
13
+ const node_fs_1 = require("node:fs");
14
+ const node_child_process_1 = require("node:child_process");
15
+ const node_util_1 = require("node:util");
16
+ const classifyPatchIntent_js_1 = require("../patch-generation/classifyPatchIntent.js");
17
+ const runLlmPatchFlow_js_1 = require("../core/runLlmPatchFlow.js");
18
+ const executionTracker_js_1 = require("../utils/executionTracker.js");
19
+ const trace_js_1 = require("../utils/trace.js");
20
+ const runFeatureAgent_js_1 = require("../core/runFeatureAgent.js");
21
+ const runAgent_js_1 = require("../core/runAgent.js");
22
+ const loadSavedAgentResult_js_1 = require("../core/loadSavedAgentResult.js");
23
+ const evaluateCiResult_js_1 = require("../ci/evaluateCiResult.js");
24
+ const buildCliViewModel_js_1 = require("../core/result/buildCliViewModel.js");
25
+ const renderCliResult_js_1 = require("../core/result/renderCliResult.js");
26
+ const formatOutput_js_1 = require("../core/formatOutput.js");
27
+ const decisionEngine_js_1 = require("../engine/decisionEngine.js");
28
+ const auditSnapshot_js_1 = require("../audit/auditSnapshot.js");
29
+ const colors_js_1 = require("./colors.js");
30
+ const diffOutput_js_1 = require("./diffOutput.js");
31
+ const output_js_1 = require("./output.js");
32
+ const snapshotWriter_js_1 = require("../audit/snapshotWriter.js");
33
+ const snapshotReader_js_1 = require("../audit/snapshotReader.js");
34
+ const snapshotDiff_js_1 = require("../audit/snapshotDiff.js");
35
+ const renderAuditDiff_js_1 = require("../audit/renderAuditDiff.js");
36
+ const loadPatchPlan_js_1 = require("./loadPatchPlan.js");
37
+ const runApplyFlow_js_1 = require("../apply/runApplyFlow.js");
38
+ const renderApplyResult_js_1 = require("../apply/renderApplyResult.js");
39
+ const buildGeneratedPatchPlanPreview_js_1 = require("./buildGeneratedPatchPlanPreview.js");
40
+ const applyLlmPatches_js_1 = require("../core/applyLlmPatches.js");
41
+ const buildGeneratedPatchPlan_js_1 = require("../patch-generation/buildGeneratedPatchPlan.js");
42
+ require("dotenv/config");
43
+ const canConvertGeneratedPlanToPatchPlan_js_1 = require("../patch/conversion/canConvertGeneratedPlanToPatchPlan.js");
44
+ const convertGeneratedPlanToPatchPlan_js_1 = require("../patch/conversion/convertGeneratedPlanToPatchPlan.js");
45
+ const runTestEngineerFlow_js_1 = require("../roles/runTestEngineerFlow.js");
46
+ const runDataAnalystFlow_js_1 = require("../roles/runDataAnalystFlow.js");
47
+ const confidenceGate_js_1 = require("../core/confidenceGate.js");
48
+ const execFileAsync = (0, node_util_1.promisify)(node_child_process_1.execFile);
49
+ const ANSI_ENABLED = node_process_1.default.env.VITEST !== "true" && node_process_1.default.env.NO_COLOR !== "1";
50
+ // ---------------------------------------------------------------------------
51
+ // Audit helpers
52
+ // ---------------------------------------------------------------------------
53
+ function resolveAuditFlag(argv) {
54
+ return argv.includes("--audit");
55
+ }
56
+ function mapSavedModeToExecutionMode(mode) {
57
+ switch (mode) {
58
+ case "apply":
59
+ return "safe_to_apply";
60
+ case "preview":
61
+ return "preview_only";
62
+ case "blocked":
63
+ return "blocked";
64
+ }
65
+ }
66
+ function resolveAuditReplayPath(options) {
67
+ const value = options.auditReplay?.trim();
68
+ return value ? value : null;
69
+ }
70
+ function resolveAuditDiffPaths(options) {
71
+ const raw = options.auditDiff?.trim();
72
+ if (!raw) {
73
+ return null;
74
+ }
75
+ const [leftPath, rightPath] = raw.split(",").map((part) => part.trim());
76
+ if (!leftPath || !rightPath) {
77
+ return null;
78
+ }
79
+ return { leftPath, rightPath };
80
+ }
81
+ function resolvePatchPlanPath(options) {
82
+ const value = options.patchPlan?.trim();
83
+ return value ? node_path_1.default.resolve(value) : null;
84
+ }
85
+ function runAuditReplayFlow(filePath) {
86
+ const snapshot = (0, snapshotReader_js_1.readAuditSnapshot)(filePath);
87
+ if (!snapshot) {
88
+ return 0;
89
+ }
90
+ (0, output_js_1.printAuditSnapshot)(snapshot);
91
+ return 0;
92
+ }
93
+ function runAuditDiffFlow(leftPath, rightPath) {
94
+ const leftSnapshot = (0, snapshotReader_js_1.readAuditSnapshot)(leftPath);
95
+ const rightSnapshot = (0, snapshotReader_js_1.readAuditSnapshot)(rightPath);
96
+ if (!leftSnapshot || !rightSnapshot) {
97
+ return 0;
98
+ }
99
+ const diff = (0, snapshotDiff_js_1.diffAuditSnapshots)(leftSnapshot, rightSnapshot);
100
+ console.log((0, renderAuditDiff_js_1.renderAuditDiff)(diff));
101
+ return 0;
102
+ }
103
+ const DEFAULT_RESULT_PATH = node_path_1.default.join(".agent-cache", "last-result.json");
104
+ function formatErrorMessage(error) {
105
+ if (error instanceof Error && error.message) {
106
+ return error.message;
107
+ }
108
+ return String(error);
109
+ }
110
+ async function ensureParentDir(filePath) {
111
+ const dir = node_path_1.default.dirname(filePath);
112
+ await node_fs_1.promises.mkdir(dir, { recursive: true });
113
+ }
114
+ async function writeJsonFile(filePath, data) {
115
+ await ensureParentDir(filePath);
116
+ await node_fs_1.promises.writeFile(filePath, JSON.stringify(data, null, 2), "utf8");
117
+ }
118
+ function tone(text, ...codes) {
119
+ return ANSI_ENABLED ? (0, colors_js_1.colorize)(text, ...codes) : text;
120
+ }
121
+ function zonePrefix() {
122
+ return tone("[zone]", colors_js_1.c.bold, colors_js_1.c.cyan);
123
+ }
124
+ function colorConfidence(score) {
125
+ if (!ANSI_ENABLED)
126
+ return String(score);
127
+ if (score >= 70)
128
+ return tone(String(score), colors_js_1.c.bold, colors_js_1.c.green);
129
+ if (score >= 50)
130
+ return tone(String(score), colors_js_1.c.bold, colors_js_1.c.yellow);
131
+ return tone(String(score), colors_js_1.c.bold, colors_js_1.c.red);
132
+ }
133
+ function colorLabel(label, color, symbol) {
134
+ if (!ANSI_ENABLED)
135
+ return label;
136
+ const prefix = symbol ? `${symbol} ` : "";
137
+ return `${tone(prefix, colors_js_1.c.bold, color)}${tone(label, colors_js_1.c.bold, color)}`;
138
+ }
139
+ function formatApplyLog(kind, values) {
140
+ const colors = {
141
+ Applied: colors_js_1.c.green,
142
+ Failed: colors_js_1.c.red,
143
+ Skipped: colors_js_1.c.gray,
144
+ };
145
+ const symbols = {
146
+ Applied: "✓",
147
+ Failed: "✗",
148
+ Skipped: "•",
149
+ };
150
+ return `${zonePrefix()} ${colorLabel(`${kind}:`, colors[kind], symbols[kind])} ${values.join(", ") || "none"}`;
151
+ }
152
+ function printHeader() {
153
+ console.log(tone("⚡ Zone", colors_js_1.c.bold, colors_js_1.c.orange) + tone(" v0.1.0", colors_js_1.c.dim, colors_js_1.c.gray));
154
+ console.log(tone("AI Code Agent — deterministic, explainable, safe", colors_js_1.c.dim, colors_js_1.c.gray));
155
+ }
156
+ function printStatusLine(statusLine) {
157
+ console.log(statusLine);
158
+ }
159
+ function printSummaryLine(summaryLine) {
160
+ console.log(summaryLine);
161
+ }
162
+ function printVerbose(label, value, enabled) {
163
+ if (!enabled) {
164
+ return;
165
+ }
166
+ const serialized = typeof value === "string" ? value : JSON.stringify(value, null, 2);
167
+ console.log(`\n${tone("[verbose]", colors_js_1.c.dim, colors_js_1.c.gray)} ${label}`);
168
+ console.log(serialized);
169
+ }
170
+ function resolveTask(options) {
171
+ const task = options.task?.trim();
172
+ if (!task) {
173
+ throw new Error("Missing required --task value. Use --task for agent runs, or use --audit-replay / --audit-diff for audit operations.");
174
+ }
175
+ return task;
176
+ }
177
+ function resolveRepoPath(options) {
178
+ if (options.repo?.trim()) {
179
+ return node_path_1.default.resolve(options.repo);
180
+ }
181
+ return node_process_1.default.cwd();
182
+ }
183
+ function resolveResultPath(options) {
184
+ if (options.output?.trim()) {
185
+ return node_path_1.default.resolve(options.output);
186
+ }
187
+ return node_path_1.default.resolve(DEFAULT_RESULT_PATH);
188
+ }
189
+ function resolveMode(options) {
190
+ return options.mode ?? "preview";
191
+ }
192
+ function resolveFormat(options) {
193
+ switch (options.format) {
194
+ case "summary":
195
+ case "detailed":
196
+ case "json":
197
+ return options.format;
198
+ default:
199
+ return "summary";
200
+ }
201
+ }
202
+ function resolveOutputFormat(rawFormat) {
203
+ if (!rawFormat || rawFormat === "text")
204
+ return "text";
205
+ if (rawFormat === "json")
206
+ return "json";
207
+ throw new Error(`Invalid --format value: "${rawFormat}". Valid values for task-only mode are: text, json`);
208
+ }
209
+ async function getChangedFiles(repoPath) {
210
+ try {
211
+ const baseSha = node_process_1.default.env.SMILE_AGENT_BASE_SHA?.trim();
212
+ const headSha = node_process_1.default.env.SMILE_AGENT_HEAD_SHA?.trim() || "HEAD";
213
+ const args = baseSha
214
+ ? ["diff", "--name-only", `${baseSha}...${headSha}`]
215
+ : ["status", "--short"];
216
+ const { stdout } = await execFileAsync("git", args, {
217
+ cwd: repoPath,
218
+ windowsHide: true,
219
+ });
220
+ const lines = stdout
221
+ .split(/\r?\n/)
222
+ .map((line) => line.trim())
223
+ .filter(Boolean);
224
+ if (baseSha) {
225
+ return lines.map((line) => line.replace(/\\/g, "/"));
226
+ }
227
+ return lines
228
+ .map((line) => {
229
+ const normalized = line.replace(/\\/g, "/");
230
+ return normalized.length > 3 ? normalized.slice(3).trim() : normalized;
231
+ })
232
+ .filter(Boolean);
233
+ }
234
+ catch {
235
+ return [];
236
+ }
237
+ }
238
+ function buildErrorResult(task, repoPath, message) {
239
+ return {
240
+ version: 2,
241
+ generatedAt: new Date().toISOString(),
242
+ summary: `Run failed: ${message}`,
243
+ statusLine: "STATUS: BLOCKED | confidence=0 | warnings=1 | penalties=1 | patches=0 | relevant=0 | suggested=0",
244
+ meta: {
245
+ task,
246
+ targetPath: repoPath,
247
+ relevantFileCount: 0,
248
+ suggestedFileCount: 0,
249
+ patchCount: 0,
250
+ },
251
+ intent: {
252
+ rawTask: task,
253
+ operation: "unknown",
254
+ target: "unknown",
255
+ scope: "unknown",
256
+ nestedTarget: null,
257
+ confidence: "low",
258
+ warnings: ["Runtime failure prevented normal execution."],
259
+ },
260
+ schema: {
261
+ summary: "Schema analysis unavailable due to runtime failure.",
262
+ entities: [],
263
+ relations: [],
264
+ confidence: "low",
265
+ },
266
+ storage: {
267
+ primaryStorage: "unknown",
268
+ detectedClients: [],
269
+ confidence: "low",
270
+ reasoning: ["Runtime failure prevented storage analysis."],
271
+ resourceStorageKind: "unknown",
272
+ },
273
+ validation: {
274
+ patch: [],
275
+ schema: [],
276
+ },
277
+ issues: {
278
+ summary: {
279
+ total: 1,
280
+ errors: 1,
281
+ warnings: 0,
282
+ },
283
+ grouped: [
284
+ {
285
+ key: "runtime",
286
+ label: "Runtime failure",
287
+ total: 1,
288
+ errors: 1,
289
+ warnings: 0,
290
+ issues: [
291
+ {
292
+ code: "RUNTIME_FAILURE",
293
+ severity: "error",
294
+ message,
295
+ },
296
+ ],
297
+ },
298
+ ],
299
+ topRisks: [
300
+ {
301
+ id: "issue:runtime_failure",
302
+ title: "Runtime failure",
303
+ description: message,
304
+ severity: "high",
305
+ score: 100,
306
+ category: "validation",
307
+ source: "derived",
308
+ relatedCode: "RUNTIME_FAILURE",
309
+ },
310
+ ],
311
+ },
312
+ decision: {
313
+ mode: "blocked",
314
+ confidence: 0,
315
+ reason: message,
316
+ recommendation: "Do not apply automatically. Resolve the runtime failure first.",
317
+ },
318
+ confidenceBreakdown: {
319
+ finalScore: 0,
320
+ level: "low",
321
+ factors: {
322
+ intentClarity: 0,
323
+ schemaCertainty: 0,
324
+ storageCertainty: 0,
325
+ patchValidationHealth: 0,
326
+ },
327
+ },
328
+ confidenceDetails: {
329
+ baseWeightedScore: 0,
330
+ totalPenalty: 100,
331
+ penalties: [
332
+ {
333
+ code: "RUNTIME_FAILURE",
334
+ label: "Runtime failure",
335
+ appliedPenalty: 100,
336
+ },
337
+ ],
338
+ },
339
+ notes: {
340
+ execution: [message],
341
+ assumptions: [],
342
+ followUps: ["Fix the runtime failure and rerun the agent."],
343
+ },
344
+ debug: {
345
+ patchTargets: [],
346
+ suggestedFiles: [],
347
+ },
348
+ };
349
+ }
350
+ async function runTaskOnlyFlow(options) {
351
+ const { task, verbose, showTrace, traceId, tracker, outputFormat, audit, auditOut, apply, confirmApply, diff, patchPlanPath, useGeneratedPatchPlan, repoPath, role, } = options;
352
+ tracker.startPhase("run_agent");
353
+ const result = await (0, runAgent_js_1.runAgent)({ task, role });
354
+ tracker.endPhase("run_agent");
355
+ tracker.endPhase("total");
356
+ printVerbose("runAgent.result", result, verbose);
357
+ const renderedDecisionOutput = (0, formatOutput_js_1.formatOutput)(result, outputFormat, {
358
+ showTrace,
359
+ verbose,
360
+ });
361
+ const generatedPlan = (0, buildGeneratedPatchPlan_js_1.buildGeneratedPatchPlan)({
362
+ task: result.task,
363
+ decision: result.decision,
364
+ reasonCodes: result.reasonCodes,
365
+ });
366
+ const generatedPatchPlanPreview = (0, buildGeneratedPatchPlanPreview_js_1.buildGeneratedPatchPlanPreview)({
367
+ task: result.task,
368
+ decision: result.decision,
369
+ reasonCodes: result.reasonCodes,
370
+ });
371
+ // Confidence gate check
372
+ const gateResult = (0, confidenceGate_js_1.checkConfidenceGate)({
373
+ confidenceScore: result.decision.confidenceScore,
374
+ role: role,
375
+ warnings: result.topRisks?.map(r => r.reason) ?? [],
376
+ });
377
+ if (!gateResult.pass && apply && confirmApply) {
378
+ console.log("");
379
+ console.log((0, confidenceGate_js_1.renderConfidenceGateBlock)(gateResult));
380
+ console.log("");
381
+ console.log(`${zonePrefix()} ${tone("Apply blocked by confidence gate. Use --verbose to see details.", colors_js_1.c.yellow)}`);
382
+ return 1;
383
+ }
384
+ if (!gateResult.pass) {
385
+ console.log("");
386
+ console.log((0, confidenceGate_js_1.renderConfidenceGateBlock)(gateResult));
387
+ console.log(`${zonePrefix()} ${tone("Proceeding in preview mode only.", colors_js_1.c.yellow)}`);
388
+ console.log("");
389
+ }
390
+ const intent = (0, classifyPatchIntent_js_1.classifyPatchIntent)(task);
391
+ let patchSection = generatedPatchPlanPreview;
392
+ if (intent === "unknown" && repoPath) {
393
+ if (role === "data_analyst") {
394
+ console.log(`${zonePrefix()} ${tone("Data Analyst role — delegating to data analyst flow...", colors_js_1.c.white)}`);
395
+ const daResult = await (0, runDataAnalystFlow_js_1.runDataAnalystFlow)({ task, repoPath });
396
+ if (!daResult.ok) {
397
+ console.error(`[zone] Data analyst flow failed: ${daResult.reason}`);
398
+ return 1;
399
+ }
400
+ console.log(`${zonePrefix()} Dialect detected: ${tone(daResult.dialect, colors_js_1.c.blue)} (${tone(daResult.migrationFormat, colors_js_1.c.blue)})`);
401
+ console.log(`${zonePrefix()} Confidence: ${colorConfidence(daResult.confidence)}`);
402
+ console.log(daResult.preview);
403
+ if (apply && confirmApply && daResult.applyPatches.length > 0) {
404
+ const originalContents = await capturePatchOriginals(repoPath, daResult.applyPatches);
405
+ console.log(`${zonePrefix()} ${tone("Applying migration files...", colors_js_1.c.white)}`);
406
+ const applyResult = await (0, applyLlmPatches_js_1.applyLlmPatches)(daResult.applyPatches, repoPath);
407
+ console.log(formatApplyLog("Applied", applyResult.applied));
408
+ console.log(formatApplyLog("Failed", applyResult.failed));
409
+ if (diff && applyResult.applied.length > 0) {
410
+ (0, diffOutput_js_1.renderDiffSummary)(applyResult.applied.map((filePath) => {
411
+ const patch = daResult.applyPatches.find((p) => p.filePath === filePath);
412
+ return {
413
+ filePath,
414
+ original: originalContents[filePath] ?? "",
415
+ updated: patch?.fullContent ?? "",
416
+ };
417
+ }));
418
+ }
419
+ }
420
+ return 0;
421
+ }
422
+ if (role === "test_engineer") {
423
+ console.log(`${zonePrefix()} ${tone("Test Engineer role — delegating to test engineer flow...", colors_js_1.c.white)}`);
424
+ const teResult = await (0, runTestEngineerFlow_js_1.runTestEngineerFlow)({ task, repoPath });
425
+ if (!teResult.ok) {
426
+ console.error(`[zone] Test engineer flow failed: ${teResult.reason}`);
427
+ if (teResult.framework === "unknown") {
428
+ console.error("[zone] No test framework detected in this repository.");
429
+ console.error("[zone] Supported: playwright-ts, playwright-js, cypress, cucumber-java, selenium-java, testng, pytest");
430
+ }
431
+ return 1;
432
+ }
433
+ console.log(`${zonePrefix()} Framework detected: ${tone(teResult.framework, colors_js_1.c.blue)} (${tone(teResult.language, colors_js_1.c.blue)})`);
434
+ console.log(`${zonePrefix()} Confidence: ${colorConfidence(teResult.confidence)}`);
435
+ if (teResult.complexity && teResult.complexity !== 'simple') {
436
+ const complexityLabels = {
437
+ data_driven: 'Data Driven',
438
+ e2e: 'E2E',
439
+ negative: 'Negative',
440
+ multi_scenario: 'Multi Scenario',
441
+ };
442
+ const label = complexityLabels[teResult.complexity] || teResult.complexity;
443
+ console.log(`${zonePrefix()} Complexity: ${tone(label, colors_js_1.c.cyan)}`);
444
+ }
445
+ console.log(teResult.preview);
446
+ if (apply && confirmApply && teResult.applyPatches.length > 0) {
447
+ const originalContents = await capturePatchOriginals(repoPath, teResult.applyPatches);
448
+ console.log(`${zonePrefix()} ${tone("Applying test files...", colors_js_1.c.white)}`);
449
+ const applyResult = await (0, applyLlmPatches_js_1.applyLlmPatches)(teResult.applyPatches, repoPath);
450
+ console.log(formatApplyLog("Applied", applyResult.applied));
451
+ console.log(formatApplyLog("Failed", applyResult.failed));
452
+ if (diff && applyResult.applied.length > 0) {
453
+ (0, diffOutput_js_1.renderDiffSummary)(applyResult.applied.map((filePath) => {
454
+ const patch = teResult.applyPatches.find((p) => p.filePath === filePath);
455
+ return {
456
+ filePath,
457
+ original: originalContents[filePath] ?? "",
458
+ updated: patch?.fullContent ?? "",
459
+ };
460
+ }));
461
+ }
462
+ }
463
+ return 0;
464
+ }
465
+ console.log(`${zonePrefix()} ${tone("Intent unknown — delegating to LLM patch flow...", colors_js_1.c.white)}`);
466
+ const llmResult = await (0, runLlmPatchFlow_js_1.runLlmPatchFlow)({ task, repoPath });
467
+ if (llmResult.ok) {
468
+ patchSection = llmResult.patchPreview;
469
+ if (apply && confirmApply && llmResult.applyPatches.length > 0) {
470
+ const originalContents = llmResult.originalContents ??
471
+ (await capturePatchOriginals(repoPath, llmResult.applyPatches));
472
+ console.log(`${zonePrefix()} ${tone("Applying LLM patches...", colors_js_1.c.white)}`);
473
+ const applyResult = await (0, applyLlmPatches_js_1.applyLlmPatches)(llmResult.applyPatches, repoPath);
474
+ console.log(formatApplyLog("Applied", applyResult.applied));
475
+ console.log(formatApplyLog("Skipped", applyResult.skipped));
476
+ console.log(formatApplyLog("Failed", applyResult.failed));
477
+ if (diff && applyResult.applied.length > 0) {
478
+ (0, diffOutput_js_1.renderDiffSummary)(applyResult.applied.map((filePath) => {
479
+ const patch = llmResult.applyPatches.find((p) => p.filePath === filePath);
480
+ return {
481
+ filePath,
482
+ original: originalContents[filePath] ?? "",
483
+ updated: patch?.fullContent ?? "",
484
+ };
485
+ }));
486
+ }
487
+ }
488
+ }
489
+ else {
490
+ patchSection = generatedPatchPlanPreview + "\n\n[zone] LLM patch flow failed: " + llmResult.reason;
491
+ }
492
+ }
493
+ const finalOutput = [
494
+ renderedDecisionOutput,
495
+ "",
496
+ patchSection,
497
+ ].join("\n");
498
+ console.log("");
499
+ console.log(finalOutput);
500
+ console.log("");
501
+ if (apply) {
502
+ console.log("=== APPLY RESULT ===");
503
+ if (!confirmApply) {
504
+ console.log("Status: skipped\nReason: Apply requested but not confirmed. Re-run with --confirm-apply.");
505
+ console.log("");
506
+ printVerbose("execution", {
507
+ traceId,
508
+ ...tracker.build(),
509
+ }, verbose);
510
+ return 0;
511
+ }
512
+ let patchPlan;
513
+ if (useGeneratedPatchPlan) {
514
+ tracker.startPhase("validate_generated_patch_plan");
515
+ const conversionCheck = (0, canConvertGeneratedPlanToPatchPlan_js_1.canConvertGeneratedPlanToPatchPlan)(generatedPlan);
516
+ tracker.endPhase("validate_generated_patch_plan");
517
+ if (!conversionCheck.canConvert) {
518
+ console.log("Status: blocked");
519
+ console.log("Reason: Generated patch plan conversion failed.");
520
+ console.log(`Code: ${conversionCheck.code}`);
521
+ console.log(`Details: ${conversionCheck.reason}`);
522
+ console.log("");
523
+ printVerbose("generatedPlan", generatedPlan, verbose);
524
+ printVerbose("generatedPlan.conversionCheck", conversionCheck, verbose);
525
+ printVerbose("execution", {
526
+ traceId,
527
+ ...tracker.build(),
528
+ }, verbose);
529
+ return 1;
530
+ }
531
+ tracker.startPhase("convert_generated_patch_plan");
532
+ patchPlan = (0, convertGeneratedPlanToPatchPlan_js_1.convertGeneratedPlanToPatchPlan)(generatedPlan);
533
+ tracker.endPhase("convert_generated_patch_plan");
534
+ printVerbose("generatedPlan", generatedPlan, verbose);
535
+ printVerbose("generatedPlan.patchPlan", patchPlan, verbose);
536
+ }
537
+ else {
538
+ if (!patchPlanPath) {
539
+ throw new Error("Apply requested but no patch plan was provided. Use --patch-plan <file>.");
540
+ }
541
+ tracker.startPhase("load_patch_plan");
542
+ patchPlan = (0, loadPatchPlan_js_1.loadPatchPlan)(patchPlanPath);
543
+ tracker.endPhase("load_patch_plan");
544
+ }
545
+ const patchEntries = Array.isArray(patchPlan.patches)
546
+ ? (patchPlan.patches)
547
+ : [];
548
+ const originalContents = diff && patchEntries.length > 0
549
+ ? await capturePatchOriginals(repoPath, patchEntries.map((patch) => ({ filePath: patch.filePath })))
550
+ : {};
551
+ tracker.startPhase("run_apply_flow");
552
+ const applyResult = await (0, runApplyFlow_js_1.runApplyFlow)({
553
+ result,
554
+ plan: patchPlan,
555
+ request: {
556
+ confirm: true,
557
+ },
558
+ });
559
+ tracker.endPhase("run_apply_flow");
560
+ console.log((0, renderApplyResult_js_1.renderApplyResult)(applyResult));
561
+ console.log("");
562
+ if (diff && applyResult.applied && patchEntries.length > 0) {
563
+ (0, diffOutput_js_1.renderDiffSummary)(patchEntries.map((patch) => ({
564
+ filePath: patch.filePath,
565
+ original: originalContents[patch.filePath] ?? "",
566
+ updated: patch.nextContent,
567
+ })));
568
+ }
569
+ printVerbose("applyResult", applyResult, verbose);
570
+ printVerbose("execution", {
571
+ traceId,
572
+ ...tracker.build(),
573
+ }, verbose);
574
+ if (audit || auditOut) {
575
+ try {
576
+ const engineInput = {
577
+ riskScore: result.risk.score / 100,
578
+ confidenceScore: result.decision.confidenceScore / 100,
579
+ mode: result.decision.mode,
580
+ };
581
+ const engineResult = (0, decisionEngine_js_1.runDecisionEngine)(engineInput);
582
+ const snapshot = (0, auditSnapshot_js_1.buildAuditSnapshot)(engineInput, engineResult, {
583
+ reasonCodes: result.reasonCodes,
584
+ });
585
+ if (audit) {
586
+ (0, output_js_1.printAuditSnapshot)(snapshot);
587
+ }
588
+ if (auditOut) {
589
+ (0, snapshotWriter_js_1.writeAuditSnapshot)(snapshot, auditOut);
590
+ }
591
+ }
592
+ catch {
593
+ // audit errors must never propagate
594
+ }
595
+ }
596
+ return applyResult.applied ? 0 : 1;
597
+ }
598
+ printVerbose("execution", {
599
+ traceId,
600
+ ...tracker.build(),
601
+ }, verbose);
602
+ if (audit || auditOut) {
603
+ try {
604
+ const engineInput = {
605
+ riskScore: result.risk.score / 100,
606
+ confidenceScore: result.decision.confidenceScore / 100,
607
+ mode: result.decision.mode,
608
+ };
609
+ const engineResult = (0, decisionEngine_js_1.runDecisionEngine)(engineInput);
610
+ const snapshot = (0, auditSnapshot_js_1.buildAuditSnapshot)(engineInput, engineResult, {
611
+ reasonCodes: result.reasonCodes,
612
+ });
613
+ if (audit) {
614
+ (0, output_js_1.printAuditSnapshot)(snapshot);
615
+ }
616
+ if (auditOut) {
617
+ (0, snapshotWriter_js_1.writeAuditSnapshot)(snapshot, auditOut);
618
+ }
619
+ }
620
+ catch {
621
+ // audit errors must never propagate
622
+ }
623
+ }
624
+ return 0;
625
+ }
626
+ async function runCliWithOptions(options) {
627
+ const tracker = new executionTracker_js_1.ExecutionTracker();
628
+ const traceId = (0, trace_js_1.generateTraceId)();
629
+ tracker.startPhase("total");
630
+ const verbose = Boolean(options.verbose);
631
+ const auditReplayPath = resolveAuditReplayPath(options);
632
+ const auditDiffPaths = resolveAuditDiffPaths(options);
633
+ if (auditReplayPath) {
634
+ printVerbose("cli.options", options, verbose);
635
+ return runAuditReplayFlow(auditReplayPath);
636
+ }
637
+ if (options.auditDiff && !auditDiffPaths) {
638
+ console.error('[audit] Failed to diff snapshots: expected --audit-diff="<left.json,right.json>"');
639
+ return 0;
640
+ }
641
+ if (auditDiffPaths) {
642
+ printVerbose("cli.options", options, verbose);
643
+ return runAuditDiffFlow(auditDiffPaths.leftPath, auditDiffPaths.rightPath);
644
+ }
645
+ const task = resolveTask(options);
646
+ const repoPath = resolveRepoPath(options);
647
+ const resultPath = resolveResultPath(options);
648
+ const mode = resolveMode(options);
649
+ const format = resolveFormat(options);
650
+ const ciMode = Boolean(options.ci);
651
+ const showTrace = Boolean(options.trace) || verbose;
652
+ const diffAware = Boolean(options.diffAware);
653
+ const taskOnly = Boolean(options.taskOnly);
654
+ const audit = Boolean(options.audit);
655
+ const auditOut = options.auditOut?.trim() || null;
656
+ printHeader();
657
+ console.log(`Mode: ${ciMode ? "CI" : "standard"}`);
658
+ console.log(`Format: ${format}`);
659
+ console.log(`Flow: ${taskOnly ? "task-only" : "legacy"}`);
660
+ printVerbose("cli.options", options, verbose);
661
+ printVerbose("repoPath", repoPath, verbose);
662
+ printVerbose("resultPath", resultPath, verbose);
663
+ try {
664
+ if (taskOnly) {
665
+ const outputFormat = resolveOutputFormat(options.format);
666
+ return await runTaskOnlyFlow({
667
+ task,
668
+ verbose,
669
+ showTrace,
670
+ traceId,
671
+ tracker,
672
+ outputFormat,
673
+ audit,
674
+ auditOut,
675
+ apply: Boolean(options.apply),
676
+ confirmApply: Boolean(options.confirmApply),
677
+ diff: Boolean(options.diff),
678
+ patchPlanPath: resolvePatchPlanPath(options),
679
+ useGeneratedPatchPlan: Boolean(options.useGeneratedPatchPlan),
680
+ repoPath,
681
+ role: options.role,
682
+ });
683
+ }
684
+ const changedFiles = diffAware ? await getChangedFiles(repoPath) : [];
685
+ if (diffAware) {
686
+ printVerbose("changedFiles", changedFiles, verbose);
687
+ }
688
+ tracker.startPhase("run_agent");
689
+ await (0, runFeatureAgent_js_1.runFeatureAgent)({
690
+ task,
691
+ targetPath: repoPath,
692
+ mode,
693
+ changedFiles,
694
+ });
695
+ tracker.endPhase("run_agent");
696
+ tracker.startPhase("load_result");
697
+ const savedResult = await (0, loadSavedAgentResult_js_1.loadSavedAgentResult)(repoPath);
698
+ tracker.endPhase("load_result");
699
+ if (!savedResult) {
700
+ throw new Error("Saved agent result could not be loaded after execution.");
701
+ }
702
+ tracker.startPhase("build_cli_view");
703
+ const cliView = (0, buildCliViewModel_js_1.buildCliViewModel)(savedResult);
704
+ tracker.endPhase("build_cli_view");
705
+ tracker.endPhase("total");
706
+ savedResult.execution = {
707
+ traceId,
708
+ ...tracker.build(),
709
+ };
710
+ await writeJsonFile(resultPath, savedResult);
711
+ console.log("");
712
+ console.log((0, renderCliResult_js_1.renderCliResult)(cliView, format));
713
+ console.log("");
714
+ console.log(`Result saved: ${resultPath}`);
715
+ if (audit || auditOut) {
716
+ try {
717
+ const engineInput = {
718
+ riskScore: 0,
719
+ confidenceScore: savedResult.decision.confidence / 100,
720
+ mode: mapSavedModeToExecutionMode(savedResult.decision.mode),
721
+ };
722
+ const engineResult = (0, decisionEngine_js_1.runDecisionEngine)(engineInput);
723
+ const snapshot = (0, auditSnapshot_js_1.buildAuditSnapshot)(engineInput, engineResult);
724
+ if (audit) {
725
+ (0, output_js_1.printAuditSnapshot)(snapshot);
726
+ }
727
+ if (auditOut) {
728
+ (0, snapshotWriter_js_1.writeAuditSnapshot)(snapshot, auditOut);
729
+ }
730
+ }
731
+ catch {
732
+ // audit errors must never propagate
733
+ }
734
+ }
735
+ if (ciMode) {
736
+ const ciEvaluation = (0, evaluateCiResult_js_1.evaluateCiResult)(savedResult);
737
+ printStatusLine(ciEvaluation.statusLine);
738
+ printSummaryLine(ciEvaluation.summaryLine);
739
+ if (verbose) {
740
+ printVerbose("ciEvaluation", ciEvaluation, true);
741
+ }
742
+ return ciEvaluation.shouldFail ? 1 : 0;
743
+ }
744
+ return 0;
745
+ }
746
+ catch (error) {
747
+ const message = formatErrorMessage(error);
748
+ tracker.endPhase("total");
749
+ if (taskOnly) {
750
+ console.error("");
751
+ console.error(`Task-only flow failed: ${message}`);
752
+ console.error("");
753
+ printVerbose("execution", {
754
+ traceId,
755
+ ...tracker.build(),
756
+ }, verbose);
757
+ return 1;
758
+ }
759
+ const errorResult = buildErrorResult(task, repoPath, message);
760
+ errorResult.execution = {
761
+ traceId,
762
+ ...tracker.build(),
763
+ };
764
+ await writeJsonFile(resultPath, errorResult);
765
+ if (ciMode) {
766
+ const ciEvaluation = (0, evaluateCiResult_js_1.evaluateCiResult)(errorResult);
767
+ printStatusLine(ciEvaluation.statusLine);
768
+ printSummaryLine(ciEvaluation.summaryLine);
769
+ return 1;
770
+ }
771
+ const cliView = (0, buildCliViewModel_js_1.buildCliViewModel)(errorResult);
772
+ console.error("");
773
+ console.error((0, renderCliResult_js_1.renderCliResult)(cliView, format));
774
+ console.error("");
775
+ console.error(`Result saved: ${resultPath}`);
776
+ return 1;
777
+ }
778
+ }
779
+ async function run() {
780
+ const program = new commander_1.Command();
781
+ let subcommandHandled = false;
782
+ program
783
+ .command("serve")
784
+ .description("Start Zone web UI on localhost")
785
+ .option("--port <port>", "Port to listen on", "3000")
786
+ .option("--open", "Open browser automatically")
787
+ .action(async (options) => {
788
+ subcommandHandled = true;
789
+ const port = Number.parseInt(options.port, 10);
790
+ console.log(tone("⚡ Zone", colors_js_1.c.bold, colors_js_1.c.orange) + tone(" v0.1.0", colors_js_1.c.dim, colors_js_1.c.gray));
791
+ console.log(tone(`Starting web UI on http://localhost:${port}`, colors_js_1.c.cyan));
792
+ node_process_1.default.env.ZONE_SERVER_MANUAL_START = "1";
793
+ const { startServer } = await import("../api/server.js");
794
+ await startServer(port);
795
+ if (options.open) {
796
+ const { exec } = await import("node:child_process");
797
+ exec(`start http://localhost:${port}`);
798
+ }
799
+ });
800
+ program
801
+ .name("zone")
802
+ .description("Zone — AI Code Agent: deterministic, explainable, safe")
803
+ .option("--task <text>", "Task or change request to analyze")
804
+ .option("--repo <path>", "Target repository path", node_process_1.default.cwd())
805
+ .option("--ci", "Enable CI mode")
806
+ .option("--verbose", "Enable verbose logs")
807
+ .option("--trace", "Show decision trace in output")
808
+ .option("--diff-aware", "Boost ranking using git diff context")
809
+ .option("--diff", "Show colored diff of applied changes")
810
+ .option("--task-only", "Run Sprint 7 task-only orchestration flow")
811
+ .option("--apply", "Execute controlled apply flow after decision output")
812
+ .option("--confirm-apply", "Explicit confirmation required before apply")
813
+ .option("--patch-plan <path>", "Path to PatchPlan JSON file")
814
+ .option("--use-generated-patch-plan", "Generate a deterministic patch plan from the decision result and use it for apply if safely convertible")
815
+ .option("--audit", "Print full audit snapshot as JSON to stdout (additive, no side effects)")
816
+ .option("--audit-out <path>", "Write audit snapshot as JSON to a file (additive, independent of --audit)")
817
+ .option("--audit-replay <path>", "Read and print an audit snapshot from disk")
818
+ .option("--audit-diff <paths>", 'Compare two audit snapshots: "<left.json,right.json>"')
819
+ .option("--mode <mode>", "Execution mode: preview | dry-run | apply", "preview")
820
+ .option("--format <mode>", "CLI output format: summary | detailed | json", "summary")
821
+ .option("--output <path>", "Path for structured JSON result output", DEFAULT_RESULT_PATH)
822
+ .option("--role <role>", "Agent role: developer | test_engineer | data_analyst")
823
+ .allowExcessArguments(false);
824
+ await program.parseAsync(node_process_1.default.argv);
825
+ if (subcommandHandled) {
826
+ return;
827
+ }
828
+ const options = program.opts();
829
+ const exitCode = await runCliWithOptions(options);
830
+ node_process_1.default.exit(exitCode);
831
+ }
832
+ if (node_process_1.default.env.VITEST !== "true") {
833
+ void run();
834
+ }
835
+ async function readRepoFileContent(repoPath, filePath) {
836
+ try {
837
+ return await node_fs_1.promises.readFile(node_path_1.default.resolve(repoPath, filePath), "utf8");
838
+ }
839
+ catch {
840
+ return "";
841
+ }
842
+ }
843
+ async function capturePatchOriginals(repoPath, patches) {
844
+ const entries = await Promise.all(patches.map(async (patch) => [
845
+ patch.filePath,
846
+ await readRepoFileContent(repoPath, patch.filePath),
847
+ ]));
848
+ return Object.fromEntries(entries);
849
+ }
850
+ //# sourceMappingURL=index.js.map