@noorm/marie-cli 0.1.18 → 0.1.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -15
- package/SENTINEL.md +4 -7
- package/dist/cli-new/components/App.js +16 -63
- package/dist/cli-new/components/App.js.map +1 -1
- package/dist/cli-new/components/ApprovalDialog.js +2 -1
- package/dist/cli-new/components/ApprovalDialog.js.map +1 -1
- package/dist/cli-new/components/Banner.js +4 -3
- package/dist/cli-new/components/Banner.js.map +1 -1
- package/dist/cli-new/components/ChatArea.js +6 -7
- package/dist/cli-new/components/ChatArea.js.map +1 -1
- package/dist/cli-new/components/Header.js +13 -7
- package/dist/cli-new/components/Header.js.map +1 -1
- package/dist/cli-new/components/InputArea.js +73 -12
- package/dist/cli-new/components/InputArea.js.map +1 -1
- package/dist/cli-new/components/MessageBubble.js +26 -18
- package/dist/cli-new/components/MessageBubble.js.map +1 -1
- package/dist/cli-new/components/SessionSwitcher.js +4 -7
- package/dist/cli-new/components/SessionSwitcher.js.map +1 -1
- package/dist/cli-new/components/SetupWizard.js +80 -257
- package/dist/cli-new/components/SetupWizard.js.map +1 -1
- package/dist/cli-new/components/ToolCallDisplay.js +20 -5
- package/dist/cli-new/components/ToolCallDisplay.js.map +1 -1
- package/dist/cli-new/components/WizardSteps.js +22 -0
- package/dist/cli-new/components/WizardSteps.js.map +1 -0
- package/dist/cli-new/constants/SetupConstants.js +42 -0
- package/dist/cli-new/constants/SetupConstants.js.map +1 -0
- package/dist/cli-new/hooks/useGit.js +19 -62
- package/dist/cli-new/hooks/useGit.js.map +1 -1
- package/dist/cli-new/hooks/useMarie.js +26 -18
- package/dist/cli-new/hooks/useMarie.js.map +1 -1
- package/dist/cli-new/hooks/useSessions.js +1 -1
- package/dist/cli-new/hooks/useSessions.js.map +1 -1
- package/dist/cli-new/hooks/useSetupWizard.js +88 -0
- package/dist/cli-new/hooks/useSetupWizard.js.map +1 -0
- package/dist/cli-new/hooks/useUpdateCheck.js +4 -3
- package/dist/cli-new/hooks/useUpdateCheck.js.map +1 -1
- package/dist/cli-new/index.js +2 -4
- package/dist/cli-new/index.js.map +1 -1
- package/dist/cli-new/services/CommandService.js +104 -0
- package/dist/cli-new/services/CommandService.js.map +1 -0
- package/dist/cli-new/services/GitService.js +91 -0
- package/dist/cli-new/services/GitService.js.map +1 -0
- package/dist/cli-new/services/MarieService.js +77 -0
- package/dist/cli-new/services/MarieService.js.map +1 -0
- package/dist/cli-new/services/auth-server.js +128 -0
- package/dist/cli-new/services/auth-server.js.map +1 -0
- package/dist/cli-new/utils/version.js +24 -0
- package/dist/cli-new/utils/version.js.map +1 -0
- package/dist/monolith/adapters/CliMarieAdapter.js +12 -11
- package/dist/monolith/adapters/CliMarieAdapter.js.map +1 -1
- package/dist/monolith/cli/CliFileSystemPort.js +17 -3
- package/dist/monolith/cli/CliFileSystemPort.js.map +1 -1
- package/dist/monolith/cli/MarieToolDefinitionsCLI.js +39 -31
- package/dist/monolith/cli/MarieToolDefinitionsCLI.js.map +1 -1
- package/dist/monolith/cli/index.js +5 -20
- package/dist/monolith/cli/index.js.map +1 -1
- package/dist/monolith/cli/services/JoyAutomationServiceCLI.js +15 -62
- package/dist/monolith/cli/services/JoyAutomationServiceCLI.js.map +1 -1
- package/dist/monolith/cli/storage.js +142 -72
- package/dist/monolith/cli/storage.js.map +1 -1
- package/dist/monolith/domain/joy/RitualService.js +44 -46
- package/dist/monolith/domain/joy/RitualService.js.map +1 -1
- package/dist/monolith/domain/marie/MarieCortex.js +148 -0
- package/dist/monolith/domain/marie/MarieCortex.js.map +1 -0
- package/dist/monolith/domain/marie/PersonalityRenderer.js +97 -0
- package/dist/monolith/domain/marie/PersonalityRenderer.js.map +1 -0
- package/dist/monolith/infrastructure/Configuration.js +68 -0
- package/dist/monolith/infrastructure/Configuration.js.map +1 -0
- package/dist/monolith/infrastructure/CoreInfrastructure.js +204 -0
- package/dist/monolith/infrastructure/CoreInfrastructure.js.map +1 -0
- package/dist/monolith/infrastructure/ai/agents/MarieAscendant.js +3 -3
- package/dist/monolith/infrastructure/ai/agents/MarieAscendant.js.map +1 -1
- package/dist/monolith/infrastructure/ai/context/ContextArchiveService.js +6 -27
- package/dist/monolith/infrastructure/ai/context/ContextArchiveService.js.map +1 -1
- package/dist/monolith/infrastructure/ai/context/ContextManager.js +142 -131
- package/dist/monolith/infrastructure/ai/context/ContextManager.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieEngine.js +115 -1077
- package/dist/monolith/infrastructure/ai/core/MarieEngine.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieEventDispatcher.js +1 -37
- package/dist/monolith/infrastructure/ai/core/MarieEventDispatcher.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieLockManager.js +6 -1
- package/dist/monolith/infrastructure/ai/core/MarieLockManager.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieProgressTracker.js +172 -221
- package/dist/monolith/infrastructure/ai/core/MarieProgressTracker.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieSanitizer.js +292 -141
- package/dist/monolith/infrastructure/ai/core/MarieSanitizer.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieToolProcessor.js +331 -614
- package/dist/monolith/infrastructure/ai/core/MarieToolProcessor.js.map +1 -1
- package/dist/monolith/infrastructure/ai/core/MarieVitality.js +238 -0
- package/dist/monolith/infrastructure/ai/core/MarieVitality.js.map +1 -0
- package/dist/monolith/infrastructure/ai/core/SessionLogService.js +9 -2
- package/dist/monolith/infrastructure/ai/core/SessionLogService.js.map +1 -1
- package/dist/monolith/infrastructure/ai/providers/AIProvider.js +402 -1
- package/dist/monolith/infrastructure/ai/providers/AIProvider.js.map +1 -1
- package/dist/monolith/infrastructure/ai/providers/DreamBeesProvider.js +114 -0
- package/dist/monolith/infrastructure/ai/providers/DreamBeesProvider.js.map +1 -0
- package/dist/monolith/infrastructure/ai/providers/OpenRouterProvider.js +426 -392
- package/dist/monolith/infrastructure/ai/providers/OpenRouterProvider.js.map +1 -1
- package/dist/monolith/infrastructure/ai/providers/OpenRouterStreamParser.js +235 -241
- package/dist/monolith/infrastructure/ai/providers/OpenRouterStreamParser.js.map +1 -1
- package/dist/monolith/infrastructure/ai/workerAi.js +185 -0
- package/dist/monolith/infrastructure/ai/workerAi.js.map +1 -0
- package/dist/monolith/infrastructure/config/ConfigService.js +216 -503
- package/dist/monolith/infrastructure/config/ConfigService.js.map +1 -1
- package/dist/monolith/infrastructure/joy/CognitiveRituals.js +4 -165
- package/dist/monolith/infrastructure/joy/CognitiveRituals.js.map +1 -1
- package/dist/monolith/infrastructure/joy/JoyTools.js +14 -47
- package/dist/monolith/infrastructure/joy/JoyTools.js.map +1 -1
- package/dist/monolith/infrastructure/persistence/MarieMindAutonomics.js +4 -0
- package/dist/monolith/infrastructure/persistence/MarieMindAutonomics.js.map +1 -0
- package/dist/monolith/infrastructure/persistence/MarieMindEngine.js +11 -0
- package/dist/monolith/infrastructure/persistence/MarieMindEngine.js.map +1 -0
- package/dist/monolith/infrastructure/persistence/NoormmeAutonomics.js +123 -106
- package/dist/monolith/infrastructure/persistence/NoormmeAutonomics.js.map +1 -1
- package/dist/monolith/infrastructure/persistence/NoormmeEngine.js +508 -63
- package/dist/monolith/infrastructure/persistence/NoormmeEngine.js.map +1 -1
- package/dist/monolith/infrastructure/persistence/NoormmeSchema.js +68 -39
- package/dist/monolith/infrastructure/persistence/NoormmeSchema.js.map +1 -1
- package/dist/monolith/infrastructure/persistence/NoormmeSeeder.js +80 -67
- package/dist/monolith/infrastructure/persistence/NoormmeSeeder.js.map +1 -1
- package/dist/monolith/infrastructure/persistence/NoormmeTools.js +122 -75
- package/dist/monolith/infrastructure/persistence/NoormmeTools.js.map +1 -1
- package/dist/monolith/infrastructure/services/MarieMemoryStore.js +133 -134
- package/dist/monolith/infrastructure/services/MarieMemoryStore.js.map +1 -1
- package/dist/monolith/infrastructure/tools/MarieToolDefinitions.js +6 -30
- package/dist/monolith/infrastructure/tools/MarieToolDefinitions.js.map +1 -1
- package/dist/monolith/infrastructure/tools/PureStreamParser.js +68 -80
- package/dist/monolith/infrastructure/tools/PureStreamParser.js.map +1 -1
- package/dist/monolith/infrastructure/tools/SharedToolDefinitions.js +12 -11
- package/dist/monolith/infrastructure/tools/SharedToolDefinitions.js.map +1 -1
- package/dist/monolith/infrastructure/tools/SovereignTools.js +326 -0
- package/dist/monolith/infrastructure/tools/SovereignTools.js.map +1 -0
- package/dist/monolith/infrastructure/tools/ToolRegistry.js +45 -26
- package/dist/monolith/infrastructure/tools/ToolRegistry.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/AnalysisTools.js +39 -153
- package/dist/monolith/infrastructure/tools/definitions/AnalysisTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/AutomationTools.js +31 -46
- package/dist/monolith/infrastructure/tools/definitions/AutomationTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/ContextTools.js +41 -13
- package/dist/monolith/infrastructure/tools/definitions/ContextTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/CoreTools.js +10 -14
- package/dist/monolith/infrastructure/tools/definitions/CoreTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/DiagnosticTools.js +39 -70
- package/dist/monolith/infrastructure/tools/definitions/DiagnosticTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/NavigationTools.js +30 -181
- package/dist/monolith/infrastructure/tools/definitions/NavigationTools.js.map +1 -1
- package/dist/monolith/infrastructure/tools/definitions/PlanningTools.js +12 -9
- package/dist/monolith/infrastructure/tools/definitions/PlanningTools.js.map +1 -1
- package/dist/monolith/plumbing/Plumbing.js +238 -0
- package/dist/monolith/plumbing/Plumbing.js.map +1 -0
- package/dist/monolith/plumbing/PlumbingAnalysis.js +109 -0
- package/dist/monolith/plumbing/PlumbingAnalysis.js.map +1 -0
- package/dist/monolith/plumbing/PlumbingSystem.js +169 -0
- package/dist/monolith/plumbing/PlumbingSystem.js.map +1 -0
- package/dist/monolith/plumbing/analysis/ComplexityService.js +30 -34
- package/dist/monolith/plumbing/analysis/ComplexityService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/DependencyService.js +55 -44
- package/dist/monolith/plumbing/analysis/DependencyService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/DiscoveryService.js +40 -42
- package/dist/monolith/plumbing/analysis/DiscoveryService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/JoyMapService.js +52 -56
- package/dist/monolith/plumbing/analysis/JoyMapService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/LintService.js +118 -118
- package/dist/monolith/plumbing/analysis/LintService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/MarieSentinelService.js +278 -268
- package/dist/monolith/plumbing/analysis/MarieSentinelService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/QualityGuardrailService.js +116 -114
- package/dist/monolith/plumbing/analysis/QualityGuardrailService.js.map +1 -1
- package/dist/monolith/plumbing/analysis/SurgicalMender.js +57 -59
- package/dist/monolith/plumbing/analysis/SurgicalMender.js.map +1 -1
- package/dist/monolith/plumbing/analysis/TestService.js +89 -89
- package/dist/monolith/plumbing/analysis/TestService.js.map +1 -1
- package/dist/monolith/plumbing/filesystem/FileService.js +123 -195
- package/dist/monolith/plumbing/filesystem/FileService.js.map +1 -1
- package/dist/monolith/plumbing/filesystem/PathResolver.js +7 -8
- package/dist/monolith/plumbing/filesystem/PathResolver.js.map +1 -1
- package/dist/monolith/plumbing/git/GitService.js +4 -4
- package/dist/monolith/plumbing/git/GitService.js.map +1 -1
- package/dist/monolith/plumbing/lsp/SymbolService.js +5 -34
- package/dist/monolith/plumbing/lsp/SymbolService.js.map +1 -1
- package/dist/monolith/plumbing/terminal/ProcessRegistry.js +20 -22
- package/dist/monolith/plumbing/terminal/ProcessRegistry.js.map +1 -1
- package/dist/monolith/plumbing/terminal/TerminalService.js +127 -141
- package/dist/monolith/plumbing/terminal/TerminalService.js.map +1 -1
- package/dist/monolith/plumbing/utils/EnvironmentUtils.js +3 -23
- package/dist/monolith/plumbing/utils/EnvironmentUtils.js.map +1 -1
- package/dist/monolith/plumbing/utils/JsonUtils.js +252 -311
- package/dist/monolith/plumbing/utils/JsonUtils.js.map +1 -1
- package/dist/monolith/plumbing/utils/PlumbingCore.js +549 -0
- package/dist/monolith/plumbing/utils/PlumbingCore.js.map +1 -0
- package/dist/monolith/plumbing/utils/PrefixTree.js +61 -114
- package/dist/monolith/plumbing/utils/PrefixTree.js.map +1 -1
- package/dist/monolith/plumbing/utils/StreamTagDetector.js +89 -127
- package/dist/monolith/plumbing/utils/StreamTagDetector.js.map +1 -1
- package/dist/monolith/plumbing/utils/StringUtils.js +87 -89
- package/dist/monolith/plumbing/utils/StringUtils.js.map +1 -1
- package/dist/monolith/runtime/MarieRuntime.js +76 -499
- package/dist/monolith/runtime/MarieRuntime.js.map +1 -1
- package/dist/monolith/runtime/RuntimeAdapterBase.js +1 -1
- package/dist/monolith/runtime/RuntimeAdapterBase.js.map +1 -1
- package/dist/monolith/runtime/providerFactory.js +1 -7
- package/dist/monolith/runtime/providerFactory.js.map +1 -1
- package/dist/monolith/services/HealthService.js +29 -32
- package/dist/monolith/services/HealthService.js.map +1 -1
- package/dist/monolith/services/JoyAutomationService.js +58 -95
- package/dist/monolith/services/JoyAutomationService.js.map +1 -1
- package/dist/monolith/services/MarieAutomationService.js +59 -0
- package/dist/monolith/services/MarieAutomationService.js.map +1 -0
- package/dist/monolith/services/MarieGhostService.js +46 -173
- package/dist/monolith/services/MarieGhostService.js.map +1 -1
- package/dist/monolith/services/MarieServices.js +102 -0
- package/dist/monolith/services/MarieServices.js.map +1 -0
- package/dist/monolith/services/MarieTypes.js +2 -0
- package/dist/monolith/services/MarieTypes.js.map +1 -0
- package/dist/monolith/services/UpdateService.js +47 -49
- package/dist/monolith/services/UpdateService.js.map +1 -1
- package/dist/prompts.js +11 -5
- package/dist/prompts.js.map +1 -1
- package/dist/test_prefix_tree.js +9 -9
- package/dist/test_prefix_tree.js.map +1 -1
- package/package.json +18 -89
- package/run_test.js +5 -0
- package/.marie_visual_verify_1771225696548/progress_bar_check.txt +0 -1
- package/dist/extension.cjs +0 -1155
- package/dist/extension.js +0 -474
- package/dist/extension.js.map +0 -1
- package/dist/monolith/adapters/VscodeMarieAdapter.js +0 -81
- package/dist/monolith/adapters/VscodeMarieAdapter.js.map +0 -1
- package/dist/monolith/infrastructure/ai/core/GhostPort.js +0 -2
- package/dist/monolith/infrastructure/ai/core/GhostPort.js.map +0 -1
- package/dist/monolith/infrastructure/ai/core/VscodeFileSystemPort.js +0 -33
- package/dist/monolith/infrastructure/ai/core/VscodeFileSystemPort.js.map +0 -1
- package/dist/monolith/infrastructure/ai/providers/AnthropicProvider.js +0 -154
- package/dist/monolith/infrastructure/ai/providers/AnthropicProvider.js.map +0 -1
- package/dist/monolith/infrastructure/ai/providers/CerebrasProvider.js +0 -214
- package/dist/monolith/infrastructure/ai/providers/CerebrasProvider.js.map +0 -1
- package/dist/monolith/plumbing/ui/DecorationService.js +0 -54
- package/dist/monolith/plumbing/ui/DecorationService.js.map +0 -1
- package/dist/monolith/services/JoyLogService.js +0 -48
- package/dist/monolith/services/JoyLogService.js.map +0 -1
- package/dist/monolith/services/JoyService.js +0 -209
- package/dist/monolith/services/JoyService.js.map +0 -1
- package/dist/monolith/services/MarieSCMProvider.js +0 -41
- package/dist/monolith/services/MarieSCMProvider.js.map +0 -1
- package/dist/webview-ui/main.css +0 -1
- package/dist/webview-ui/main.js +0 -108
- package/lint_output.txt +0 -705
- package/lint_output_v2.txt +0 -711
- package/test-mind-p6.sqlite +0 -0
- package/test-mind-p6.sqlite-shm +0 -0
- package/test-mind-p6.sqlite-wal +0 -0
|
@@ -1,1097 +1,135 @@
|
|
|
1
|
-
import
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
import { MarieLockManager } from "./MarieLockManager.js";
|
|
7
|
-
import { MarieToolMender } from "./MarieToolMender.js";
|
|
8
|
-
import { MarieStabilityMonitor } from "./MarieStabilityMonitor.js";
|
|
9
|
-
import { MariePulseService } from "./MariePulseService.js";
|
|
10
|
-
import { ReasoningBudget } from "./ReasoningBudget.js";
|
|
11
|
-
import { SessionLogService } from "./SessionLogService.js";
|
|
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";
|
|
16
|
-
export function getPromptProfileForDepth(depth) {
|
|
17
|
-
return depth > 0 ? "continuation" : "full";
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Entry point for the AI Engine. YOLO Supremacy Edition.
|
|
21
|
-
*/
|
|
1
|
+
import { getTool, getRegisteredTools } from "../../tools/SovereignTools.js";
|
|
2
|
+
import { getModel, getMaxRecursiveDepth, } from "../../Configuration.js";
|
|
3
|
+
import { manageContext } from "../../CoreInfrastructure.js";
|
|
4
|
+
import { SYSTEM_CONTINUATION_PROMPT, SYSTEM_PROMPT } from "../../../../prompts.js";
|
|
5
|
+
import { safeStringify, safeSpread } from "../../../plumbing/utils/PlumbingCore.js";
|
|
22
6
|
export class MarieEngine {
|
|
23
7
|
provider;
|
|
24
8
|
toolRegistry;
|
|
25
9
|
approvalRequester;
|
|
26
10
|
providerFactory;
|
|
27
|
-
fs;
|
|
28
|
-
ghostPort;
|
|
29
|
-
static CONTENT_BUFFER_MAX_BYTES = 1024 * 1024;
|
|
30
|
-
static GLOBAL_CONCURRENCY_LIMIT = 5;
|
|
31
|
-
static globalSemaphore = new MarieSemaphore(MarieEngine.GLOBAL_CONCURRENCY_LIMIT);
|
|
32
|
-
ascendant;
|
|
33
11
|
state;
|
|
34
|
-
|
|
35
|
-
toolMender;
|
|
36
|
-
pulseService;
|
|
37
|
-
reasoningBudget;
|
|
38
|
-
toolCallCounter = 0;
|
|
39
|
-
contentBuffer = "";
|
|
40
|
-
lastContentEmit = 0;
|
|
12
|
+
pulse;
|
|
41
13
|
activeTurn = null;
|
|
42
14
|
disposed = false;
|
|
43
|
-
|
|
44
|
-
|
|
15
|
+
heartbeatTimer = null;
|
|
16
|
+
watchdogTimer = null;
|
|
17
|
+
iterations = [];
|
|
18
|
+
static toolsInFlight = new Map();
|
|
19
|
+
logPath;
|
|
20
|
+
logQueue = [];
|
|
21
|
+
isWritingLog = false;
|
|
22
|
+
constructor(provider, toolRegistry, approvalRequester = async () => true, providerFactory) {
|
|
45
23
|
this.provider = provider;
|
|
46
24
|
this.toolRegistry = toolRegistry;
|
|
47
25
|
this.approvalRequester = approvalRequester;
|
|
48
26
|
this.providerFactory = providerFactory;
|
|
49
|
-
this.
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
this.
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
return {
|
|
59
|
-
errorHotspots: {},
|
|
60
|
-
totalErrorCount: 0,
|
|
61
|
-
spiritPressure: 50,
|
|
62
|
-
recentFiles: [],
|
|
63
|
-
toolHistory: [],
|
|
64
|
-
techniqueExecutions: [],
|
|
65
|
-
victoryStreak: 0,
|
|
66
|
-
shakyResponseDensity: 0,
|
|
67
|
-
writtenFiles: [],
|
|
68
|
-
actionDiffs: {},
|
|
69
|
-
wiringAlerts: [],
|
|
70
|
-
mood: "STABLE",
|
|
71
|
-
isSpiritBurstActive: false,
|
|
72
|
-
isAwakened: false,
|
|
73
|
-
karmaBond: undefined,
|
|
74
|
-
panicCoolDown: 0,
|
|
75
|
-
environment: this.fs?.type === "vscode" ? "vscode" : "cli",
|
|
76
|
-
lastFailedFile: undefined,
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
async chatLoop(messages, tracker, saveHistory, signal, consecutiveErrorCount = 0, depth = 0, accumulatedContent = "") {
|
|
80
|
-
if (this.disposed) {
|
|
81
|
-
throw new Error("MarieEngine has been disposed.");
|
|
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
|
-
}
|
|
107
|
-
console.log(`[MarieEngine] chatLoop started at depth ${depth}. Accumulated content length: ${accumulatedContent.length}`);
|
|
108
|
-
// TURN COLLISION GUARD (Instance): Wait for any existing turn in this instance to finish
|
|
109
|
-
if (this.activeTurn) {
|
|
110
|
-
console.warn("[MarieEngine] INSTANCE RE-ENTRY DETECTED. Waiting for previous turn to finalize...");
|
|
111
|
-
await this.activeTurn;
|
|
112
|
-
}
|
|
113
|
-
// GLOBAL SEMAPHORE: Acquire slot before proceeding
|
|
114
|
-
await MarieEngine.globalSemaphore.acquire(signal);
|
|
115
|
-
let resolveTurn = () => { };
|
|
116
|
-
this.activeTurn = new Promise((resolve) => {
|
|
117
|
-
resolveTurn = resolve;
|
|
118
|
-
});
|
|
27
|
+
this.state = { totalErrorCount: 0, confidenceLevel: 80, recentFiles: [], executionHistory: [] };
|
|
28
|
+
}
|
|
29
|
+
async chatLoop(messages, run, callbacks, saveHistory, signal) {
|
|
30
|
+
if (this.disposed)
|
|
31
|
+
throw new Error("Engine disposed.");
|
|
32
|
+
this.pulse = { pendingContent: "", pendingToolDeltas: new Map(), throttleTimer: null, toolThrottleTimer: null, run, callbacks };
|
|
33
|
+
let depth = 0;
|
|
34
|
+
let accumulatedContent = "";
|
|
35
|
+
const maxDepth = getMaxRecursiveDepth();
|
|
119
36
|
try {
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
}
|
|
162
|
-
async _executeChatLoop(messages, tracker, saveHistory, signal, consecutiveErrorCount = 0, depth = 0, accumulatedContent = "") {
|
|
163
|
-
if (signal?.aborted) {
|
|
164
|
-
throw new Error("Execution aborted by user.");
|
|
165
|
-
}
|
|
166
|
-
const pulse = this.ensurePulseService(tracker);
|
|
167
|
-
// Initialize incremental logging
|
|
168
|
-
const originatingSessionId = tracker.getRun().originatingSessionId || "default";
|
|
169
|
-
if (!this.logService) {
|
|
170
|
-
this.logService = new SessionLogService(originatingSessionId);
|
|
171
|
-
}
|
|
172
|
-
const logService = this.logService;
|
|
173
|
-
logService.setProgressCallback((totalBytes, eventCount) => {
|
|
174
|
-
tracker.emitEvent({
|
|
175
|
-
type: "session_persistence_update",
|
|
176
|
-
runId: tracker.getRun().runId,
|
|
177
|
-
sessionId: originatingSessionId,
|
|
178
|
-
totalBytes,
|
|
179
|
-
elapsedMs: tracker.elapsedMs(),
|
|
180
|
-
});
|
|
181
|
-
});
|
|
182
|
-
// Override tracker emit to persist every event
|
|
183
|
-
const originalEmit = tracker.emitEvent.bind(tracker);
|
|
184
|
-
tracker.emitEvent = (event) => {
|
|
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(() => { });
|
|
210
|
-
originalEmit(event);
|
|
211
|
-
};
|
|
212
|
-
if (depth > 20) {
|
|
213
|
-
// Graceful Stability Limit Reached
|
|
214
|
-
const msg = "⚠️ Stability Alert: Maximum reasoning depth (20) reached. Returning current accumulation to prevent infinite loop.";
|
|
215
|
-
console.warn(msg);
|
|
216
|
-
// Return currently accumulated content so the user sees *something*
|
|
217
|
-
return accumulatedContent + "\n\n" + msg;
|
|
218
|
-
}
|
|
219
|
-
tracker.resetReasoningBudget();
|
|
220
|
-
this.lockManager = new MarieLockManager(tracker);
|
|
221
|
-
const dispatcher = new MarieEventDispatcher(tracker, this.ghostPort);
|
|
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
|
-
}
|
|
240
|
-
if (tracker.getRun().steps === 0 && !tracker.getRun().isResuming) {
|
|
241
|
-
tracker.emitEvent({
|
|
242
|
-
type: "reasoning",
|
|
243
|
-
runId: tracker.getRun().runId,
|
|
244
|
-
text: "🔥 Ascension protocol initiated. Hero's conviction rising.",
|
|
245
|
-
elapsedMs: tracker.elapsedMs(),
|
|
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
|
-
}
|
|
412
|
-
}
|
|
413
|
-
// SPIRIT BURST & AWAKENING DETECTION
|
|
414
|
-
const wasBurstActive = this.state.isSpiritBurstActive;
|
|
415
|
-
const wasAwakened = this.state.isAwakened;
|
|
416
|
-
this.state.isSpiritBurstActive = this.state.spiritPressure > 85;
|
|
417
|
-
this.state.isAwakened = this.state.spiritPressure > 95;
|
|
418
|
-
if (this.state.isAwakened && !wasAwakened) {
|
|
419
|
-
tracker.emitEvent({
|
|
420
|
-
type: "reasoning",
|
|
421
|
-
runId: tracker.getRun().runId,
|
|
422
|
-
text: "✨ AWAKENED! Ultra Instinct achieved. Full codebase sovereignty established.",
|
|
423
|
-
elapsedMs: tracker.elapsedMs(),
|
|
424
|
-
});
|
|
425
|
-
}
|
|
426
|
-
else if (this.state.isSpiritBurstActive && !wasBurstActive) {
|
|
427
|
-
tracker.emitEvent({
|
|
428
|
-
type: "reasoning",
|
|
429
|
-
runId: tracker.getRun().runId,
|
|
430
|
-
text: "💥 SPIRIT BURST! Conviction is absolute. Auto-approval mandate expanded.",
|
|
431
|
-
elapsedMs: tracker.elapsedMs(),
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
// Decay spirit pressure if stale
|
|
435
|
-
if (Date.now() -
|
|
436
|
-
(this.state.techniqueExecutions.slice(-1)[0]?.timestamp || 0) >
|
|
437
|
-
300000) {
|
|
438
|
-
this.state.spiritPressure = Math.max(30, this.state.spiritPressure - 10);
|
|
439
|
-
}
|
|
440
|
-
const processor = new MarieToolProcessor(this.toolRegistry, tracker, async (name, input) => {
|
|
441
|
-
// YOLO AUTO-APPROVAL: Tiered risk assessment
|
|
442
|
-
if (this.shouldAutoApprove(name, input)) {
|
|
443
|
-
tracker.emitEvent({
|
|
444
|
-
type: "checkpoint",
|
|
445
|
-
runId: tracker.getRun().runId,
|
|
446
|
-
status: "approved",
|
|
447
|
-
toolName: name,
|
|
448
|
-
summary: {
|
|
449
|
-
what: "Ascension Auto-Approved",
|
|
450
|
-
why: "Heroic Conviction",
|
|
451
|
-
impact: "Maximum Speed",
|
|
452
|
-
},
|
|
453
|
-
elapsedMs: tracker.elapsedMs(),
|
|
454
|
-
});
|
|
455
|
-
return true;
|
|
456
|
-
}
|
|
457
|
-
return this.approvalRequester(name, input);
|
|
458
|
-
}, this.state, this.fs);
|
|
459
|
-
let turnContent = "";
|
|
460
|
-
const toolBuffer = new Map();
|
|
461
|
-
const parsedInputCache = new Map();
|
|
462
|
-
const toolResultBlocks = [];
|
|
463
|
-
let turnFailureCount = 0;
|
|
464
|
-
let totalToolCount = 0;
|
|
465
|
-
let lastTokenTime = Date.now();
|
|
466
|
-
const MAX_TOOLS_PER_TURN = 30;
|
|
467
|
-
const executeTool = async (toolCall) => {
|
|
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
|
-
}
|
|
499
|
-
if (!tool) {
|
|
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
|
-
}
|
|
504
|
-
if (repairResult) {
|
|
505
|
-
this.toolCallCounter++;
|
|
506
|
-
return {
|
|
507
|
-
type: "tool_result",
|
|
508
|
-
tool_use_id: toolCall.id,
|
|
509
|
-
content: repairResult,
|
|
510
|
-
};
|
|
511
|
-
}
|
|
512
|
-
this.updateShakyResponse();
|
|
513
|
-
return {
|
|
514
|
-
type: "tool_result",
|
|
515
|
-
tool_use_id: toolCall.id,
|
|
516
|
-
content: `Error: Tool "${toolCall.name}" not found.`,
|
|
517
|
-
};
|
|
518
|
-
}
|
|
519
|
-
const startTime = Date.now();
|
|
520
|
-
pulse.startHeartbeat();
|
|
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
|
-
}
|
|
594
|
-
// Determine if we need to transition objectives
|
|
595
|
-
if (tracker.getRun().activeObjectiveId === "understand_request") {
|
|
596
|
-
tracker.setObjectiveStatus("understand_request", "completed");
|
|
597
|
-
tracker.setObjectiveStatus("execute_plan", "in_progress");
|
|
598
|
-
tracker.getRun().activeObjectiveId = "execute_plan";
|
|
599
|
-
tracker.emitProgressUpdate(`Executing technique: ${toolCall.name}`);
|
|
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
|
-
}
|
|
613
|
-
let toolResult = await processor.process(toolCall, signal);
|
|
614
|
-
// Buffer Hard-Cap
|
|
615
|
-
if (typeof toolResult === "string" && toolResult.length > 1024 * 1024) {
|
|
616
|
-
toolResult =
|
|
617
|
-
toolResult.substring(0, 1024 * 1024) + "\n\n🚨 Truncated at 1MB.";
|
|
618
|
-
}
|
|
619
|
-
const durationMs = Date.now() - startTime;
|
|
620
|
-
const targetFile = toolCall.input?.path ||
|
|
621
|
-
toolCall.input?.targetFile ||
|
|
622
|
-
toolCall.input?.file;
|
|
623
|
-
let status = "success";
|
|
624
|
-
if (typeof toolResult === "string" && toolResult.startsWith("Error")) {
|
|
625
|
-
this.handleFailure(tracker, toolCall.name, toolResult, targetFile);
|
|
626
|
-
turnFailureCount++;
|
|
627
|
-
status = "failure";
|
|
628
|
-
}
|
|
629
|
-
else {
|
|
630
|
-
this.handleSuccess(tracker, toolCall.name, durationMs, targetFile, signal);
|
|
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
|
-
}
|
|
664
|
-
this.toolCallCounter++;
|
|
665
|
-
return {
|
|
666
|
-
type: "tool_result",
|
|
667
|
-
tool_use_id: toolCall.id,
|
|
668
|
-
content: toolResult,
|
|
669
|
-
};
|
|
670
|
-
}
|
|
671
|
-
finally {
|
|
672
|
-
pulse.stopHeartbeat();
|
|
673
|
-
}
|
|
674
|
-
};
|
|
675
|
-
const promptProfile = getPromptProfileForDepth(depth);
|
|
676
|
-
const session = new MarieSession(this.provider, this.toolRegistry, saveHistory, messages, tracker, this.providerFactory, promptProfile);
|
|
677
|
-
const toolExecutions = [];
|
|
678
|
-
try {
|
|
679
|
-
const stream = session.executeLoop(messages, signal);
|
|
680
|
-
for await (const event of stream) {
|
|
681
|
-
const now = Date.now();
|
|
682
|
-
lastTokenTime = now;
|
|
683
|
-
pulse.startHeartbeat();
|
|
684
|
-
tracker.recordLog(`[MarieEngine] AI Event: ${event.type}`);
|
|
685
|
-
// RESTORE EVENT ROUTING: Dispatch all stream events
|
|
686
|
-
if (process.env.MARIE_DEBUG) {
|
|
687
|
-
console.log(`[Engine Debug] AI Event: ${event.type}`, event.type === "content_delta"
|
|
688
|
-
? `(${event.text.length} chars)`
|
|
689
|
-
: "");
|
|
690
|
-
}
|
|
691
|
-
dispatcher.dispatch(event);
|
|
692
|
-
if (event.type === "content_delta") {
|
|
693
|
-
turnContent += event.text;
|
|
694
|
-
this.contentBuffer += event.text;
|
|
695
|
-
if (this.contentBuffer.length >= MarieEngine.CONTENT_BUFFER_MAX_BYTES)
|
|
696
|
-
break;
|
|
697
|
-
}
|
|
698
|
-
else if (event.type === "tool_call_delta") {
|
|
699
|
-
let tb = toolBuffer.get(event.index);
|
|
700
|
-
if (!tb) {
|
|
701
|
-
tb = { id: event.id, name: event.name, inputString: "" };
|
|
702
|
-
toolBuffer.set(event.index, tb);
|
|
703
|
-
}
|
|
704
|
-
else {
|
|
705
|
-
// UPDATE: Ensure name and id are captured even if they arrive in later deltas
|
|
706
|
-
if (event.id && !tb.id)
|
|
707
|
-
tb.id = event.id;
|
|
708
|
-
if (event.name && !tb.name)
|
|
709
|
-
tb.name = event.name;
|
|
710
|
-
}
|
|
711
|
-
if (event.argumentsDelta)
|
|
712
|
-
tb.inputString += event.argumentsDelta;
|
|
713
|
-
if (tb.name && this.isLikelyCompleteJson(tb.inputString)) {
|
|
714
|
-
const input = this.tryParseToolInput(tb.inputString, tb.name, parsedInputCache);
|
|
715
|
-
if (!input)
|
|
716
|
-
continue;
|
|
717
|
-
toolBuffer.delete(event.index);
|
|
718
|
-
totalToolCount++;
|
|
719
|
-
if (totalToolCount > MAX_TOOLS_PER_TURN)
|
|
720
|
-
break;
|
|
721
|
-
const target = input.path || input.targetFile || input.file || "GLOBAL";
|
|
722
|
-
const isWrite = [
|
|
723
|
-
"write_to_file",
|
|
724
|
-
"replace_file_content",
|
|
725
|
-
"multi_replace_file_content",
|
|
726
|
-
"run_command",
|
|
727
|
-
"delete_file",
|
|
728
|
-
].includes(tb.name);
|
|
729
|
-
// Execute concurrently
|
|
730
|
-
const executionPromise = (async () => {
|
|
731
|
-
await this.lockManager.acquireLock(target, isWrite, signal, tracker.getRun().runId);
|
|
732
|
-
const promise = executeTool({
|
|
733
|
-
id: tb.id,
|
|
734
|
-
name: tb.name,
|
|
735
|
-
input,
|
|
736
|
-
});
|
|
737
|
-
this.lockManager.registerExecution(target, isWrite, promise, tracker.getRun().runId);
|
|
738
|
-
return await promise;
|
|
739
|
-
})();
|
|
740
|
-
toolExecutions.push(executionPromise);
|
|
741
|
-
}
|
|
742
|
-
}
|
|
743
|
-
else if (event.type === "usage") {
|
|
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
|
-
}
|
|
37
|
+
while (depth <= maxDepth) {
|
|
38
|
+
await this.align(messages);
|
|
39
|
+
const prompt = depth > 0 ? SYSTEM_CONTINUATION_PROMPT : SYSTEM_PROMPT;
|
|
40
|
+
const tools = this.getEffectiveTools();
|
|
41
|
+
const managedMessages = await manageContext(messages, this.provider, this.state);
|
|
42
|
+
let turnContent = "";
|
|
43
|
+
const toolExecutions = [];
|
|
44
|
+
const buffer = new Map();
|
|
45
|
+
await this.provider.createMessageStream({
|
|
46
|
+
model: getModel(),
|
|
47
|
+
messages: managedMessages,
|
|
48
|
+
system: prompt,
|
|
49
|
+
tools,
|
|
50
|
+
}, (event) => {
|
|
51
|
+
this.dispatchPulse(event);
|
|
52
|
+
if (event.type === "content_delta")
|
|
53
|
+
turnContent += event.text;
|
|
54
|
+
else if (event.type === "tool_call_delta")
|
|
55
|
+
this.onToolDelta(event, buffer, toolExecutions, signal);
|
|
56
|
+
else if (event.type === "usage")
|
|
57
|
+
this.onUsage(event);
|
|
58
|
+
}, signal);
|
|
59
|
+
this.flushPulse();
|
|
60
|
+
const results = await Promise.all(toolExecutions);
|
|
61
|
+
accumulatedContent += turnContent;
|
|
62
|
+
if (results.length > 0) {
|
|
63
|
+
messages.push({ role: "user", content: results });
|
|
64
|
+
depth++;
|
|
754
65
|
}
|
|
66
|
+
else
|
|
67
|
+
break;
|
|
755
68
|
}
|
|
69
|
+
return accumulatedContent;
|
|
756
70
|
}
|
|
757
71
|
finally {
|
|
758
|
-
|
|
759
|
-
}
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
if (this.
|
|
788
|
-
this.contentBuffer = "";
|
|
789
|
-
}
|
|
790
|
-
// Await all concurrent tool executions
|
|
791
|
-
const results = await Promise.all(toolExecutions);
|
|
792
|
-
toolResultBlocks.push(...results);
|
|
793
|
-
await this.lockManager.waitForAll();
|
|
794
|
-
if (signal?.aborted) {
|
|
795
|
-
throw new Error("Execution aborted by user after tool execution.");
|
|
796
|
-
}
|
|
797
|
-
// Final tool processing if results were returned
|
|
798
|
-
if (totalToolCount > 0) {
|
|
799
|
-
messages.push({ role: "user", content: toolResultBlocks });
|
|
800
|
-
// ASCENSION EVALUATION: Local decree (NO API CALL)
|
|
801
|
-
const decree = await this.ascendant.evaluate(messages, this.state);
|
|
802
|
-
this.state.lastDecree = decree;
|
|
803
|
-
// Visual feedback only — no state mutations from decree
|
|
804
|
-
tracker.emitEvent({
|
|
805
|
-
type: "reasoning",
|
|
806
|
-
runId: tracker.getRun().runId,
|
|
807
|
-
text: `⚡ Decree: ${decree.strategy} @ ${decree.confidence.toFixed(2)} — ${decree.reason}`,
|
|
808
|
-
elapsedMs: tracker.elapsedMs(),
|
|
809
|
-
});
|
|
810
|
-
if (decree.heroicVow) {
|
|
811
|
-
tracker.emitEvent({
|
|
812
|
-
type: "reasoning",
|
|
813
|
-
runId: tracker.getRun().runId,
|
|
814
|
-
text: `🗡️ VOW: "${decree.heroicVow}"`,
|
|
815
|
-
elapsedMs: tracker.elapsedMs(),
|
|
816
|
-
});
|
|
817
|
-
}
|
|
818
|
-
saveHistory(tracker.getRun()).catch((e) => console.error("History Save Error:", e));
|
|
819
|
-
return await this._executeChatLoop(messages, tracker, saveHistory, signal, turnFailureCount > 0 ? consecutiveErrorCount + 1 : 0, depth + 1, currentAccumulatedContent);
|
|
820
|
-
}
|
|
821
|
-
// End of turn logic
|
|
822
|
-
tracker.setObjectiveStatus("execute_plan", "completed");
|
|
823
|
-
tracker.setObjectiveStatus("deliver_result", "completed");
|
|
824
|
-
tracker.emitEvent({
|
|
825
|
-
type: "reasoning",
|
|
826
|
-
runId: tracker.getRun().runId,
|
|
827
|
-
text: "✨ Convergence achieved. The pattern sparks joy.",
|
|
828
|
-
elapsedMs: tracker.elapsedMs(),
|
|
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
|
-
}
|
|
865
|
-
dispatcher.clear();
|
|
866
|
-
return currentAccumulatedContent;
|
|
867
|
-
}
|
|
868
|
-
handleSuccess(tracker, toolName, durationMs, filePath, signal) {
|
|
869
|
-
this.state.victoryStreak++;
|
|
870
|
-
this.state.totalErrorCount = 0;
|
|
871
|
-
this.state.spiritPressure = Math.min(100, this.state.spiritPressure + 10);
|
|
872
|
-
this.state.techniqueExecutions.push({
|
|
873
|
-
name: toolName,
|
|
874
|
-
durationMs,
|
|
875
|
-
success: true,
|
|
876
|
-
timestamp: Date.now(),
|
|
877
|
-
filePath,
|
|
878
|
-
});
|
|
879
|
-
this.state.toolHistory.push(toolName);
|
|
880
|
-
if (this.state.victoryStreak % 3 === 0) {
|
|
881
|
-
tracker.emitEvent({
|
|
882
|
-
type: "reasoning",
|
|
883
|
-
runId: tracker.getRun().runId,
|
|
884
|
-
text: `✨ Technique Mastery! ${toolName} executed perfectly. Victory Streak: ${this.state.victoryStreak}.`,
|
|
885
|
-
elapsedMs: tracker.elapsedMs(),
|
|
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
|
-
});
|
|
891
|
-
}
|
|
892
|
-
if (filePath && !this.state.recentFiles.includes(filePath)) {
|
|
893
|
-
this.state.recentFiles.push(filePath);
|
|
894
|
-
if (this.state.recentFiles.length > 10)
|
|
895
|
-
this.state.recentFiles.shift();
|
|
896
|
-
// ZENITH AUTONOMY: Proactive Context Anchoring
|
|
897
|
-
this.proactiveContextAnchoring(filePath, tracker, signal);
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
handleFailure(tracker, toolName, error, filePath) {
|
|
901
|
-
this.state.victoryStreak = 0;
|
|
902
|
-
this.state.spiritPressure = Math.max(0, this.state.spiritPressure - 20);
|
|
903
|
-
this.state.techniqueExecutions.push({
|
|
904
|
-
name: toolName,
|
|
905
|
-
durationMs: 0,
|
|
906
|
-
success: false,
|
|
907
|
-
timestamp: Date.now(),
|
|
908
|
-
filePath,
|
|
909
|
-
});
|
|
910
|
-
const hotspotCount = (this.state.errorHotspots[filePath || "system"] || 0) + 1;
|
|
911
|
-
if (filePath) {
|
|
912
|
-
this.state.errorHotspots[filePath] = hotspotCount;
|
|
913
|
-
this.state.totalErrorCount++;
|
|
914
|
-
this.state.lastFailedFile = filePath;
|
|
915
|
-
}
|
|
916
|
-
tracker.emitEvent({
|
|
917
|
-
type: "reasoning",
|
|
918
|
-
runId: tracker.getRun().runId,
|
|
919
|
-
text: `⚠️ Technique Falter! ${toolName} failed in ${filePath || "system"}. Resistance: ${hotspotCount}x. Regrouping...`,
|
|
920
|
-
elapsedMs: tracker.elapsedMs(),
|
|
921
|
-
});
|
|
922
|
-
}
|
|
923
|
-
updateShakyResponse() {
|
|
924
|
-
this.state.shakyResponseDensity = Math.min(1, this.state.shakyResponseDensity + 0.2);
|
|
925
|
-
}
|
|
926
|
-
shouldAutoApprove(toolName, input) {
|
|
927
|
-
const safeTools = [
|
|
928
|
-
"read_file",
|
|
929
|
-
"view_file",
|
|
930
|
-
"list_dir",
|
|
931
|
-
"grep_search",
|
|
932
|
-
"search_web",
|
|
933
|
-
"get_file_diagnostics",
|
|
934
|
-
];
|
|
935
|
-
if (safeTools.includes(toolName))
|
|
936
|
-
return true;
|
|
937
|
-
// SPIRIT PRESSURE & KARMA NEUTERED:
|
|
938
|
-
// We no longer auto-approve based on pressure/streak to prevent "crashes" or unintended loops.
|
|
939
|
-
// The visual feedback remains, but the functional override is disabled.
|
|
940
|
-
return false;
|
|
941
|
-
}
|
|
942
|
-
tryParseToolInput(rawInput, toolName, cache) {
|
|
943
|
-
try {
|
|
944
|
-
return JSON.parse(rawInput);
|
|
945
|
-
}
|
|
946
|
-
catch (e) {
|
|
947
|
-
const repaired = this.toolMender.repairJsonString(rawInput);
|
|
948
|
-
try {
|
|
949
|
-
return JSON.parse(repaired);
|
|
950
|
-
}
|
|
951
|
-
catch (e2) {
|
|
952
|
-
console.warn(`[MarieEngine] JSON Parse Failed for ${toolName}: ${e instanceof Error ? e.message : String(e)}`);
|
|
953
|
-
return null;
|
|
954
|
-
}
|
|
955
|
-
}
|
|
956
|
-
}
|
|
957
|
-
isLikelyCompleteJson(input) {
|
|
958
|
-
const text = input.trim();
|
|
959
|
-
if (!text || (!text.startsWith("{") && !text.startsWith("[")))
|
|
960
|
-
return false;
|
|
961
|
-
let stack = 0;
|
|
962
|
-
let inString = false;
|
|
963
|
-
for (let i = 0; i < text.length; i++) {
|
|
964
|
-
if (text[i] === '"' && text[i - 1] !== "\\")
|
|
965
|
-
inString = !inString;
|
|
966
|
-
if (!inString) {
|
|
967
|
-
if (text[i] === "{" || text[i] === "[")
|
|
968
|
-
stack++;
|
|
969
|
-
if (text[i] === "}" || text[i] === "]")
|
|
970
|
-
stack--;
|
|
971
|
-
}
|
|
972
|
-
}
|
|
973
|
-
return stack === 0 && text.length >= 2;
|
|
974
|
-
}
|
|
975
|
-
suggestSelfHealing(tracker, messages) {
|
|
976
|
-
// SPIRIT PRESSURE & KARMA NEUTERED:
|
|
977
|
-
// We calculate the values for UI visuals but DO NOT inject mandatory recovery protocols.
|
|
978
|
-
// This prevents the "crash" loop the user described.
|
|
979
|
-
const pressure = this.state.spiritPressure;
|
|
980
|
-
const hotspots = Object.entries(this.state.errorHotspots).filter(([_, count]) => count >= 2);
|
|
981
|
-
if (pressure < 40 || hotspots.length > 0) {
|
|
982
|
-
const hotspotFiles = hotspots.map(([f]) => path.basename(f)).join(", ");
|
|
983
|
-
const reason = pressure < 40
|
|
984
|
-
? "Low spirit pressure (instability detected)"
|
|
985
|
-
: `Repeated failures in: ${hotspotFiles}`;
|
|
986
|
-
console.log(`[MarieEngine] Suggestion: ${reason}. (Auto-recovery disabled for stability)`);
|
|
987
|
-
}
|
|
988
|
-
}
|
|
989
|
-
/**
|
|
990
|
-
* REAGENT DISPOSAL: Ensure absolute resource sanctity.
|
|
991
|
-
*/
|
|
992
|
-
dispose() {
|
|
993
|
-
this.disposed = true;
|
|
994
|
-
if (this.activeTurn) {
|
|
995
|
-
// We don't await here as dispose is usually synchronous
|
|
996
|
-
}
|
|
997
|
-
this.pulseService?.cleanup();
|
|
998
|
-
this.pulseService = undefined;
|
|
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
|
-
}
|
|
1008
|
-
}
|
|
1009
|
-
ensurePulseService(tracker) {
|
|
1010
|
-
if (!this.pulseService)
|
|
1011
|
-
this.pulseService = new MariePulseService(tracker);
|
|
1012
|
-
return this.pulseService;
|
|
1013
|
-
}
|
|
1014
|
-
calibrateStrategicTrajectory(decree, tracker) {
|
|
1015
|
-
const run = tracker.getRun();
|
|
1016
|
-
if (decree.strategy === "RESEARCH" ||
|
|
1017
|
-
(decree.urgency === "HIGH" && decree.confidence > 2.0)) {
|
|
1018
|
-
const oldPasses = run.totalPasses || 3;
|
|
1019
|
-
if (oldPasses < 10) {
|
|
1020
|
-
run.totalPasses = oldPasses + 1;
|
|
1021
|
-
tracker.emitEvent({
|
|
1022
|
-
type: "reasoning",
|
|
1023
|
-
runId: run.runId,
|
|
1024
|
-
text: `🌌 ZENITH: Autonomously expanded roadmap to ${run.totalPasses} passes. Focus sharpened: ${decree.reason}`,
|
|
1025
|
-
elapsedMs: tracker.elapsedMs(),
|
|
1026
|
-
});
|
|
1027
|
-
}
|
|
1028
|
-
}
|
|
1029
|
-
}
|
|
1030
|
-
async proactiveContextAnchoring(filePath, tracker, signal) {
|
|
1031
|
-
// Only anchor critical files
|
|
1032
|
-
const isCritical = /Domain|Config|Service|Interface|types/i.test(filePath);
|
|
1033
|
-
if (isCritical) {
|
|
72
|
+
this.cleanupPulse();
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
dispatchPulse(event) {
|
|
76
|
+
if (!this.pulse)
|
|
77
|
+
return;
|
|
78
|
+
switch (event.type) {
|
|
79
|
+
case "content_delta":
|
|
80
|
+
this.pulse.pendingContent += event.text;
|
|
81
|
+
break;
|
|
82
|
+
case "tool_call_delta": break;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
flushPulse() {
|
|
86
|
+
if (!this.pulse || !this.pulse.pendingContent)
|
|
87
|
+
return;
|
|
88
|
+
this.pulse.callbacks?.onStream?.(this.pulse.pendingContent, this.pulse.run.runId);
|
|
89
|
+
this.pulse.pendingContent = "";
|
|
90
|
+
}
|
|
91
|
+
cleanupPulse() { this.pulse = undefined; }
|
|
92
|
+
onToolDelta(event, buffer, executions, signal) {
|
|
93
|
+
let tb = buffer.get(event.index) || { id: event.id, name: event.name, inputString: "" };
|
|
94
|
+
if (event.id)
|
|
95
|
+
tb.id = event.id;
|
|
96
|
+
if (event.name)
|
|
97
|
+
tb.name = event.name;
|
|
98
|
+
if (event.argumentsDelta)
|
|
99
|
+
tb.inputString += event.argumentsDelta;
|
|
100
|
+
buffer.set(event.index, tb);
|
|
101
|
+
if (tb.name && this.isJsonComplete(tb.inputString)) {
|
|
1034
102
|
try {
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
}
|
|
1064
|
-
|
|
1065
|
-
|
|
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
|
-
}
|
|
103
|
+
const input = JSON.parse(tb.inputString);
|
|
104
|
+
buffer.delete(event.index);
|
|
105
|
+
executions.push(this.runTool(tb.id, tb.name, input, signal));
|
|
106
|
+
}
|
|
107
|
+
catch { }
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async runTool(id, name, input, signal) {
|
|
111
|
+
const start = Date.now();
|
|
112
|
+
const tool = this.getTool(name);
|
|
113
|
+
if (!tool)
|
|
114
|
+
return { type: "tool_result", tool_use_id: id, content: `Error: Tool ${name} not found.` };
|
|
115
|
+
this.pulse?.callbacks?.onEvent?.({ type: "tool", runId: this.pulse.run.runId, id, phase: "start", name, input: safeSpread(input), elapsedMs: Date.now() - this.pulse.run.startedAt });
|
|
116
|
+
const result = await tool.execute(input);
|
|
117
|
+
const final = typeof result === "string" ? result : safeStringify(result);
|
|
118
|
+
this.pulse?.callbacks?.onEvent?.({ type: "tool", runId: this.pulse.run.runId, id, phase: "complete", name, message: final.substring(0, 50), elapsedMs: Date.now() - this.pulse.run.startedAt });
|
|
119
|
+
return { type: "tool_result", tool_use_id: id, content: final };
|
|
120
|
+
}
|
|
121
|
+
async align(messages) { }
|
|
122
|
+
onUsage(e) { if (this.pulse)
|
|
123
|
+
this.pulse.run.usage = e.usage; }
|
|
124
|
+
getEffectiveTools() { return this.toolRegistry ? this.toolRegistry.getRegisteredTools() : getRegisteredTools(); }
|
|
125
|
+
isJsonComplete(s) { try {
|
|
126
|
+
JSON.parse(s);
|
|
127
|
+
return true;
|
|
128
|
+
}
|
|
129
|
+
catch {
|
|
130
|
+
return false;
|
|
131
|
+
} }
|
|
132
|
+
getTool(name) { return this.toolRegistry ? this.toolRegistry.get(name) : getTool(name); }
|
|
133
|
+
dispose() { this.disposed = true; }
|
|
1096
134
|
}
|
|
1097
135
|
//# sourceMappingURL=MarieEngine.js.map
|