@mcoda/mswarm 0.1.57 → 0.1.61

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 (250) hide show
  1. package/README.md +19 -0
  2. package/dist/codali-executor.d.ts +278 -0
  3. package/dist/codali-executor.d.ts.map +1 -0
  4. package/dist/codali-executor.js +243 -0
  5. package/dist/codali-executor.js.map +1 -0
  6. package/dist/runtime.d.ts +46 -1
  7. package/dist/runtime.d.ts.map +1 -1
  8. package/dist/runtime.js +298 -30
  9. package/dist/runtime.js.map +1 -1
  10. package/dist/server.d.ts.map +1 -1
  11. package/dist/server.js +66 -1
  12. package/dist/server.js.map +1 -1
  13. package/dist/vendor/codali/agents/AgentProtocol.d.ts +287 -0
  14. package/dist/vendor/codali/agents/AgentProtocol.d.ts.map +1 -0
  15. package/dist/vendor/codali/agents/AgentProtocol.js +365 -0
  16. package/dist/vendor/codali/agents/AgentResolver.d.ts +23 -0
  17. package/dist/vendor/codali/agents/AgentResolver.d.ts.map +1 -0
  18. package/dist/vendor/codali/agents/AgentResolver.js +77 -0
  19. package/dist/vendor/codali/agents/PhaseAgentSelector.d.ts +23 -0
  20. package/dist/vendor/codali/agents/PhaseAgentSelector.d.ts.map +1 -0
  21. package/dist/vendor/codali/agents/PhaseAgentSelector.js +287 -0
  22. package/dist/vendor/codali/cli/EvalCommand.d.ts +37 -0
  23. package/dist/vendor/codali/cli/EvalCommand.d.ts.map +1 -0
  24. package/dist/vendor/codali/cli/EvalCommand.js +333 -0
  25. package/dist/vendor/codali/cli/FeedbackCommand.d.ts +22 -0
  26. package/dist/vendor/codali/cli/FeedbackCommand.d.ts.map +1 -0
  27. package/dist/vendor/codali/cli/FeedbackCommand.js +163 -0
  28. package/dist/vendor/codali/cli/RunCommand.d.ts +78 -0
  29. package/dist/vendor/codali/cli/RunCommand.d.ts.map +1 -0
  30. package/dist/vendor/codali/cli/RunCommand.js +2261 -0
  31. package/dist/vendor/codali/cli.d.ts +3 -0
  32. package/dist/vendor/codali/cli.d.ts.map +1 -0
  33. package/dist/vendor/codali/cli.js +109 -0
  34. package/dist/vendor/codali/cognitive/ArchitectPlanner.d.ts +107 -0
  35. package/dist/vendor/codali/cognitive/ArchitectPlanner.d.ts.map +1 -0
  36. package/dist/vendor/codali/cognitive/ArchitectPlanner.js +1726 -0
  37. package/dist/vendor/codali/cognitive/BuilderOutputParser.d.ts +25 -0
  38. package/dist/vendor/codali/cognitive/BuilderOutputParser.d.ts.map +1 -0
  39. package/dist/vendor/codali/cognitive/BuilderOutputParser.js +164 -0
  40. package/dist/vendor/codali/cognitive/BuilderRunner.d.ts +76 -0
  41. package/dist/vendor/codali/cognitive/BuilderRunner.d.ts.map +1 -0
  42. package/dist/vendor/codali/cognitive/BuilderRunner.js +1159 -0
  43. package/dist/vendor/codali/cognitive/ContextAssembler.d.ts +91 -0
  44. package/dist/vendor/codali/cognitive/ContextAssembler.d.ts.map +1 -0
  45. package/dist/vendor/codali/cognitive/ContextAssembler.js +4547 -0
  46. package/dist/vendor/codali/cognitive/ContextBudget.d.ts +19 -0
  47. package/dist/vendor/codali/cognitive/ContextBudget.d.ts.map +1 -0
  48. package/dist/vendor/codali/cognitive/ContextBudget.js +35 -0
  49. package/dist/vendor/codali/cognitive/ContextFileLoader.d.ts +30 -0
  50. package/dist/vendor/codali/cognitive/ContextFileLoader.d.ts.map +1 -0
  51. package/dist/vendor/codali/cognitive/ContextFileLoader.js +307 -0
  52. package/dist/vendor/codali/cognitive/ContextManager.d.ts +47 -0
  53. package/dist/vendor/codali/cognitive/ContextManager.d.ts.map +1 -0
  54. package/dist/vendor/codali/cognitive/ContextManager.js +272 -0
  55. package/dist/vendor/codali/cognitive/ContextRedactor.d.ts +18 -0
  56. package/dist/vendor/codali/cognitive/ContextRedactor.d.ts.map +1 -0
  57. package/dist/vendor/codali/cognitive/ContextRedactor.js +53 -0
  58. package/dist/vendor/codali/cognitive/ContextSelector.d.ts +22 -0
  59. package/dist/vendor/codali/cognitive/ContextSelector.d.ts.map +1 -0
  60. package/dist/vendor/codali/cognitive/ContextSelector.js +431 -0
  61. package/dist/vendor/codali/cognitive/ContextSerializer.d.ts +8 -0
  62. package/dist/vendor/codali/cognitive/ContextSerializer.d.ts.map +1 -0
  63. package/dist/vendor/codali/cognitive/ContextSerializer.js +882 -0
  64. package/dist/vendor/codali/cognitive/ContextStore.d.ts +27 -0
  65. package/dist/vendor/codali/cognitive/ContextStore.d.ts.map +1 -0
  66. package/dist/vendor/codali/cognitive/ContextStore.js +79 -0
  67. package/dist/vendor/codali/cognitive/ContextSummarizer.d.ts +16 -0
  68. package/dist/vendor/codali/cognitive/ContextSummarizer.d.ts.map +1 -0
  69. package/dist/vendor/codali/cognitive/ContextSummarizer.js +45 -0
  70. package/dist/vendor/codali/cognitive/CostEstimator.d.ts +31 -0
  71. package/dist/vendor/codali/cognitive/CostEstimator.d.ts.map +1 -0
  72. package/dist/vendor/codali/cognitive/CostEstimator.js +66 -0
  73. package/dist/vendor/codali/cognitive/CriticEvaluator.d.ts +32 -0
  74. package/dist/vendor/codali/cognitive/CriticEvaluator.d.ts.map +1 -0
  75. package/dist/vendor/codali/cognitive/CriticEvaluator.js +297 -0
  76. package/dist/vendor/codali/cognitive/EvidenceGate.d.ts +9 -0
  77. package/dist/vendor/codali/cognitive/EvidenceGate.d.ts.map +1 -0
  78. package/dist/vendor/codali/cognitive/EvidenceGate.js +75 -0
  79. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.d.ts +12 -0
  80. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.d.ts.map +1 -0
  81. package/dist/vendor/codali/cognitive/GoldenExampleIndexer.js +34 -0
  82. package/dist/vendor/codali/cognitive/GoldenSetStore.d.ts +33 -0
  83. package/dist/vendor/codali/cognitive/GoldenSetStore.d.ts.map +1 -0
  84. package/dist/vendor/codali/cognitive/GoldenSetStore.js +159 -0
  85. package/dist/vendor/codali/cognitive/IntentSignals.d.ts +7 -0
  86. package/dist/vendor/codali/cognitive/IntentSignals.d.ts.map +1 -0
  87. package/dist/vendor/codali/cognitive/IntentSignals.js +285 -0
  88. package/dist/vendor/codali/cognitive/LearningGovernance.d.ts +100 -0
  89. package/dist/vendor/codali/cognitive/LearningGovernance.d.ts.map +1 -0
  90. package/dist/vendor/codali/cognitive/LearningGovernance.js +276 -0
  91. package/dist/vendor/codali/cognitive/MemoryWriteback.d.ts +64 -0
  92. package/dist/vendor/codali/cognitive/MemoryWriteback.d.ts.map +1 -0
  93. package/dist/vendor/codali/cognitive/MemoryWriteback.js +287 -0
  94. package/dist/vendor/codali/cognitive/PatchApplier.d.ts +49 -0
  95. package/dist/vendor/codali/cognitive/PatchApplier.d.ts.map +1 -0
  96. package/dist/vendor/codali/cognitive/PatchApplier.js +199 -0
  97. package/dist/vendor/codali/cognitive/PatchInterpreter.d.ts +35 -0
  98. package/dist/vendor/codali/cognitive/PatchInterpreter.d.ts.map +1 -0
  99. package/dist/vendor/codali/cognitive/PatchInterpreter.js +100 -0
  100. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.d.ts +7 -0
  101. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.d.ts.map +1 -0
  102. package/dist/vendor/codali/cognitive/PatchOutputNormalizer.js +59 -0
  103. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.d.ts +17 -0
  104. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.d.ts.map +1 -0
  105. package/dist/vendor/codali/cognitive/PostMortemAnalyzer.js +131 -0
  106. package/dist/vendor/codali/cognitive/PreferenceExtraction.d.ts +3 -0
  107. package/dist/vendor/codali/cognitive/PreferenceExtraction.d.ts.map +1 -0
  108. package/dist/vendor/codali/cognitive/PreferenceExtraction.js +85 -0
  109. package/dist/vendor/codali/cognitive/Prompts.d.ts +15 -0
  110. package/dist/vendor/codali/cognitive/Prompts.d.ts.map +1 -0
  111. package/dist/vendor/codali/cognitive/Prompts.js +326 -0
  112. package/dist/vendor/codali/cognitive/ProviderRouting.d.ts +16 -0
  113. package/dist/vendor/codali/cognitive/ProviderRouting.d.ts.map +1 -0
  114. package/dist/vendor/codali/cognitive/ProviderRouting.js +24 -0
  115. package/dist/vendor/codali/cognitive/QueryExtraction.d.ts +12 -0
  116. package/dist/vendor/codali/cognitive/QueryExtraction.d.ts.map +1 -0
  117. package/dist/vendor/codali/cognitive/QueryExtraction.js +262 -0
  118. package/dist/vendor/codali/cognitive/RunHistoryIndexer.d.ts +13 -0
  119. package/dist/vendor/codali/cognitive/RunHistoryIndexer.d.ts.map +1 -0
  120. package/dist/vendor/codali/cognitive/RunHistoryIndexer.js +125 -0
  121. package/dist/vendor/codali/cognitive/SmartPipeline.d.ts +92 -0
  122. package/dist/vendor/codali/cognitive/SmartPipeline.d.ts.map +1 -0
  123. package/dist/vendor/codali/cognitive/SmartPipeline.js +4804 -0
  124. package/dist/vendor/codali/cognitive/Types.d.ts +474 -0
  125. package/dist/vendor/codali/cognitive/Types.d.ts.map +1 -0
  126. package/dist/vendor/codali/cognitive/Types.js +7 -0
  127. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts +57 -0
  128. package/dist/vendor/codali/cognitive/ValidationRunner.d.ts.map +1 -0
  129. package/dist/vendor/codali/cognitive/ValidationRunner.js +515 -0
  130. package/dist/vendor/codali/config/Config.d.ts +249 -0
  131. package/dist/vendor/codali/config/Config.d.ts.map +1 -0
  132. package/dist/vendor/codali/config/Config.js +200 -0
  133. package/dist/vendor/codali/config/ConfigLoader.d.ts +56 -0
  134. package/dist/vendor/codali/config/ConfigLoader.d.ts.map +1 -0
  135. package/dist/vendor/codali/config/ConfigLoader.js +1246 -0
  136. package/dist/vendor/codali/docdex/DocdexClient.d.ts +158 -0
  137. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -0
  138. package/dist/vendor/codali/docdex/DocdexClient.js +785 -0
  139. package/dist/vendor/codali/eval/EvalRunner.d.ts +35 -0
  140. package/dist/vendor/codali/eval/EvalRunner.d.ts.map +1 -0
  141. package/dist/vendor/codali/eval/EvalRunner.js +38 -0
  142. package/dist/vendor/codali/eval/EvalTaskExecutor.d.ts +81 -0
  143. package/dist/vendor/codali/eval/EvalTaskExecutor.d.ts.map +1 -0
  144. package/dist/vendor/codali/eval/EvalTaskExecutor.js +371 -0
  145. package/dist/vendor/codali/eval/GateEvaluator.d.ts +31 -0
  146. package/dist/vendor/codali/eval/GateEvaluator.d.ts.map +1 -0
  147. package/dist/vendor/codali/eval/GateEvaluator.js +134 -0
  148. package/dist/vendor/codali/eval/MetricTypes.d.ts +28 -0
  149. package/dist/vendor/codali/eval/MetricTypes.d.ts.map +1 -0
  150. package/dist/vendor/codali/eval/MetricTypes.js +1 -0
  151. package/dist/vendor/codali/eval/MetricsAggregator.d.ts +4 -0
  152. package/dist/vendor/codali/eval/MetricsAggregator.d.ts.map +1 -0
  153. package/dist/vendor/codali/eval/MetricsAggregator.js +97 -0
  154. package/dist/vendor/codali/eval/RegressionComparator.d.ts +29 -0
  155. package/dist/vendor/codali/eval/RegressionComparator.d.ts.map +1 -0
  156. package/dist/vendor/codali/eval/RegressionComparator.js +155 -0
  157. package/dist/vendor/codali/eval/ReportInputAdapter.d.ts +52 -0
  158. package/dist/vendor/codali/eval/ReportInputAdapter.d.ts.map +1 -0
  159. package/dist/vendor/codali/eval/ReportInputAdapter.js +229 -0
  160. package/dist/vendor/codali/eval/ReportSerializer.d.ts +32 -0
  161. package/dist/vendor/codali/eval/ReportSerializer.d.ts.map +1 -0
  162. package/dist/vendor/codali/eval/ReportSerializer.js +33 -0
  163. package/dist/vendor/codali/eval/ReportStore.d.ts +18 -0
  164. package/dist/vendor/codali/eval/ReportStore.d.ts.map +1 -0
  165. package/dist/vendor/codali/eval/ReportStore.js +96 -0
  166. package/dist/vendor/codali/eval/SuiteLoader.d.ts +12 -0
  167. package/dist/vendor/codali/eval/SuiteLoader.d.ts.map +1 -0
  168. package/dist/vendor/codali/eval/SuiteLoader.js +51 -0
  169. package/dist/vendor/codali/eval/SuiteSchema.d.ts +56 -0
  170. package/dist/vendor/codali/eval/SuiteSchema.d.ts.map +1 -0
  171. package/dist/vendor/codali/eval/SuiteSchema.js +357 -0
  172. package/dist/vendor/codali/index.d.ts +11 -0
  173. package/dist/vendor/codali/index.d.ts.map +1 -0
  174. package/dist/vendor/codali/index.js +5 -0
  175. package/dist/vendor/codali/providers/CodexCliProvider.d.ts +8 -0
  176. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -0
  177. package/dist/vendor/codali/providers/CodexCliProvider.js +282 -0
  178. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts +8 -0
  179. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -0
  180. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +300 -0
  181. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts +8 -0
  182. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -0
  183. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +192 -0
  184. package/dist/vendor/codali/providers/ProviderRegistry.d.ts +12 -0
  185. package/dist/vendor/codali/providers/ProviderRegistry.d.ts.map +1 -0
  186. package/dist/vendor/codali/providers/ProviderRegistry.js +28 -0
  187. package/dist/vendor/codali/providers/ProviderTypes.d.ts +81 -0
  188. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -0
  189. package/dist/vendor/codali/providers/ProviderTypes.js +1 -0
  190. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts +189 -0
  191. package/dist/vendor/codali/runtime/CodaliRuntime.d.ts.map +1 -0
  192. package/dist/vendor/codali/runtime/CodaliRuntime.js +1435 -0
  193. package/dist/vendor/codali/runtime/DeepInvestigationErrors.d.ts +39 -0
  194. package/dist/vendor/codali/runtime/DeepInvestigationErrors.d.ts.map +1 -0
  195. package/dist/vendor/codali/runtime/DeepInvestigationErrors.js +57 -0
  196. package/dist/vendor/codali/runtime/RunContext.d.ts +27 -0
  197. package/dist/vendor/codali/runtime/RunContext.d.ts.map +1 -0
  198. package/dist/vendor/codali/runtime/RunContext.js +51 -0
  199. package/dist/vendor/codali/runtime/RunLogQuery.d.ts +48 -0
  200. package/dist/vendor/codali/runtime/RunLogQuery.d.ts.map +1 -0
  201. package/dist/vendor/codali/runtime/RunLogQuery.js +36 -0
  202. package/dist/vendor/codali/runtime/RunLogReader.d.ts +19 -0
  203. package/dist/vendor/codali/runtime/RunLogReader.d.ts.map +1 -0
  204. package/dist/vendor/codali/runtime/RunLogReader.js +361 -0
  205. package/dist/vendor/codali/runtime/RunLogger.d.ts +71 -0
  206. package/dist/vendor/codali/runtime/RunLogger.d.ts.map +1 -0
  207. package/dist/vendor/codali/runtime/RunLogger.js +100 -0
  208. package/dist/vendor/codali/runtime/RunTelemetryTypes.d.ts +117 -0
  209. package/dist/vendor/codali/runtime/RunTelemetryTypes.d.ts.map +1 -0
  210. package/dist/vendor/codali/runtime/RunTelemetryTypes.js +299 -0
  211. package/dist/vendor/codali/runtime/Runner.d.ts +66 -0
  212. package/dist/vendor/codali/runtime/Runner.d.ts.map +1 -0
  213. package/dist/vendor/codali/runtime/Runner.js +215 -0
  214. package/dist/vendor/codali/runtime/StoragePaths.d.ts +3 -0
  215. package/dist/vendor/codali/runtime/StoragePaths.d.ts.map +1 -0
  216. package/dist/vendor/codali/runtime/StoragePaths.js +19 -0
  217. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts +30 -0
  218. package/dist/vendor/codali/runtime/WorkspaceLock.d.ts.map +1 -0
  219. package/dist/vendor/codali/runtime/WorkspaceLock.js +141 -0
  220. package/dist/vendor/codali/session/InstructionLoader.d.ts +14 -0
  221. package/dist/vendor/codali/session/InstructionLoader.d.ts.map +1 -0
  222. package/dist/vendor/codali/session/InstructionLoader.js +107 -0
  223. package/dist/vendor/codali/session/SessionStore.d.ts +81 -0
  224. package/dist/vendor/codali/session/SessionStore.d.ts.map +1 -0
  225. package/dist/vendor/codali/session/SessionStore.js +244 -0
  226. package/dist/vendor/codali/subagents/SubagentOrchestrator.d.ts +68 -0
  227. package/dist/vendor/codali/subagents/SubagentOrchestrator.d.ts.map +1 -0
  228. package/dist/vendor/codali/subagents/SubagentOrchestrator.js +150 -0
  229. package/dist/vendor/codali/tools/ToolRegistry.d.ts +9 -0
  230. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -0
  231. package/dist/vendor/codali/tools/ToolRegistry.js +293 -0
  232. package/dist/vendor/codali/tools/ToolTypes.d.ts +66 -0
  233. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -0
  234. package/dist/vendor/codali/tools/ToolTypes.js +40 -0
  235. package/dist/vendor/codali/tools/diff/DiffTool.d.ts +3 -0
  236. package/dist/vendor/codali/tools/diff/DiffTool.d.ts.map +1 -0
  237. package/dist/vendor/codali/tools/diff/DiffTool.js +34 -0
  238. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts +4 -0
  239. package/dist/vendor/codali/tools/docdex/DocdexTools.d.ts.map +1 -0
  240. package/dist/vendor/codali/tools/docdex/DocdexTools.js +490 -0
  241. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts +3 -0
  242. package/dist/vendor/codali/tools/filesystem/FileTools.d.ts.map +1 -0
  243. package/dist/vendor/codali/tools/filesystem/FileTools.js +141 -0
  244. package/dist/vendor/codali/tools/search/SearchTool.d.ts +3 -0
  245. package/dist/vendor/codali/tools/search/SearchTool.d.ts.map +1 -0
  246. package/dist/vendor/codali/tools/search/SearchTool.js +46 -0
  247. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +3 -0
  248. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -0
  249. package/dist/vendor/codali/tools/shell/ShellTool.js +104 -0
  250. package/package.json +5 -3
