@noorm/marie-cli 0.1.17 → 0.1.18

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 (156) hide show
  1. package/dist/cli-new/components/AgenticSpinner.js +28 -0
  2. package/dist/cli-new/components/AgenticSpinner.js.map +1 -0
  3. package/dist/cli-new/components/App.js +1 -1
  4. package/dist/cli-new/components/App.js.map +1 -1
  5. package/dist/cli-new/components/ApprovalDialog.js +1 -1
  6. package/dist/cli-new/components/ApprovalDialog.js.map +1 -1
  7. package/dist/cli-new/components/Banner.js +15 -5
  8. package/dist/cli-new/components/Banner.js.map +1 -1
  9. package/dist/cli-new/components/Header.js +2 -2
  10. package/dist/cli-new/components/Header.js.map +1 -1
  11. package/dist/cli-new/components/InputArea.js +29 -23
  12. package/dist/cli-new/components/InputArea.js.map +1 -1
  13. package/dist/cli-new/components/MessageBubble.js +5 -4
  14. package/dist/cli-new/components/MessageBubble.js.map +1 -1
  15. package/dist/cli-new/components/SessionSwitcher.js +3 -3
  16. package/dist/cli-new/components/SessionSwitcher.js.map +1 -1
  17. package/dist/cli-new/components/SetupWizard.js +11 -11
  18. package/dist/cli-new/components/SetupWizard.js.map +1 -1
  19. package/dist/cli-new/components/ToolCallDisplay.js +1 -1
  20. package/dist/cli-new/components/ToolCallDisplay.js.map +1 -1
  21. package/dist/cli-new/hooks/useUpdateCheck.js +1 -1
  22. package/dist/cli-new/hooks/useUpdateCheck.js.map +1 -1
  23. package/dist/cli-new/styles/theme.js +17 -17
  24. package/dist/cli-new/styles/theme.js.map +1 -1
  25. package/dist/extension.cjs +861 -341
  26. package/dist/extension.js +2 -1
  27. package/dist/extension.js.map +1 -1
  28. package/dist/monolith/adapters/CliMarieAdapter.js +7 -7
  29. package/dist/monolith/adapters/CliMarieAdapter.js.map +1 -1
  30. package/dist/monolith/adapters/VscodeMarieAdapter.js +9 -9
  31. package/dist/monolith/adapters/VscodeMarieAdapter.js.map +1 -1
  32. package/dist/monolith/cli/MarieToolDefinitionsCLI.js +5 -2
  33. package/dist/monolith/cli/MarieToolDefinitionsCLI.js.map +1 -1
  34. package/dist/monolith/cli/index.js +6 -0
  35. package/dist/monolith/cli/index.js.map +1 -1
  36. package/dist/monolith/cli/storage.js +79 -60
  37. package/dist/monolith/cli/storage.js.map +1 -1
  38. package/dist/monolith/infrastructure/ai/context/ContextArchiveService.js +52 -37
  39. package/dist/monolith/infrastructure/ai/context/ContextArchiveService.js.map +1 -1
  40. package/dist/monolith/infrastructure/ai/context/ContextManager.js +35 -2
  41. package/dist/monolith/infrastructure/ai/context/ContextManager.js.map +1 -1
  42. package/dist/monolith/infrastructure/ai/core/MarieEngine.js +513 -3
  43. package/dist/monolith/infrastructure/ai/core/MarieEngine.js.map +1 -1
  44. package/dist/monolith/infrastructure/ai/core/MarieLockManager.js +25 -5
  45. package/dist/monolith/infrastructure/ai/core/MarieLockManager.js.map +1 -1
  46. package/dist/monolith/infrastructure/ai/core/MarieProgressTracker.js +29 -0
  47. package/dist/monolith/infrastructure/ai/core/MarieProgressTracker.js.map +1 -1
  48. package/dist/monolith/infrastructure/ai/core/MariePulseService.js +41 -7
  49. package/dist/monolith/infrastructure/ai/core/MariePulseService.js.map +1 -1
  50. package/dist/monolith/infrastructure/ai/core/MarieSanitizer.js +97 -8
  51. package/dist/monolith/infrastructure/ai/core/MarieSanitizer.js.map +1 -1
  52. package/dist/monolith/infrastructure/ai/core/MarieSemaphore.js +47 -4
  53. package/dist/monolith/infrastructure/ai/core/MarieSemaphore.js.map +1 -1
  54. package/dist/monolith/infrastructure/ai/core/MarieSession.js +95 -15
  55. package/dist/monolith/infrastructure/ai/core/MarieSession.js.map +1 -1
  56. package/dist/monolith/infrastructure/ai/core/MarieStabilityMonitor.js +21 -0
  57. package/dist/monolith/infrastructure/ai/core/MarieStabilityMonitor.js.map +1 -1
  58. package/dist/monolith/infrastructure/ai/core/MarieToolMender.js +12 -0
  59. package/dist/monolith/infrastructure/ai/core/MarieToolMender.js.map +1 -1
  60. package/dist/monolith/infrastructure/ai/core/MarieToolProcessor.js +155 -14
  61. package/dist/monolith/infrastructure/ai/core/MarieToolProcessor.js.map +1 -1
  62. package/dist/monolith/infrastructure/ai/core/ReasoningBudget.js +23 -12
  63. package/dist/monolith/infrastructure/ai/core/ReasoningBudget.js.map +1 -1
  64. package/dist/monolith/infrastructure/ai/providers/AnthropicProvider.js +6 -0
  65. package/dist/monolith/infrastructure/ai/providers/AnthropicProvider.js.map +1 -1
  66. package/dist/monolith/infrastructure/ai/providers/CerebrasProvider.js +6 -0
  67. package/dist/monolith/infrastructure/ai/providers/CerebrasProvider.js.map +1 -1
  68. package/dist/monolith/infrastructure/ai/providers/OpenRouterProvider.js +22 -0
  69. package/dist/monolith/infrastructure/ai/providers/OpenRouterProvider.js.map +1 -1
  70. package/dist/monolith/infrastructure/config/ConfigService.js +145 -1
  71. package/dist/monolith/infrastructure/config/ConfigService.js.map +1 -1
  72. package/dist/monolith/infrastructure/joy/CognitiveRituals.js +169 -0
  73. package/dist/monolith/infrastructure/joy/CognitiveRituals.js.map +1 -0
  74. package/dist/monolith/infrastructure/joy/JoyTools.js +15 -2
  75. package/dist/monolith/infrastructure/joy/JoyTools.js.map +1 -1
  76. package/dist/monolith/infrastructure/persistence/NoormmeAutonomics.js +118 -0
  77. package/dist/monolith/infrastructure/persistence/NoormmeAutonomics.js.map +1 -0
  78. package/dist/monolith/infrastructure/persistence/NoormmeEngine.js +78 -0
  79. package/dist/monolith/infrastructure/persistence/NoormmeEngine.js.map +1 -0
  80. package/dist/monolith/infrastructure/persistence/NoormmeSchema.js +150 -0
  81. package/dist/monolith/infrastructure/persistence/NoormmeSchema.js.map +1 -0
  82. package/dist/monolith/infrastructure/persistence/NoormmeSeeder.js +81 -0
  83. package/dist/monolith/infrastructure/persistence/NoormmeSeeder.js.map +1 -0
  84. package/dist/monolith/infrastructure/persistence/NoormmeTools.js +324 -0
  85. package/dist/monolith/infrastructure/persistence/NoormmeTools.js.map +1 -0
  86. package/dist/monolith/infrastructure/tools/MarieToolDefinitions.js +29 -1577
  87. package/dist/monolith/infrastructure/tools/MarieToolDefinitions.js.map +1 -1
  88. package/dist/monolith/infrastructure/tools/definitions/AnalysisTools.js +346 -0
  89. package/dist/monolith/infrastructure/tools/definitions/AnalysisTools.js.map +1 -0
  90. package/dist/monolith/infrastructure/tools/definitions/AutomationTools.js +289 -0
  91. package/dist/monolith/infrastructure/tools/definitions/AutomationTools.js.map +1 -0
  92. package/dist/monolith/infrastructure/tools/definitions/ContextTools.js +43 -0
  93. package/dist/monolith/infrastructure/tools/definitions/ContextTools.js.map +1 -0
  94. package/dist/monolith/infrastructure/tools/definitions/CoreTools.js +41 -0
  95. package/dist/monolith/infrastructure/tools/definitions/CoreTools.js.map +1 -0
  96. package/dist/monolith/infrastructure/tools/definitions/DiagnosticTools.js +185 -0
  97. package/dist/monolith/infrastructure/tools/definitions/DiagnosticTools.js.map +1 -0
  98. package/dist/monolith/infrastructure/tools/definitions/NavigationTools.js +348 -0
  99. package/dist/monolith/infrastructure/tools/definitions/NavigationTools.js.map +1 -0
  100. package/dist/monolith/infrastructure/tools/definitions/PlanningTools.js +297 -0
  101. package/dist/monolith/infrastructure/tools/definitions/PlanningTools.js.map +1 -0
  102. package/dist/monolith/plumbing/analysis/MarieSentinelService.js +1 -2
  103. package/dist/monolith/plumbing/analysis/MarieSentinelService.js.map +1 -1
  104. package/dist/monolith/plumbing/terminal/TerminalService.js +5 -0
  105. package/dist/monolith/plumbing/terminal/TerminalService.js.map +1 -1
  106. package/dist/monolith/plumbing/utils/EnvironmentUtils.js +1 -1
  107. package/dist/monolith/plumbing/utils/EnvironmentUtils.js.map +1 -1
  108. package/dist/monolith/plumbing/utils/MutexUtils.js.map +1 -1
  109. package/dist/monolith/runtime/MarieRuntime.js +86 -4
  110. package/dist/monolith/runtime/MarieRuntime.js.map +1 -1
  111. package/dist/monolith/runtime/RuntimeAdapterBase.js.map +1 -1
  112. package/dist/monolith/services/JoyService.js +1 -1
  113. package/dist/monolith/services/JoyService.js.map +1 -1
  114. package/dist/monolith/services/MarieGhostService.js +12 -0
  115. package/dist/monolith/services/MarieGhostService.js.map +1 -1
  116. package/dist/monolith/services/UpdateService.js +6 -6
  117. package/dist/monolith/services/UpdateService.js.map +1 -1
  118. package/dist/webview-ui/main.js +23 -23
  119. package/package.json +2 -1
  120. package/test-mind-p6.sqlite +0 -0
  121. package/test-mind-p6.sqlite-shm +0 -0
  122. package/test-mind-p6.sqlite-wal +0 -0
  123. package/dist/monolith/domain/joy/JoyTools.js +0 -535
  124. package/dist/monolith/domain/joy/JoyTools.js.map +0 -1
  125. package/dist/monolith/infrastructure/ai/agents/MarieYOLO.js +0 -207
  126. package/dist/monolith/infrastructure/ai/agents/MarieYOLO.js.map +0 -1
  127. package/dist/monolith/infrastructure/ai/core/MarieYOLOTypes.js +0 -2
  128. package/dist/monolith/infrastructure/ai/core/MarieYOLOTypes.js.map +0 -1
  129. package/dist/test_agent_stream_control_plane.js +0 -170
  130. package/dist/test_agent_stream_control_plane.js.map +0 -1
  131. package/dist/test_strategy_integration.js +0 -114
  132. package/dist/test_strategy_integration.js.map +0 -1
  133. package/dist/test_streaming_fragility.js +0 -191
  134. package/dist/test_streaming_fragility.js.map +0 -1
  135. package/dist/webview-ui/App.js +0 -16
  136. package/dist/webview-ui/App.js.map +0 -1
  137. package/dist/webview-ui/Providers.js +0 -6
  138. package/dist/webview-ui/Providers.js.map +0 -1
  139. package/dist/webview-ui/components/ApprovalPanel.js +0 -8
  140. package/dist/webview-ui/components/ApprovalPanel.js.map +0 -1
  141. package/dist/webview-ui/components/ChatPanel.js +0 -19
  142. package/dist/webview-ui/components/ChatPanel.js.map +0 -1
  143. package/dist/webview-ui/components/Composer.js +0 -19
  144. package/dist/webview-ui/components/Composer.js.map +0 -1
  145. package/dist/webview-ui/components/HeaderBar.js +0 -5
  146. package/dist/webview-ui/components/HeaderBar.js.map +0 -1
  147. package/dist/webview-ui/components/SessionList.js +0 -14
  148. package/dist/webview-ui/components/SessionList.js.map +0 -1
  149. package/dist/webview-ui/context/WebviewStateContext.js +0 -146
  150. package/dist/webview-ui/context/WebviewStateContext.js.map +0 -1
  151. package/dist/webview-ui/main.js.map +0 -1
  152. package/dist/webview-ui/types.js +0 -2
  153. package/dist/webview-ui/types.js.map +0 -1
  154. package/dist/webview-ui/vscode.js +0 -4
  155. package/dist/webview-ui/vscode.js.map +0 -1
  156. package/marie-coder-0.1.16.vsix +0 -0