@@ -0,0 +1,287 @@
1
+ import path from "node:path";
2
+ import { DEFAULT_LEARNING_GOVERNANCE_POLICY, governLearningRule, mergeLearningRuleIntoLedger, promoteLearningRuleCandidate, readLearningRuleLedger, writeLearningRuleLedger, } from "./LearningGovernance.js";
3
+ const isUnsupportedDocdexMethod = (error) => {
4
+ if (!error)
5
+ return false;
6
+ const message = error instanceof Error ? error.message : String(error);
7
+ const normalized = message.toLowerCase();
8
+ return normalized.includes("unknown method") || normalized.includes("method not found");
9
+ };
10
+ const resolveLedgerPath = (workspaceRoot, candidateStoreFile) => {
11
+ if (path.isAbsolute(candidateStoreFile))
12
+ return candidateStoreFile;
13
+ return path.resolve(workspaceRoot, candidateStoreFile);
14
+ };
15
+ const mapLearningPolicy = (learning) => ({
16
+ persistence_min_confidence: learning?.persistence_min_confidence
17
+ ?? DEFAULT_LEARNING_GOVERNANCE_POLICY.persistence_min_confidence,
18
+ enforcement_min_confidence: learning?.enforcement_min_confidence
19
+ ?? DEFAULT_LEARNING_GOVERNANCE_POLICY.enforcement_min_confidence,
20
+ require_confirmation_for_low_confidence: learning?.require_confirmation_for_low_confidence
21
+ ?? DEFAULT_LEARNING_GOVERNANCE_POLICY.require_confirmation_for_low_confidence,
22
+ auto_enforce_high_confidence: learning?.auto_enforce_high_confidence
23
+ ?? DEFAULT_LEARNING_GOVERNANCE_POLICY.auto_enforce_high_confidence,
24
+ });
25
+ export class MemoryWriteback {
26
+ constructor(client, options = {}) {
27
+ this.client = client;
28
+ this.agentId = options.agentId ?? "default";
29
+ this.workspaceRoot = path.resolve(options.workspaceRoot ?? process.cwd());
30
+ const candidateStoreFile = options.learning?.candidate_store_file ?? "logs/codali/learning-rules.json";
31
+ this.ledgerPath = resolveLedgerPath(this.workspaceRoot, candidateStoreFile);
32
+ this.policy = mapLearningPolicy(options.learning);
33
+ this.logger = options.logger;
34
+ }
35
+ async logOutcome(outcome) {
36
+ if (!this.logger)
37
+ return;
38
+ await this.logger.log("learning_write_decision", { ...outcome });
39
+ }
40
+ toLegacyProposals(input) {
41
+ const rules = [];
42
+ if (input.failures >= input.maxRetries && input.lesson.trim()) {
43
+ const overshoot = Math.max(0, input.failures - input.maxRetries);
44
+ const confidence = Math.min(0.95, 0.55 + overshoot * 0.05);
45
+ rules.push({
46
+ category: "lesson",
47
+ content: input.lesson.trim(),
48
+ source: "smart_pipeline_failure_threshold",
49
+ scope: "repo_memory",
50
+ confidence_score: confidence,
51
+ evidence: [{ kind: "run", ref: `failures=${input.failures};maxRetries=${input.maxRetries}` }],
52
+ });
53
+ }
54
+ for (const preference of input.preferences ?? []) {
55
+ rules.push({
56
+ category: preference.category,
57
+ content: preference.content,
58
+ source: preference.source ?? "request_directive",
59
+ scope: preference.scope,
60
+ agent_id: preference.agentId,
61
+ confidence_score: preference.confidence_score,
62
+ confidence_band: preference.confidence_band,
63
+ confidence_reasons: preference.confidence_reasons,
64
+ evidence: preference.evidence,
65
+ explicit_confirmation: preference.explicit_confirmation,
66
+ });
67
+ }
68
+ return rules;
69
+ }
70
+ async persistRuleToDocdex(rule) {
71
+ const metadata = {
72
+ schema_version: 1,
73
+ rule_id: rule.id,
74
+ dedupe_key: rule.dedupe_key,
75
+ lifecycle_state: rule.lifecycle_state,
76
+ confidence_score: rule.confidence_score,
77
+ confidence_band: rule.confidence_band,
78
+ confidence_reasons: rule.confidence_reasons,
79
+ source: rule.source,
80
+ evidence: rule.evidence,
81
+ supersedes: rule.supersedes,
82
+ };
83
+ if (rule.scope === "repo_memory") {
84
+ try {
85
+ await this.client.memorySave(rule.content, metadata);
86
+ }
87
+ catch (error) {
88
+ if (!isUnsupportedDocdexMethod(error))
89
+ throw error;
90
+ await this.client.memorySave(rule.content);
91
+ }
92
+ return;
93
+ }
94
+ const agentId = rule.agent_id ?? this.agentId;
95
+ try {
96
+ await this.client.savePreference(agentId, rule.category, rule.content, metadata);
97
+ }
98
+ catch (error) {
99
+ if (!isUnsupportedDocdexMethod(error))
100
+ throw error;
101
+ try {
102
+ await this.client.savePreference(agentId, rule.category, rule.content);
103
+ }
104
+ catch (fallbackError) {
105
+ if (!isUnsupportedDocdexMethod(fallbackError))
106
+ throw fallbackError;
107
+ await this.client.memorySave(`[profile:${rule.category}] ${rule.content}`);
108
+ }
109
+ }
110
+ }
111
+ async persist(input) {
112
+ const outcomes = [];
113
+ const proposals = [...(input.rules ?? []), ...this.toLegacyProposals(input)];
114
+ const promotions = input.promotions ?? [];
115
+ let ledgerChanged = false;
116
+ const ledger = await readLearningRuleLedger(this.ledgerPath);
117
+ for (const proposal of proposals) {
118
+ try {
119
+ const decision = governLearningRule(proposal, this.policy);
120
+ const baseOutcome = {
121
+ status: decision.status,
122
+ code: decision.code,
123
+ message: decision.message,
124
+ rule_id: decision.rule.id,
125
+ dedupe_key: decision.rule.dedupe_key,
126
+ scope: decision.rule.scope,
127
+ lifecycle_state: decision.rule.lifecycle_state,
128
+ confidence_score: decision.rule.confidence_score,
129
+ confidence_band: decision.rule.confidence_band,
130
+ target: decision.rule.scope,
131
+ };
132
+ if (decision.status !== "accepted") {
133
+ outcomes.push(baseOutcome);
134
+ await this.logOutcome(baseOutcome);
135
+ continue;
136
+ }
137
+ const mergeResult = mergeLearningRuleIntoLedger(ledger, decision.rule);
138
+ if (mergeResult.action === "suppressed") {
139
+ const suppressed = {
140
+ ...baseOutcome,
141
+ status: "suppressed",
142
+ code: "dedupe_suppressed",
143
+ message: "Duplicate or weaker learning rule was suppressed.",
144
+ rule_id: mergeResult.rule.id,
145
+ lifecycle_state: mergeResult.rule.lifecycle_state,
146
+ confidence_score: mergeResult.rule.confidence_score,
147
+ confidence_band: mergeResult.rule.confidence_band,
148
+ };
149
+ outcomes.push(suppressed);
150
+ await this.logOutcome(suppressed);
151
+ continue;
152
+ }
153
+ ledgerChanged = true;
154
+ try {
155
+ await this.persistRuleToDocdex(mergeResult.rule);
156
+ const accepted = {
157
+ ...baseOutcome,
158
+ status: "accepted",
159
+ code: mergeResult.action === "superseded"
160
+ ? "accepted_superseded_previous"
161
+ : baseOutcome.code,
162
+ message: mergeResult.action === "superseded"
163
+ ? "Rule accepted and superseded previous rule."
164
+ : baseOutcome.message,
165
+ rule_id: mergeResult.rule.id,
166
+ lifecycle_state: mergeResult.rule.lifecycle_state,
167
+ confidence_score: mergeResult.rule.confidence_score,
168
+ confidence_band: mergeResult.rule.confidence_band,
169
+ };
170
+ outcomes.push(accepted);
171
+ await this.logOutcome(accepted);
172
+ }
173
+ catch (error) {
174
+ const rejected = {
175
+ ...baseOutcome,
176
+ status: "rejected",
177
+ code: "docdex_write_failed",
178
+ message: error instanceof Error ? error.message : String(error),
179
+ rule_id: mergeResult.rule.id,
180
+ };
181
+ outcomes.push(rejected);
182
+ await this.logOutcome(rejected);
183
+ }
184
+ }
185
+ catch (error) {
186
+ const rejected = {
187
+ status: "rejected",
188
+ code: "governance_error",
189
+ message: error instanceof Error ? error.message : String(error),
190
+ };
191
+ outcomes.push(rejected);
192
+ await this.logOutcome(rejected);
193
+ }
194
+ }
195
+ for (const promotion of promotions) {
196
+ try {
197
+ const result = promoteLearningRuleCandidate(ledger, promotion.dedupe_key, this.policy);
198
+ if (result.action === "not_found") {
199
+ const outcome = {
200
+ status: "rejected",
201
+ code: "candidate_not_found",
202
+ message: `No candidate rule found for ${promotion.dedupe_key}.`,
203
+ dedupe_key: promotion.dedupe_key,
204
+ };
205
+ outcomes.push(outcome);
206
+ await this.logOutcome(outcome);
207
+ continue;
208
+ }
209
+ if (result.action === "already_enforced") {
210
+ const outcome = {
211
+ status: "suppressed",
212
+ code: "candidate_already_enforced",
213
+ message: "Candidate is already enforced.",
214
+ dedupe_key: promotion.dedupe_key,
215
+ rule_id: result.previous?.id,
216
+ lifecycle_state: result.previous?.lifecycle_state,
217
+ scope: result.previous?.scope,
218
+ target: result.previous?.scope,
219
+ };
220
+ outcomes.push(outcome);
221
+ await this.logOutcome(outcome);
222
+ continue;
223
+ }
224
+ ledgerChanged = true;
225
+ if (!result.promoted) {
226
+ const outcome = {
227
+ status: "rejected",
228
+ code: "promotion_failed",
229
+ message: "Candidate promotion failed.",
230
+ dedupe_key: promotion.dedupe_key,
231
+ };
232
+ outcomes.push(outcome);
233
+ await this.logOutcome(outcome);
234
+ continue;
235
+ }
236
+ try {
237
+ await this.persistRuleToDocdex({
238
+ ...result.promoted,
239
+ agent_id: promotion.agentId ?? result.promoted.agent_id,
240
+ });
241
+ const outcome = {
242
+ status: "promoted",
243
+ code: "candidate_promoted",
244
+ message: "Candidate promoted to enforced.",
245
+ dedupe_key: result.promoted.dedupe_key,
246
+ rule_id: result.promoted.id,
247
+ scope: result.promoted.scope,
248
+ lifecycle_state: result.promoted.lifecycle_state,
249
+ confidence_score: result.promoted.confidence_score,
250
+ confidence_band: result.promoted.confidence_band,
251
+ target: result.promoted.scope,
252
+ };
253
+ outcomes.push(outcome);
254
+ await this.logOutcome(outcome);
255
+ }
256
+ catch (error) {
257
+ const outcome = {
258
+ status: "rejected",
259
+ code: "promotion_write_failed",
260
+ message: error instanceof Error ? error.message : String(error),
261
+ dedupe_key: result.promoted.dedupe_key,
262
+ rule_id: result.promoted.id,
263
+ };
264
+ outcomes.push(outcome);
265
+ await this.logOutcome(outcome);
266
+ }
267
+ }
268
+ catch (error) {
269
+ const outcome = {
270
+ status: "rejected",
271
+ code: "promotion_error",
272
+ message: error instanceof Error ? error.message : String(error),
273
+ dedupe_key: promotion.dedupe_key,
274
+ };
275
+ outcomes.push(outcome);
276
+ await this.logOutcome(outcome);
277
+ }
278
+ }
279
+ if (ledgerChanged) {
280
+ await writeLearningRuleLedger(this.ledgerPath, ledger);
281
+ }
282
+ return {
283
+ outcomes,
284
+ ledgerPath: this.ledgerPath,
285
+ };
286
+ }
287
+ }
@@ -0,0 +1,49 @@
1
+ import type { PatchAction } from "./BuilderOutputParser.js";
2
+ export interface PatchApplyResult {
3
+ touched: string[];
4
+ }
5
+ export type PatchPolicyReasonCode = "patch_outside_workspace" | "patch_outside_allowed_scope" | "patch_read_only_path" | "destructive_operation_blocked" | "writes_disabled_by_profile";
6
+ export interface PatchPolicyErrorMetadata {
7
+ reason_code: PatchPolicyReasonCode;
8
+ file: string;
9
+ normalized_file: string;
10
+ action: PatchAction["action"];
11
+ allowed_paths?: string[];
12
+ read_only_paths?: string[];
13
+ policy?: string;
14
+ }
15
+ export declare class PatchPolicyError extends Error {
16
+ readonly metadata: PatchPolicyErrorMetadata;
17
+ constructor(message: string, metadata: PatchPolicyErrorMetadata);
18
+ }
19
+ export interface PatchApplyPolicy {
20
+ allowWritePaths?: string[];
21
+ readOnlyPaths?: string[];
22
+ allowDestructiveOperations?: boolean;
23
+ allowWrites?: boolean;
24
+ }
25
+ export interface PatchApplierOptions {
26
+ workspaceRoot: string;
27
+ validateFile?: (filePath: string) => Promise<void> | void;
28
+ policy?: PatchApplyPolicy;
29
+ }
30
+ export interface PatchRollbackEntry {
31
+ file: string;
32
+ normalizedFile: string;
33
+ resolved: string;
34
+ existed: boolean;
35
+ content?: string;
36
+ }
37
+ export interface PatchRollbackPlan {
38
+ entries: PatchRollbackEntry[];
39
+ }
40
+ export declare class PatchApplier {
41
+ private options;
42
+ constructor(options: PatchApplierOptions);
43
+ private resolvePolicy;
44
+ private resolvePatchTarget;
45
+ createRollback(patches: PatchAction[], policyOverride?: PatchApplyPolicy): Promise<PatchRollbackPlan>;
46
+ rollback(plan: PatchRollbackPlan): Promise<void>;
47
+ apply(patches: PatchAction[], policyOverride?: PatchApplyPolicy): Promise<PatchApplyResult>;
48
+ }
49
+ //# sourceMappingURL=PatchApplier.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PatchApplier.d.ts","sourceRoot":"","sources":["../../src/cognitive/PatchApplier.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAE5D,MAAM,WAAW,gBAAgB;IAC/B,OAAO,EAAE,MAAM,EAAE,CAAC;CACnB;AAED,MAAM,MAAM,qBAAqB,GAC7B,yBAAyB,GACzB,6BAA6B,GAC7B,sBAAsB,GACtB,+BAA+B,GAC/B,4BAA4B,CAAC;AAEjC,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,qBAAqB,CAAC;IACnC,IAAI,EAAE,MAAM,CAAC;IACb,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IAC9B,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB;AAED,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,QAAQ,CAAC,QAAQ,EAAE,wBAAwB,CAAC;gBAEhC,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,wBAAwB;CAKhE;AAED,MAAM,WAAW,gBAAgB;IAC/B,eAAe,CAAC,EAAE,MAAM,EAAE,CAAC;IAC3B,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;IACzB,0BAA0B,CAAC,EAAE,OAAO,CAAC;IACrC,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB;AAED,MAAM,WAAW,mBAAmB;IAClC,aAAa,EAAE,MAAM,CAAC;IACtB,YAAY,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC;IAC1D,MAAM,CAAC,EAAE,gBAAgB,CAAC;CAC3B;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC;IACjB,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,kBAAkB,EAAE,CAAC;CAC/B;AAqED,qBAAa,YAAY;IACX,OAAO,CAAC,OAAO;gBAAP,OAAO,EAAE,mBAAmB;IAEhD,OAAO,CAAC,aAAa;IAarB,OAAO,CAAC,kBAAkB;IAuDpB,cAAc,CAClB,OAAO,EAAE,WAAW,EAAE,EACtB,cAAc,CAAC,EAAE,gBAAgB,GAChC,OAAO,CAAC,iBAAiB,CAAC;IA6BvB,QAAQ,CAAC,IAAI,EAAE,iBAAiB,GAAG,OAAO,CAAC,IAAI,CAAC;IAWhD,KAAK,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,cAAc,CAAC,EAAE,gBAAgB,GAAG,OAAO,CAAC,gBAAgB,CAAC;CAwBlG"}
@@ -0,0 +1,199 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ export class PatchPolicyError extends Error {
4
+ constructor(message, metadata) {
5
+ super(message);
6
+ this.name = "PatchPolicyError";
7
+ this.metadata = metadata;
8
+ }
9
+ }
10
+ const normalizePath = (value) => value.replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+/g, "/");
11
+ const dedupePaths = (values) => Array.from(new Set(values.map(normalizePath)));
12
+ const pathMatches = (candidates, target) => candidates.some((entry) => target === entry || target.startsWith(`${entry}/`));
13
+ const resolvePath = (workspaceRoot, targetPath) => {
14
+ const normalizedTarget = normalizePath(targetPath);
15
+ const resolved = path.resolve(workspaceRoot, normalizedTarget);
16
+ const relative = normalizePath(path.relative(workspaceRoot, resolved));
17
+ if (relative.startsWith("..") || path.isAbsolute(relative)) {
18
+ throw new Error("Path is outside workspace root");
19
+ }
20
+ return { resolved, normalized: normalizedTarget };
21
+ };
22
+ const buildWhitespaceCollapsed = (input) => {
23
+ let compact = "";
24
+ const map = [];
25
+ for (let index = 0; index < input.length; index += 1) {
26
+ const char = input[index];
27
+ if (/\s/.test(char)) {
28
+ continue;
29
+ }
30
+ compact += char;
31
+ map.push(index);
32
+ }
33
+ return { compact, map };
34
+ };
35
+ const replaceOnce = (content, search, replace) => {
36
+ const occurrences = content.split(search).length - 1;
37
+ if (occurrences === 1) {
38
+ return content.replace(search, replace);
39
+ }
40
+ if (occurrences > 1) {
41
+ throw new Error("Ambiguous search block. Provide more context.");
42
+ }
43
+ const compactSearch = search.replace(/\s+/g, "");
44
+ if (!compactSearch) {
45
+ throw new Error("Search block not found in file.");
46
+ }
47
+ const collapsed = buildWhitespaceCollapsed(content);
48
+ const firstIndex = collapsed.compact.indexOf(compactSearch);
49
+ if (firstIndex < 0) {
50
+ throw new Error("Search block not found in file.");
51
+ }
52
+ if (collapsed.compact.indexOf(compactSearch, firstIndex + 1) >= 0) {
53
+ throw new Error("Ambiguous search block. Provide more context.");
54
+ }
55
+ const start = collapsed.map[firstIndex];
56
+ const end = collapsed.map[firstIndex + compactSearch.length - 1] + 1;
57
+ return `${content.slice(0, start)}${replace}${content.slice(end)}`;
58
+ };
59
+ const toMessage = (error) => (error instanceof Error ? error.message : String(error));
60
+ const isNotFoundError = (error) => {
61
+ const message = toMessage(error);
62
+ return message.includes("no such file") || message.includes("ENOENT");
63
+ };
64
+ export class PatchApplier {
65
+ constructor(options) {
66
+ this.options = options;
67
+ }
68
+ resolvePolicy(override) {
69
+ const merged = {
70
+ ...(this.options.policy ?? {}),
71
+ ...(override ?? {}),
72
+ };
73
+ return {
74
+ allowWritePaths: dedupePaths((merged.allowWritePaths ?? []).filter(Boolean)),
75
+ readOnlyPaths: dedupePaths((merged.readOnlyPaths ?? []).filter(Boolean)),
76
+ allowDestructiveOperations: merged.allowDestructiveOperations === true,
77
+ allowWrites: merged.allowWrites !== false,
78
+ };
79
+ }
80
+ resolvePatchTarget(patch, policyOverride) {
81
+ const policy = this.resolvePolicy(policyOverride);
82
+ let target;
83
+ try {
84
+ target = resolvePath(this.options.workspaceRoot, patch.file);
85
+ }
86
+ catch (error) {
87
+ throw new PatchPolicyError("Path is outside workspace root", {
88
+ reason_code: "patch_outside_workspace",
89
+ file: patch.file,
90
+ normalized_file: normalizePath(patch.file),
91
+ action: patch.action,
92
+ });
93
+ }
94
+ if (!policy.allowWrites) {
95
+ throw new PatchPolicyError("Write actions are disabled for the active workflow profile", {
96
+ reason_code: "writes_disabled_by_profile",
97
+ file: patch.file,
98
+ normalized_file: target.normalized,
99
+ action: patch.action,
100
+ policy: "allowWrites",
101
+ });
102
+ }
103
+ if (pathMatches(policy.readOnlyPaths, target.normalized)) {
104
+ throw new PatchPolicyError(`Patch target is read-only: ${patch.file}`, {
105
+ reason_code: "patch_read_only_path",
106
+ file: patch.file,
107
+ normalized_file: target.normalized,
108
+ action: patch.action,
109
+ read_only_paths: policy.readOnlyPaths,
110
+ });
111
+ }
112
+ if (policy.allowWritePaths.length > 0 && !pathMatches(policy.allowWritePaths, target.normalized)) {
113
+ throw new PatchPolicyError(`Patch target is outside allowed scope: ${patch.file}`, {
114
+ reason_code: "patch_outside_allowed_scope",
115
+ file: patch.file,
116
+ normalized_file: target.normalized,
117
+ action: patch.action,
118
+ allowed_paths: policy.allowWritePaths,
119
+ });
120
+ }
121
+ if (patch.action === "delete" && !policy.allowDestructiveOperations) {
122
+ throw new PatchPolicyError("Delete action blocked by destructive-operation policy", {
123
+ reason_code: "destructive_operation_blocked",
124
+ file: patch.file,
125
+ normalized_file: target.normalized,
126
+ action: patch.action,
127
+ policy: "allowDestructiveOperations",
128
+ });
129
+ }
130
+ return { resolved: target.resolved, normalized: target.normalized, policy };
131
+ }
132
+ async createRollback(patches, policyOverride) {
133
+ const entries = [];
134
+ for (const patch of patches) {
135
+ const target = this.resolvePatchTarget(patch, policyOverride);
136
+ try {
137
+ const content = await fs.readFile(target.resolved, "utf8");
138
+ entries.push({
139
+ file: patch.file,
140
+ normalizedFile: target.normalized,
141
+ resolved: target.resolved,
142
+ existed: true,
143
+ content,
144
+ });
145
+ }
146
+ catch (error) {
147
+ if (isNotFoundError(error)) {
148
+ entries.push({
149
+ file: patch.file,
150
+ normalizedFile: target.normalized,
151
+ resolved: target.resolved,
152
+ existed: false,
153
+ });
154
+ }
155
+ else {
156
+ throw error;
157
+ }
158
+ }
159
+ }
160
+ return { entries };
161
+ }
162
+ async rollback(plan) {
163
+ for (const entry of plan.entries) {
164
+ if (entry.existed) {
165
+ await fs.mkdir(path.dirname(entry.resolved), { recursive: true });
166
+ await fs.writeFile(entry.resolved, entry.content ?? "", "utf8");
167
+ }
168
+ else {
169
+ await fs.rm(entry.resolved, { force: true });
170
+ }
171
+ }
172
+ }
173
+ async apply(patches, policyOverride) {
174
+ const touched = [];
175
+ for (const patch of patches) {
176
+ const target = this.resolvePatchTarget(patch, policyOverride);
177
+ if (patch.action === "create") {
178
+ await fs.mkdir(path.dirname(target.resolved), { recursive: true });
179
+ await fs.writeFile(target.resolved, patch.content, "utf8");
180
+ touched.push(patch.file);
181
+ if (this.options.validateFile)
182
+ await this.options.validateFile(target.resolved);
183
+ continue;
184
+ }
185
+ if (patch.action === "delete") {
186
+ await fs.rm(target.resolved, { force: true });
187
+ touched.push(patch.file);
188
+ continue;
189
+ }
190
+ const content = await fs.readFile(target.resolved, "utf8");
191
+ const updated = replaceOnce(content, patch.search_block, patch.replace_block);
192
+ await fs.writeFile(target.resolved, updated, "utf8");
193
+ touched.push(patch.file);
194
+ if (this.options.validateFile)
195
+ await this.options.validateFile(target.resolved);
196
+ }
197
+ return { touched };
198
+ }
199
+ }
@@ -0,0 +1,35 @@
1
+ import type { Provider, ProviderResponseFormat } from "../providers/ProviderTypes.js";
2
+ import { type PatchFormat, type PatchPayload } from "./BuilderOutputParser.js";
3
+ export interface PatchInterpreterLogger {
4
+ log(type: string, data: Record<string, unknown>): Promise<void>;
5
+ }
6
+ export interface PatchInterpreterOptions {
7
+ provider: Provider;
8
+ patchFormat: PatchFormat;
9
+ responseFormat?: ProviderResponseFormat;
10
+ temperature?: number;
11
+ maxTokens?: number;
12
+ timeoutMs?: number;
13
+ maxRetries?: number;
14
+ logger?: PatchInterpreterLogger;
15
+ model?: string;
16
+ }
17
+ export interface PatchInterpreterClient {
18
+ interpret(raw: string, patchFormatOverride?: PatchFormat): Promise<PatchPayload>;
19
+ }
20
+ export declare class PatchInterpreter implements PatchInterpreterClient {
21
+ private provider;
22
+ private patchFormat;
23
+ private responseFormat?;
24
+ private temperature?;
25
+ private maxTokens?;
26
+ private timeoutMs?;
27
+ private maxRetries;
28
+ private logger?;
29
+ private model?;
30
+ constructor(options: PatchInterpreterOptions);
31
+ private requestPatch;
32
+ private parse;
33
+ interpret(raw: string, patchFormatOverride?: PatchFormat): Promise<PatchPayload>;
34
+ }
35
+ //# sourceMappingURL=PatchInterpreter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"PatchInterpreter.d.ts","sourceRoot":"","sources":["../../src/cognitive/PatchInterpreter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,QAAQ,EAER,sBAAsB,EACvB,MAAM,+BAA+B,CAAC;AACvC,OAAO,EAAoB,KAAK,WAAW,EAAE,KAAK,YAAY,EAAE,MAAM,0BAA0B,CAAC;AAIjG,MAAM,WAAW,sBAAsB;IACrC,GAAG,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACjE;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,EAAE,QAAQ,CAAC;IACnB,WAAW,EAAE,WAAW,CAAC;IACzB,cAAc,CAAC,EAAE,sBAAsB,CAAC;IACxC,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,MAAM,CAAC,EAAE,sBAAsB,CAAC;IAChC,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACrC,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,mBAAmB,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;CAClF;AAED,qBAAa,gBAAiB,YAAW,sBAAsB;IAC7D,OAAO,CAAC,QAAQ,CAAW;IAC3B,OAAO,CAAC,WAAW,CAAc;IACjC,OAAO,CAAC,cAAc,CAAC,CAAyB;IAChD,OAAO,CAAC,WAAW,CAAC,CAAS;IAC7B,OAAO,CAAC,SAAS,CAAC,CAAS;IAC3B,OAAO,CAAC,SAAS,CAAC,CAAS;IAC3B,OAAO,CAAC,UAAU,CAAS;IAC3B,OAAO,CAAC,MAAM,CAAC,CAAyB;IACxC,OAAO,CAAC,KAAK,CAAC,CAAS;gBAEX,OAAO,EAAE,uBAAuB;YAY9B,YAAY;IA0C1B,OAAO,CAAC,KAAK;IAQP,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,mBAAmB,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,YAAY,CAAC;CAsCvF"}
@@ -0,0 +1,100 @@
1
+ import { parsePatchOutput } from "./BuilderOutputParser.js";
2
+ import { normalizePatchOutput } from "./PatchOutputNormalizer.js";
3
+ import { buildInterpreterPrompt, buildInterpreterRetryPrompt } from "./Prompts.js";
4
+ export class PatchInterpreter {
5
+ constructor(options) {
6
+ this.provider = options.provider;
7
+ this.patchFormat = options.patchFormat;
8
+ this.responseFormat = options.responseFormat;
9
+ this.temperature = options.temperature;
10
+ this.maxTokens = options.maxTokens;
11
+ this.timeoutMs = options.timeoutMs;
12
+ this.maxRetries = options.maxRetries ?? 1;
13
+ this.logger = options.logger;
14
+ this.model = options.model;
15
+ }
16
+ async requestPatch(prompt, raw, meta) {
17
+ const messages = [
18
+ { role: "system", content: prompt },
19
+ { role: "user", content: raw },
20
+ ];
21
+ if (this.logger) {
22
+ await this.logger.log("provider_request", {
23
+ provider: this.provider.name,
24
+ model: this.model,
25
+ messages,
26
+ temperature: this.temperature,
27
+ maxTokens: this.maxTokens,
28
+ responseFormat: this.responseFormat ?? { type: "json" },
29
+ stream: false,
30
+ });
31
+ await this.logger.log("interpreter_request", {
32
+ retry: meta.retry,
33
+ patchFormat: meta.patchFormat,
34
+ model: this.model,
35
+ });
36
+ }
37
+ const response = await this.provider.generate({
38
+ messages,
39
+ maxTokens: this.maxTokens,
40
+ temperature: this.temperature,
41
+ responseFormat: this.responseFormat ?? { type: "json" },
42
+ stream: false,
43
+ });
44
+ if (this.logger) {
45
+ await this.logger.log("interpreter_response", {
46
+ retry: meta.retry,
47
+ length: response.message?.content?.length ?? 0,
48
+ patchFormat: meta.patchFormat,
49
+ });
50
+ }
51
+ return response.message?.content ?? "";
52
+ }
53
+ parse(content, patchFormat) {
54
+ const normalized = normalizePatchOutput(content);
55
+ if (!normalized) {
56
+ throw new Error("Patch output is not valid JSON");
57
+ }
58
+ return parsePatchOutput(normalized, patchFormat);
59
+ }
60
+ async interpret(raw, patchFormatOverride) {
61
+ const patchFormat = patchFormatOverride ?? this.patchFormat;
62
+ // Fast-path: in patch_json mode the builder may already emit a usable payload.
63
+ try {
64
+ const parsed = this.parse(raw, patchFormat);
65
+ if (this.logger) {
66
+ await this.logger.log("interpreter_direct_parse", {
67
+ patchFormat,
68
+ length: raw.length,
69
+ });
70
+ }
71
+ return parsed;
72
+ }
73
+ catch {
74
+ // Fall back to provider-assisted interpretation below.
75
+ }
76
+ const prompt = buildInterpreterPrompt(patchFormat);
77
+ const content = await this.requestPatch(prompt, raw, {
78
+ retry: false,
79
+ patchFormat,
80
+ });
81
+ try {
82
+ return this.parse(content, patchFormat);
83
+ }
84
+ catch (error) {
85
+ if (this.maxRetries <= 0) {
86
+ throw error;
87
+ }
88
+ if (this.logger) {
89
+ const message = error instanceof Error ? error.message : String(error);
90
+ await this.logger.log("interpreter_retry", { error: message });
91
+ }
92
+ const retryPrompt = buildInterpreterRetryPrompt(patchFormat);
93
+ const retryContent = await this.requestPatch(retryPrompt, raw, {
94
+ retry: true,
95
+ patchFormat,
96
+ });
97
+ return this.parse(retryContent, patchFormat);
98
+ }
99
+ }
100
+ }