@@ -5,11 +5,14 @@ import { MarieToolProcessor } from "./MarieToolProcessor.js";
5
5
  import { MarieAscendant } from "../agents/MarieAscendant.js";
6
6
  import { MarieLockManager } from "./MarieLockManager.js";
7
7
  import { MarieToolMender } from "./MarieToolMender.js";
8
- import { MariePulseService } from "./MariePulseService.js";
9
8
  import { MarieStabilityMonitor } from "./MarieStabilityMonitor.js";
9
+ import { MariePulseService } from "./MariePulseService.js";
10
10
  import { ReasoningBudget } from "./ReasoningBudget.js";
11
11
  import { SessionLogService } from "./SessionLogService.js";
12
12
  import { MarieSemaphore } from "./MarieSemaphore.js";
13
+ import { ConfigService } from "../../config/ConfigService.js";
14
+ import { NoormmeEngine } from "../../persistence/NoormmeEngine.js";
15
+ import { MarieGhostService } from "../../../services/MarieGhostService.js";
13
16
  export function getPromptProfileForDepth(depth) {
14
17
  return depth > 0 ? "continuation" : "full";
15
18
  }
@@ -77,6 +80,30 @@ export class MarieEngine {
77
80
  if (this.disposed) {
78
81
  throw new Error("MarieEngine has been disposed.");
79
82
  }
83
+ // PHASE 17: Recursive Depth Enforcement
84
+ const maxDepth = ConfigService.getMaxRecursiveDepth();
85
+ if (depth > maxDepth) {
86
+ console.error(`[MarieEngine] ABORT: Maximum recursive depth (${maxDepth}) reached.`);
87
+ tracker.emitEvent({
88
+ type: "reasoning",
89
+ runId: tracker.getRun().runId,
90
+ text: `🚨 EMERGENCY PROTOCOL: Recursive reasoning ceiling reached (Depth: ${depth}/${maxDepth}). Aborting to prevent systemic depletion.`,
91
+ elapsedMs: tracker.elapsedMs(),
92
+ });
93
+ return accumulatedContent;
94
+ }
95
+ // PHASE 22: Emergency Sub-turn Shedding
96
+ if (depth > 0 && MarieStabilityMonitor.isCriticalPressure()) {
97
+ const msg = "🚨 RESOURCE DEPLETION: Critical system pressure detected. Shedding recursive sub-turn to preserve stability.";
98
+ console.warn(`[MarieEngine] ${msg}`);
99
+ tracker.emitEvent({
100
+ type: "reasoning",
101
+ runId: tracker.getRun().runId,
102
+ text: msg,
103
+ elapsedMs: tracker.elapsedMs(),
104
+ });
105
+ return accumulatedContent;
106
+ }
80
107
  console.log(`[MarieEngine] chatLoop started at depth ${depth}. Accumulated content length: ${accumulatedContent.length}`);
81
108
  // TURN COLLISION GUARD (Instance): Wait for any existing turn in this instance to finish
82
109
  if (this.activeTurn) {
@@ -84,22 +111,54 @@ export class MarieEngine {
84
111
  await this.activeTurn;
85
112
  }
86
113
  // GLOBAL SEMAPHORE: Acquire slot before proceeding
87
- await MarieEngine.globalSemaphore.acquire();
114
+ await MarieEngine.globalSemaphore.acquire(signal);
88
115
  let resolveTurn = () => { };
89
116
  this.activeTurn = new Promise((resolve) => {
90
117
  resolveTurn = resolve;
91
118
  });
92
119
  try {
120
+ tracker.recordLog(`[MarieEngine] chatLoop started at depth ${depth}. Accumulated content length: ${accumulatedContent.length}`);
93
121
  const result = await this._executeChatLoop(messages, tracker, saveHistory, signal, consecutiveErrorCount, depth, accumulatedContent);
94
122
  console.log(`[MarieEngine] chatLoop finished at depth ${depth}. Final content length: ${result.length}`);
95
123
  return result;
96
124
  }
125
+ catch (error) {
126
+ // PHASE 18: Automated Post-Mortem
127
+ await this.triggerPostMortem(error, tracker);
128
+ // PHASE 22: Memory-Aware Ghost Cleanup
129
+ if (MarieStabilityMonitor.isCriticalPressure()) {
130
+ MarieGhostService.clearAll();
131
+ }
132
+ throw error;
133
+ }
97
134
  finally {
98
135
  MarieEngine.globalSemaphore.release();
99
136
  resolveTurn();
100
137
  this.activeTurn = null;
101
138
  }
102
139
  }
140
+ async triggerPostMortem(error, tracker) {
141
+ console.error(`[MarieEngine] CRITICAL FAILURE. Triggering Automated Post-Mortem.`, error);
142
+ try {
143
+ const db = await NoormmeEngine.getInstance();
144
+ const snapshot = tracker.getDiagnosticSnapshot();
145
+ await db.execute(`INSERT INTO agent_post_mortems
146
+ (session_id, run_id, error_message, stack_trace, event_snapshot, log_snapshot, state_snapshot)
147
+ VALUES (?, ?, ?, ?, ?, ?, ?)`, [
148
+ snapshot.runMetadata.sessionId || "default",
149
+ snapshot.runMetadata.runId,
150
+ error.message,
151
+ error.stack || "No stack trace available",
152
+ JSON.stringify(snapshot.events),
153
+ JSON.stringify(snapshot.logs),
154
+ JSON.stringify(this.state)
155
+ ]);
156
+ console.log(`[MarieEngine] Post-Mortem snapshot persisted for run: ${snapshot.runMetadata.runId}`);
157
+ }
158
+ catch (e) {
159
+ console.warn("[MarieEngine] Failed to persist post-mortem snapshot", e);
160
+ }
161
+ }
103
162
  async _executeChatLoop(messages, tracker, saveHistory, signal, consecutiveErrorCount = 0, depth = 0, accumulatedContent = "") {
104
163
  if (signal?.aborted) {
105
164
  throw new Error("Execution aborted by user.");
@@ -124,6 +183,30 @@ export class MarieEngine {
124
183
  const originalEmit = tracker.emitEvent.bind(tracker);
125
184
  tracker.emitEvent = (event) => {
126
185
  void logService.appendEvent(event);
186
+ // PHASE 8: Deep NOORMME Telemetry Integration
187
+ NoormmeEngine.getInstance().then(db => {
188
+ const typeMap = {
189
+ "reasoning": "prompt",
190
+ "content_delta": "output",
191
+ "checkpoint": "action",
192
+ "technique_falter": "error",
193
+ "decree": "pivot"
194
+ };
195
+ const noormType = typeMap[event.type] || "telemetry";
196
+ // Extract text content for NOORMME synthesis
197
+ let content = "";
198
+ if (event.text && typeof event.text === "string")
199
+ content = event.text;
200
+ else if (event.summary && typeof event.summary === "object")
201
+ content = JSON.stringify(event.summary);
202
+ else
203
+ content = JSON.stringify(event);
204
+ db.agent.cortex.telemetry.track(originatingSessionId, noormType, content, { ...event, runId: tracker.getRun().runId }).catch(e => console.warn("[MarieEngine] NOORMME Telemetry track failed", e));
205
+ // Track "Magic" for high-confidence breakthroughs
206
+ if (event.type === "decree" && typeof event.confidence === "number" && event.confidence > 2.0) {
207
+ db.agent.cortex.telemetry.track(originatingSessionId, "magic", `High Confidence Breakthrough: ${event.reason || "Unknown"}`, { surpriseScore: event.confidence / 2 }).catch(() => { });
208
+ }
209
+ }).catch(() => { });
127
210
  originalEmit(event);
128
211
  };
129
212
  if (depth > 20) {
@@ -137,6 +220,23 @@ export class MarieEngine {
137
220
  this.lockManager = new MarieLockManager(tracker);
138
221
  const dispatcher = new MarieEventDispatcher(tracker, this.ghostPort);
139
222
  MarieStabilityMonitor.start();
223
+ // PHASE 8.4: Resource Quota Throttling
224
+ try {
225
+ const db = await NoormmeEngine.getInstance();
226
+ const quotaCheck = await db.agent.cortex.quotas.checkQuota("global"); // Global check for safety
227
+ if (!quotaCheck.allowed) {
228
+ tracker.emitEvent({
229
+ type: "reasoning",
230
+ runId: tracker.getRun().runId,
231
+ text: `🛑 **GLOBAL QUOTA EXCEEDED**: ${quotaCheck.reason}. Throttling execution for safety.`,
232
+ elapsedMs: tracker.elapsedMs(),
233
+ });
234
+ return accumulatedContent + "\n\n⚠️ Resource Quota Exceeded. " + quotaCheck.reason;
235
+ }
236
+ }
237
+ catch (e) {
238
+ console.warn("[MarieEngine] Quota check failed", e);
239
+ }
140
240
  if (tracker.getRun().steps === 0 && !tracker.getRun().isResuming) {
141
241
  tracker.emitEvent({
142
242
  type: "reasoning",
@@ -144,6 +244,171 @@ export class MarieEngine {
144
244
  text: "🔥 Ascension protocol initiated. Hero's conviction rising.",
145
245
  elapsedMs: tracker.elapsedMs(),
146
246
  });
247
+ // PHASE 7: Goal Deconstruction & Persistence
248
+ try {
249
+ const db = await NoormmeEngine.getInstance();
250
+ const userMsg = messages.filter(m => m.role === "user").pop();
251
+ if (userMsg && typeof userMsg.content === "string") {
252
+ // START EPISODIC NARRATIVE
253
+ const episode = await db.agent.cortex.episodes.startEpisode(originatingSessionId, userMsg.content.substring(0, 50) + "...");
254
+ this.state.activeEpisodeId = episode.id;
255
+ // PHASE 8: Strategic Evolution & Persona Mutation
256
+ try {
257
+ tracker.emitEvent({
258
+ type: "reasoning",
259
+ runId: tracker.getRun().runId,
260
+ text: "🧬 **Strategic Alignment**: Auditing performance metrics for evolutionary mutation...",
261
+ elapsedMs: tracker.elapsedMs(),
262
+ });
263
+ const mutations = await db.agent.cortex.strategy.mutateStrategy();
264
+ if (mutations.length > 0) {
265
+ tracker.emitEvent({
266
+ type: "reasoning",
267
+ runId: tracker.getRun().runId,
268
+ text: `✨ **Evolutionary Mutation Applied**: ${mutations[0]}`,
269
+ elapsedMs: tracker.elapsedMs(),
270
+ });
271
+ }
272
+ // PHASE 7: Logical Contradiction Protection
273
+ const contradictions = await db.agent.cortex.reasoner.detectContradictions();
274
+ if (contradictions.length > 0) {
275
+ const conflictContext = contradictions.slice(0, 3).map(c => `> ${c}`).join("\n");
276
+ tracker.emitEvent({
277
+ type: "reasoning",
278
+ runId: tracker.getRun().runId,
279
+ text: `⚠️ **LOGICAL CONTRADICTION ALERT**: Detected potential goal conflicts:\n${conflictContext}`,
280
+ elapsedMs: tracker.elapsedMs(),
281
+ });
282
+ messages.push({
283
+ role: "system",
284
+ content: `[LOGICAL CONTRADICTION ALERT]\nThe sovereign mind has detected contradictions in current objectives. Ensure your next actions resolve or respect these constraints:\n${conflictContext}`
285
+ });
286
+ }
287
+ // Fetch the current active persona to align system prompt
288
+ const activePersona = await db.execute("SELECT role, policies FROM agent_personas WHERE status = 'active' LIMIT 1");
289
+ if (activePersona?.rows?.[0]) {
290
+ const p = activePersona.rows[0];
291
+ messages.unshift({
292
+ role: "system",
293
+ content: `[SOVEREIGN PERSONA ALIGNMENT]\nYour current role has been evolved: ${p.role}\nActive Policies: ${p.policies}`
294
+ });
295
+ }
296
+ }
297
+ catch (e) {
298
+ console.warn("[MarieEngine] Strategic evolution failed", e);
299
+ }
300
+ // PHASE 9: Alpha Cross-Pollination
301
+ try {
302
+ if (Math.random() < 0.05) { // 5% chance to cross-pollinate from HiveMind Alpha variants
303
+ const alphaVariants = await db.execute("SELECT role FROM agent_personas WHERE metadata LIKE '%\"anchored_reliability\":%' ORDER BY json_extract(metadata, '$.anchored_reliability') DESC LIMIT 3");
304
+ if (alphaVariants?.rows?.[0]) {
305
+ const alphaRole = alphaVariants.rows[0].role;
306
+ tracker.emitEvent({
307
+ type: "reasoning",
308
+ runId: tracker.getRun().runId,
309
+ text: "🐝 **Alpha Cross-Pollination**: Incorporating high-reliability traits from the Hive Alpha...",
310
+ elapsedMs: tracker.elapsedMs(),
311
+ });
312
+ messages.push({
313
+ role: "system",
314
+ content: `[ALPHA CROSS-POLLINATION]\nIncorporate these verified high-performance traits into your current reasoning chain:\n${alphaRole.substring(0, 200)}...`
315
+ });
316
+ }
317
+ }
318
+ }
319
+ catch (e) {
320
+ console.warn("[MarieEngine] Alpha cross-pollination failed", e);
321
+ }
322
+ // PHASE 8: Shadow Trials (Experimental Strategy)
323
+ try {
324
+ const useShadow = Math.random() < 0.1; // 10% chance for shadow trial
325
+ if (useShadow) {
326
+ tracker.emitEvent({
327
+ type: "reasoning",
328
+ runId: tracker.getRun().runId,
329
+ text: "🌓 **Shadow Trial Initiated**: Activating experimental reasoning parameters...",
330
+ elapsedMs: tracker.elapsedMs(),
331
+ });
332
+ messages.push({
333
+ role: "system",
334
+ content: "[SHADOW TRIAL ACTIVE]\nYou are in an experimental reasoning mode. Prioritize direct, high-precision actions and minimize explanation verbosity."
335
+ });
336
+ }
337
+ }
338
+ catch (e) {
339
+ console.warn("[MarieEngine] Shadow Trial initiation failed", e);
340
+ }
341
+ // PHASE 8: Proactive Curiosity & Knowledge Gaps
342
+ try {
343
+ tracker.emitEvent({
344
+ type: "reasoning",
345
+ runId: tracker.getRun().runId,
346
+ text: "🕵️ **Internal Reflection**: Sifting for knowledge hotspots and ontological gaps...",
347
+ elapsedMs: tracker.elapsedMs(),
348
+ });
349
+ const proposals = await db.agent.cortex.curiosity.proposeResearch();
350
+ if (proposals.length > 0) {
351
+ const gapContext = proposals.slice(0, 3).map(p => `- ${p}`).join("\n");
352
+ tracker.emitEvent({
353
+ type: "reasoning",
354
+ runId: tracker.getRun().runId,
355
+ text: `🔍 **Identified Knowledge Gaps**:\n${gapContext}`,
356
+ elapsedMs: tracker.elapsedMs(),
357
+ });
358
+ messages.push({
359
+ role: "system",
360
+ content: `[INTERNAL REFLECTION: KNOWLEDGE GAPS]\nThe sovereign mind has identified these potential gaps in your current understanding of the ecosystem. Prioritize bridging these if relevant to the current quest:\n${gapContext}`
361
+ });
362
+ }
363
+ }
364
+ catch (e) {
365
+ console.warn("[MarieEngine] Curiosity ingestion failed", e);
366
+ }
367
+ const parentGoal = await db.agent.cortex.sessions.upsertGoal(originatingSessionId, userMsg.content.substring(0, 100) + (userMsg.content.length > 100 ? "..." : ""), { priority: 10 });
368
+ // PHASE 12: LLM-Powered Goal Architecture
369
+ try {
370
+ tracker.emitEvent({
371
+ type: "reasoning",
372
+ runId: tracker.getRun().runId,
373
+ text: "🏗️ **Goal Architecture**: Systemically deconstructing complex objectives...",
374
+ elapsedMs: tracker.elapsedMs(),
375
+ });
376
+ // Use the GoalArchitect to decompose the high-level intent into systemic milestones
377
+ // NOORMME's GoalArchitect uses the LLM to slice the intent into atomic, verifiable goals.
378
+ const subGoals = await db.agent.cortex.goalArchitect.deconstructGoal(parentGoal.id, userMsg.content);
379
+ if (subGoals.length > 0) {
380
+ const milestoneSummary = subGoals.map((sg) => `- [ ] ${sg.description}`).join("\n");
381
+ tracker.emitEvent({
382
+ type: "reasoning",
383
+ runId: tracker.getRun().runId,
384
+ text: `📍 **System Milestones Established**:\n${milestoneSummary}`,
385
+ elapsedMs: tracker.elapsedMs(),
386
+ });
387
+ }
388
+ }
389
+ catch (e) {
390
+ console.warn("[MarieEngine] Goal deconstruction failed", e);
391
+ }
392
+ // PHASE 8.2: Ablation Performance Monitoring
393
+ try {
394
+ const ablationStatus = await db.agent.cortex.ablation.monitorAblationPerformance();
395
+ if (ablationStatus.status === "degraded") {
396
+ tracker.emitEvent({
397
+ type: "reasoning",
398
+ runId: tracker.getRun().runId,
399
+ text: `🩻 **Performance Drift Detected**: Success rates dropped. Recovered ${ablationStatus.recoveredCount} high-value memories.`,
400
+ elapsedMs: tracker.elapsedMs(),
401
+ });
402
+ }
403
+ }
404
+ catch (e) {
405
+ console.warn("[MarieEngine] Ablation monitoring failed", e);
406
+ }
407
+ }
408
+ }
409
+ catch (e) {
410
+ console.warn("[MarieEngine] Failed to deconstruct goals or check conflicts", e);
411
+ }
147
412
  }
148
413
  // SPIRIT BURST & AWAKENING DETECTION
149
414
  const wasBurstActive = this.state.isSpiritBurstActive;
@@ -201,8 +466,41 @@ export class MarieEngine {
201
466
  const MAX_TOOLS_PER_TURN = 30;
202
467
  const executeTool = async (toolCall) => {
203
468
  const tool = this.toolRegistry.getTool(toolCall.name);
469
+ const db = await NoormmeEngine.getInstance();
470
+ let action = null;
471
+ try {
472
+ action = await db.agent.cortex.actions.logAction(originatingSessionId, toolCall.name, toolCall.input);
473
+ }
474
+ catch (e) {
475
+ console.warn("[MarieEngine] Failed to log action start to NOORMME", e);
476
+ }
477
+ // PHASE 8.4: Capability Sandboxing
478
+ try {
479
+ const personaId = this.state.activePersonaId || "default";
480
+ const access = await db.agent.cortex.capabilities.validateCapabilityAccess(personaId, toolCall.name);
481
+ if (!access.allowed) {
482
+ tracker.emitEvent({
483
+ type: "reasoning",
484
+ runId: tracker.getRun().runId,
485
+ text: `🛡️ **CAPABILITY BLOCKED**: Access to tool '${toolCall.name}' denied. Reason: ${access.reason}`,
486
+ elapsedMs: tracker.elapsedMs(),
487
+ });
488
+ return {
489
+ tool_call_id: toolCall.id,
490
+ role: "tool",
491
+ name: toolCall.name,
492
+ content: `Error: Capability Blocked. ${access.reason}`,
493
+ };
494
+ }
495
+ }
496
+ catch (e) {
497
+ console.warn("[MarieEngine] Capability validation failed", e);
498
+ }
204
499
  if (!tool) {
205
500
  const repairResult = await this.toolMender.performFuzzyRepair(toolCall, "Tool not found", tracker, processor, this.state, signal);
501
+ if (action) {
502
+ await db.agent.cortex.actions.recordOutcome(action.id, repairResult && !repairResult.startsWith("Error") ? "success" : "failure", repairResult || "Tool not found");
503
+ }
206
504
  if (repairResult) {
207
505
  this.toolCallCounter++;
208
506
  return {
@@ -221,6 +519,78 @@ export class MarieEngine {
221
519
  const startTime = Date.now();
222
520
  pulse.startHeartbeat();
223
521
  try {
522
+ // PHASE 8: Universal Policy Shield
523
+ try {
524
+ const evalContext = {
525
+ ...toolCall.input,
526
+ tool_name: toolCall.name,
527
+ content: JSON.stringify(toolCall.input),
528
+ // PHASE 12: Token-based Turn Cost Heuristic
529
+ turn_cost: (JSON.stringify(toolCall.input).length / 4) / 1000 // Tokens / 1000 base unit
530
+ };
531
+ const policyResult = await db.agent.cortex.policies.evaluateContext(evalContext);
532
+ if (!policyResult.allowed) {
533
+ tracker.emitEvent({
534
+ type: "reasoning",
535
+ runId: tracker.getRun().runId,
536
+ text: `🛑 **AGENTIC INTERCEPTION**: Policy Violation Detected.\n> ${policyResult.violations.join("\n> ")}`,
537
+ elapsedMs: tracker.elapsedMs(),
538
+ });
539
+ // PHASE 8: Track Policy Vetoes in telemetry
540
+ const run = tracker.getRun();
541
+ run.policyVetoes = (run.policyVetoes || 0) + 1;
542
+ if (action) {
543
+ await db.agent.cortex.actions.recordOutcome(action.id, "failure", `Policy Veto: ${policyResult.violations.join(", ")}`);
544
+ }
545
+ return {
546
+ type: "tool_result",
547
+ tool_use_id: toolCall.id,
548
+ content: `Error: Execution blocked by Sovereign Governance. Reason: ${policyResult.violations.join("; ")}`,
549
+ };
550
+ }
551
+ }
552
+ catch (e) {
553
+ console.warn("[MarieEngine] Policy enforcement failed, failing safe...", e);
554
+ }
555
+ // PHASE 8.2: Mid-Turn Conflict Resolution
556
+ try {
557
+ const conflicts = await db.agent.cortex.conflicts.auditRuleConflicts();
558
+ if (conflicts.length > 0) {
559
+ // Identify if any conflict applies to the CURRENT tool call (Semantic Shield)
560
+ const relevantConflict = conflicts.find(c => c.toLowerCase().includes(toolCall.name.toLowerCase()));
561
+ if (relevantConflict) {
562
+ tracker.emitEvent({
563
+ type: "reasoning",
564
+ runId: tracker.getRun().runId,
565
+ text: `🛡️ **INTERNAL CONFLICT ALERT**: Tool '${toolCall.name}' may violate cognitive alignment.\n> ${relevantConflict}`,
566
+ elapsedMs: tracker.elapsedMs(),
567
+ });
568
+ }
569
+ }
570
+ }
571
+ catch (e) {
572
+ console.warn("[MarieEngine] Mid-turn conflict resolution failed", e);
573
+ }
574
+ // PHASE 8.3: Goal Milestone Verification
575
+ try {
576
+ const activeGoals = await db.agent.cortex.sessions.getGoals(originatingSessionId);
577
+ for (const goal of activeGoals) {
578
+ if (goal.status === "in_progress" || goal.status === "pending") {
579
+ const deps = await db.agent.cortex.goalArchitect.checkGoalDependencies(goal.id);
580
+ if (!deps.canComplete) {
581
+ tracker.emitEvent({
582
+ type: "reasoning",
583
+ runId: tracker.getRun().runId,
584
+ text: `🚩 **INTERNAL BLOCKER**: Goal "${goal.description.substring(0, 30)}..." has ${deps.pendingSubGoals} pending milestones.`,
585
+ elapsedMs: tracker.elapsedMs(),
586
+ });
587
+ }
588
+ }
589
+ }
590
+ }
591
+ catch (e) {
592
+ console.warn("[MarieEngine] Milestone verification failed", e);
593
+ }
224
594
  // Determine if we need to transition objectives
225
595
  if (tracker.getRun().activeObjectiveId === "understand_request") {
226
596
  tracker.setObjectiveStatus("understand_request", "completed");
@@ -228,6 +598,18 @@ export class MarieEngine {
228
598
  tracker.getRun().activeObjectiveId = "execute_plan";
229
599
  tracker.emitProgressUpdate(`Executing technique: ${toolCall.name}`);
230
600
  }
601
+ // PHASE 13: Active Stability Throttling
602
+ if (MarieStabilityMonitor.isHighPressure()) {
603
+ const metrics = MarieStabilityMonitor.getMetrics();
604
+ console.warn(`[MarieEngine] High pressure detected (Lag: ${metrics.lagMs}ms). Throttling execution...`);
605
+ tracker.emitEvent({
606
+ type: "reasoning",
607
+ runId: tracker.getRun().runId,
608
+ text: `⚠️ **STABILITY THROTTLE**: System pressure detected (Lag: ${metrics.lagMs}ms). Pausing for 2s to allow event loop recovery...`,
609
+ elapsedMs: tracker.elapsedMs(),
610
+ });
611
+ await new Promise(resolve => setTimeout(resolve, 2000));
612
+ }
231
613
  let toolResult = await processor.process(toolCall, signal);
232
614
  // Buffer Hard-Cap
233
615
  if (typeof toolResult === "string" && toolResult.length > 1024 * 1024) {
@@ -238,13 +620,47 @@ export class MarieEngine {
238
620
  const targetFile = toolCall.input?.path ||
239
621
  toolCall.input?.targetFile ||
240
622
  toolCall.input?.file;
623
+ let status = "success";
241
624
  if (typeof toolResult === "string" && toolResult.startsWith("Error")) {
242
625
  this.handleFailure(tracker, toolCall.name, toolResult, targetFile);
243
626
  turnFailureCount++;
627
+ status = "failure";
244
628
  }
245
629
  else {
246
630
  this.handleSuccess(tracker, toolCall.name, durationMs, targetFile, signal);
247
631
  }
632
+ try {
633
+ await db.agent.cortex.actions.recordOutcome(action.id, status, typeof toolResult === "string"
634
+ ? toolResult.substring(0, 500)
635
+ : "Success (Object)", durationMs);
636
+ // PHASE 9: Shadow Trial Success Metrics
637
+ const run = tracker.getRun();
638
+ if (run.shadowTrialActive) {
639
+ await db.agent.cortex.metrics.recordMetric("experimental_success", status === "success" ? 1 : 0, {
640
+ sessionId: originatingSessionId,
641
+ metadata: {
642
+ trialType: "shadow_reasoning",
643
+ toolName: toolCall.name
644
+ }
645
+ });
646
+ }
647
+ // PHASE 10: Capability Evolution
648
+ await db.agent.cortex.capabilities.reportOutcome(toolCall.name, status === "success");
649
+ // Populate 'error' column for ActionRefiner if failure
650
+ if (status === "failure") {
651
+ await db.execute("UPDATE agent_actions SET error = ? WHERE id = ?", [typeof toolResult === "string" ? toolResult : "Unknown Error", action.id]);
652
+ }
653
+ // PHASE 11: Structural Bottleneck Detection
654
+ if (durationMs > 5000) { // Flag slow operations as hotspots for indexing
655
+ await db.agent.cortex.metrics.recordMetric("structural_latency_spike", durationMs, {
656
+ sessionId: originatingSessionId,
657
+ metadata: { toolName: toolCall.name, complexity: "high" }
658
+ });
659
+ }
660
+ }
661
+ catch (e) {
662
+ console.warn("[MarieEngine] Failed to record action outcome to NOORMME", e);
663
+ }
248
664
  this.toolCallCounter++;
249
665
  return {
250
666
  type: "tool_result",
@@ -265,6 +681,7 @@ export class MarieEngine {
265
681
  const now = Date.now();
266
682
  lastTokenTime = now;
267
683
  pulse.startHeartbeat();
684
+ tracker.recordLog(`[MarieEngine] AI Event: ${event.type}`);
268
685
  // RESTORE EVENT ROUTING: Dispatch all stream events
269
686
  if (process.env.MARIE_DEBUG) {
270
687
  console.log(`[Engine Debug] AI Event: ${event.type}`, event.type === "content_delta"
@@ -325,6 +742,15 @@ export class MarieEngine {
325
742
  }
326
743
  else if (event.type === "usage") {
327
744
  tracker.getRun().usage = event.usage;
745
+ // PHASE 6: Resource Consciousness
746
+ try {
747
+ const db = await NoormmeEngine.getInstance();
748
+ await db.agent.cortex.resources.recordUsage(tracker.getRun().runId, ConfigService.getModel(), event.usage.inputTokens, event.usage.outputTokens, 0 // Cost calculation can be added later or handled by NOORMME if configured
749
+ );
750
+ }
751
+ catch (e) {
752
+ console.warn("[MarieEngine] Failed to record resource usage", e);
753
+ }
328
754
  }
329
755
  }
330
756
  }
@@ -401,6 +827,41 @@ export class MarieEngine {
401
827
  text: "✨ Convergence achieved. The pattern sparks joy.",
402
828
  elapsedMs: tracker.elapsedMs(),
403
829
  });
830
+ // PHASE 8: Sovereign Metrics (Life Satisfaction)
831
+ try {
832
+ const db = await NoormmeEngine.getInstance();
833
+ const turnDurationMs = tracker.elapsedMs(); // Use tracker's elapsed time for full turn intensity
834
+ await db.agent.cortex.metrics.recordMetric("turn_intensity", turnDurationMs, {
835
+ sessionId: originatingSessionId,
836
+ unit: "ms"
837
+ });
838
+ const pendingGoals = await db.agent.cortex.sessions.getGoals(originatingSessionId);
839
+ const goalVelocity = Math.max(0, 100 - (pendingGoals.filter(g => g.status !== 'completed').length * 10));
840
+ await db.agent.cortex.metrics.recordMetric("goal_velocity", goalVelocity, {
841
+ sessionId: originatingSessionId,
842
+ unit: "percent"
843
+ });
844
+ }
845
+ catch (e) {
846
+ console.warn("[MarieEngine] Performance metrics recording failed", e);
847
+ }
848
+ // PHASE 5: Sovereign Governance
849
+ try {
850
+ const db = await NoormmeEngine.getInstance();
851
+ // Performance Audit: Sanity check before finalizing turn
852
+ const audit = await db.agent.cortex.governor.performAudit();
853
+ if (!audit.healthy) {
854
+ tracker.emitEvent({
855
+ type: "reasoning",
856
+ runId: tracker.getRun().runId,
857
+ text: `🛡️ GOVERNANCE ALERT: ${audit.issues.length} compliance issues detected. Autonomous remediation initiated.`,
858
+ elapsedMs: tracker.elapsedMs(),
859
+ });
860
+ }
861
+ }
862
+ catch (e) {
863
+ console.warn("[MarieEngine] Governance/Distillation cycle failed", e);
864
+ }
404
865
  dispatcher.clear();
405
866
  return currentAccumulatedContent;
406
867
  }
@@ -423,6 +884,10 @@ export class MarieEngine {
423
884
  text: `✨ Technique Mastery! ${toolName} executed perfectly. Victory Streak: ${this.state.victoryStreak}.`,
424
885
  elapsedMs: tracker.elapsedMs(),
425
886
  });
887
+ // PHASE 8: Hive Skill Propagation
888
+ NoormmeEngine.getInstance().then(db => {
889
+ db.agent.cortex.hive.broadcastSkills().catch(e => console.warn("[MarieEngine] Hive Skill Propagation failed", e));
890
+ });
426
891
  }
427
892
  if (filePath && !this.state.recentFiles.includes(filePath)) {
428
893
  this.state.recentFiles.push(filePath);
@@ -518,15 +983,28 @@ export class MarieEngine {
518
983
  const reason = pressure < 40
519
984
  ? "Low spirit pressure (instability detected)"
520
985
  : `Repeated failures in: ${hotspotFiles}`;
521
- // Log only - do not force the user/agent into a recovery loop
522
986
  console.log(`[MarieEngine] Suggestion: ${reason}. (Auto-recovery disabled for stability)`);
523
987
  }
524
988
  }
989
+ /**
990
+ * REAGENT DISPOSAL: Ensure absolute resource sanctity.
991
+ */
525
992
  dispose() {
526
993
  this.disposed = true;
994
+ if (this.activeTurn) {
995
+ // We don't await here as dispose is usually synchronous
996
+ }
527
997
  this.pulseService?.cleanup();
528
998
  this.pulseService = undefined;
529
999
  this.contentBuffer = "";
1000
+ try {
1001
+ // PHASE 17: Definitive Terminal Cleanup
1002
+ const { TerminalService } = require("../../../plumbing/terminal/TerminalService.js");
1003
+ TerminalService.cleanup();
1004
+ }
1005
+ catch (e) {
1006
+ // Ignore errors if TerminalService is not yet loaded or failed
1007
+ }
530
1008
  }
531
1009
  ensurePulseService(tracker) {
532
1010
  if (!this.pulseService)
@@ -583,5 +1061,37 @@ export class MarieEngine {
583
1061
  }
584
1062
  }
585
1063
  }
1064
+ /**
1065
+ * SEMANTIC SOVEREIGNTY: Search Marie's long-term semantic memory.
1066
+ */
1067
+ async searchMemories(query, limit = 5) {
1068
+ try {
1069
+ const db = await NoormmeEngine.getInstance();
1070
+ if (!db.agent.cortex.vectors)
1071
+ return [];
1072
+ const embedding = await this.provider.createEmbedding(query);
1073
+ return await db.agent.cortex.vectors.search(embedding, { limit });
1074
+ }
1075
+ catch (e) {
1076
+ console.warn("[MarieEngine] Semantic memory search failed", e);
1077
+ return [];
1078
+ }
1079
+ }
1080
+ /**
1081
+ * SEMANTIC SOVEREIGNTY: Search Marie's distilled knowledge base.
1082
+ */
1083
+ async searchKnowledge(entity) {
1084
+ try {
1085
+ const db = await NoormmeEngine.getInstance();
1086
+ return await db.agent.cortex.knowledge.getKnowledgeByEntity(entity);
1087
+ }
1088
+ catch (e) {
1089
+ console.warn("[MarieEngine] Knowledge search failed", e);
1090
+ return [];
1091
+ }
1092
+ }
1093
+ isDisposed() {
1094
+ return this.disposed;
1095
+ }
586
1096
  }
587
1097
  //# sourceMappingURL=MarieEngine.js.map