@monoes/monomindcli 1.14.7 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/reengineer-squad/boss.md +113 -0
- package/.claude/agents/reengineer-squad/critic-architect.md +132 -0
- package/.claude/agents/reengineer-squad/git-manager.md +145 -0
- package/.claude/agents/reengineer-squad/idea-generator.md +95 -0
- package/.claude/agents/reengineer-squad/implementer.md +112 -0
- package/.claude/agents/reengineer-squad/integration-planner.md +112 -0
- package/.claude/agents/reengineer-squad/source-analyst.md +103 -0
- package/.claude/agents/reengineer-squad/target-analyst.md +118 -0
- package/.claude/agents/reengineer-squad/tester.md +105 -0
- package/.claude/commands/mastermind/master.md +35 -14
- package/.claude/helpers/handlers/capture-handler.cjs +155 -18
- package/.claude/helpers/monolean-activate.cjs +20 -0
- package/.claude/helpers/monolean-config.cjs +76 -0
- package/.claude/helpers/monolean-instructions.cjs +109 -0
- package/.claude/helpers/monolean-propagate.cjs +9 -0
- package/.claude/helpers/monolean-tracker.cjs +18 -0
- package/.claude/helpers/skill-registry.json +2 -2
- package/.claude/skills/agent-browser-testing/SKILL.md +301 -18
- package/.claude/skills/mastermind/runorg.md +69 -23
- package/.claude/skills/monodesign/SKILL.md +32 -1
- package/.claude/skills/monodesign/adapt.md +53 -0
- package/.claude/skills/monodesign/agents/monodesign-asset-producer.md +100 -0
- package/.claude/skills/monodesign/animate.md +65 -0
- package/.claude/skills/monodesign/audit.md +89 -0
- package/.claude/skills/monodesign/bolder.md +50 -0
- package/.claude/skills/monodesign/clarify.md +64 -0
- package/.claude/skills/monodesign/colorize.md +68 -0
- package/.claude/skills/monodesign/craft.md +51 -0
- package/.claude/skills/monodesign/critique.md +66 -0
- package/.claude/skills/monodesign/delight.md +47 -0
- package/.claude/skills/monodesign/distill.md +56 -0
- package/.claude/skills/monodesign/document.md +80 -0
- package/.claude/skills/monodesign/extract.md +74 -0
- package/.claude/skills/monodesign/harden.md +65 -0
- package/.claude/skills/monodesign/live.md +59 -0
- package/.claude/skills/monodesign/onboard.md +50 -0
- package/.claude/skills/monodesign/optimize.md +64 -0
- package/.claude/skills/monodesign/overdrive.md +56 -0
- package/.claude/skills/monodesign/polish.md +68 -0
- package/.claude/skills/monodesign/quieter.md +57 -0
- package/.claude/skills/monodesign/reference/antipatterns-catalog.md +248 -76
- package/.claude/skills/monodesign/reference/codex.md +107 -0
- package/.claude/skills/monodesign/reference/craft.md +3 -0
- package/.claude/skills/monodesign/reference/hooks.md +99 -0
- package/.claude/skills/monodesign/reference/image-prompts.md +12 -0
- package/.claude/skills/monodesign/shape.md +71 -0
- package/.claude/skills/monodesign/teach.md +69 -0
- package/.claude/skills/monodesign/typeset.md +59 -0
- package/.claude/skills/monolean/SKILL.md +118 -0
- package/.claude/skills/monolean-audit/SKILL.md +41 -0
- package/.claude/skills/monolean-debt/SKILL.md +46 -0
- package/.claude/skills/monolean-help/SKILL.md +60 -0
- package/.claude/skills/monolean-review/SKILL.md +57 -0
- package/bin/cli.js +3 -1
- package/dist/dashboard/server.js +137 -0
- package/dist/src/__tests__/browse-adapters.test.d.ts +2 -0
- package/dist/src/__tests__/browse-adapters.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-adapters.test.js +51 -0
- package/dist/src/__tests__/browse-adapters.test.js.map +1 -0
- package/dist/src/__tests__/browse-analyzer.test.d.ts +2 -0
- package/dist/src/__tests__/browse-analyzer.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-analyzer.test.js +68 -0
- package/dist/src/__tests__/browse-analyzer.test.js.map +1 -0
- package/dist/src/__tests__/browse-builtin-handlers.test.d.ts +2 -0
- package/dist/src/__tests__/browse-builtin-handlers.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-builtin-handlers.test.js +139 -0
- package/dist/src/__tests__/browse-builtin-handlers.test.js.map +1 -0
- package/dist/src/__tests__/browse-cdp.test.d.ts +2 -0
- package/dist/src/__tests__/browse-cdp.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-cdp.test.js +169 -0
- package/dist/src/__tests__/browse-cdp.test.js.map +1 -0
- package/dist/src/__tests__/browse-dashboard.test.d.ts +2 -0
- package/dist/src/__tests__/browse-dashboard.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-dashboard.test.js +179 -0
- package/dist/src/__tests__/browse-dashboard.test.js.map +1 -0
- package/dist/src/__tests__/browse-engine.test.d.ts +2 -0
- package/dist/src/__tests__/browse-engine.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-engine.test.js +122 -0
- package/dist/src/__tests__/browse-engine.test.js.map +1 -0
- package/dist/src/__tests__/browse-expression.test.d.ts +2 -0
- package/dist/src/__tests__/browse-expression.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-expression.test.js +54 -0
- package/dist/src/__tests__/browse-expression.test.js.map +1 -0
- package/dist/src/__tests__/browse-store.test.d.ts +2 -0
- package/dist/src/__tests__/browse-store.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-store.test.js +99 -0
- package/dist/src/__tests__/browse-store.test.js.map +1 -0
- package/dist/src/__tests__/browse-workflow-types.test.d.ts +2 -0
- package/dist/src/__tests__/browse-workflow-types.test.d.ts.map +1 -0
- package/dist/src/__tests__/browse-workflow-types.test.js +33 -0
- package/dist/src/__tests__/browse-workflow-types.test.js.map +1 -0
- package/dist/src/browser/action-builder/analyzer.d.ts +11 -0
- package/dist/src/browser/action-builder/analyzer.d.ts.map +1 -0
- package/dist/src/browser/action-builder/analyzer.js +71 -0
- package/dist/src/browser/action-builder/analyzer.js.map +1 -0
- package/dist/src/browser/action-builder/types.d.ts +47 -0
- package/dist/src/browser/action-builder/types.d.ts.map +1 -0
- package/dist/src/browser/action-builder/types.js +2 -0
- package/dist/src/browser/action-builder/types.js.map +1 -0
- package/dist/src/browser/adapters/gemini.d.ts +3 -0
- package/dist/src/browser/adapters/gemini.d.ts.map +1 -0
- package/dist/src/browser/adapters/gemini.js +16 -0
- package/dist/src/browser/adapters/gemini.js.map +1 -0
- package/dist/src/browser/adapters/google.d.ts +3 -0
- package/dist/src/browser/adapters/google.d.ts.map +1 -0
- package/dist/src/browser/adapters/google.js +17 -0
- package/dist/src/browser/adapters/google.js.map +1 -0
- package/dist/src/browser/adapters/index.d.ts +19 -0
- package/dist/src/browser/adapters/index.d.ts.map +1 -0
- package/dist/src/browser/adapters/index.js +23 -0
- package/dist/src/browser/adapters/index.js.map +1 -0
- package/dist/src/browser/adapters/instagram.d.ts +3 -0
- package/dist/src/browser/adapters/instagram.d.ts.map +1 -0
- package/dist/src/browser/adapters/instagram.js +17 -0
- package/dist/src/browser/adapters/instagram.js.map +1 -0
- package/dist/src/browser/adapters/linkedin.d.ts +3 -0
- package/dist/src/browser/adapters/linkedin.d.ts.map +1 -0
- package/dist/src/browser/adapters/linkedin.js +19 -0
- package/dist/src/browser/adapters/linkedin.js.map +1 -0
- package/dist/src/browser/adapters/microsoft.d.ts +3 -0
- package/dist/src/browser/adapters/microsoft.d.ts.map +1 -0
- package/dist/src/browser/adapters/microsoft.js +16 -0
- package/dist/src/browser/adapters/microsoft.js.map +1 -0
- package/dist/src/browser/adapters/x.d.ts +3 -0
- package/dist/src/browser/adapters/x.d.ts.map +1 -0
- package/dist/src/browser/adapters/x.js +19 -0
- package/dist/src/browser/adapters/x.js.map +1 -0
- package/dist/src/browser/dashboard/api-types.d.ts +50 -0
- package/dist/src/browser/dashboard/api-types.d.ts.map +1 -0
- package/dist/src/browser/dashboard/api-types.js +14 -0
- package/dist/src/browser/dashboard/api-types.js.map +1 -0
- package/dist/src/browser/dashboard/server.d.ts +9 -0
- package/dist/src/browser/dashboard/server.d.ts.map +1 -0
- package/dist/src/browser/dashboard/server.js +62 -0
- package/dist/src/browser/dashboard/server.js.map +1 -0
- package/dist/src/browser/dashboard/ui.html +1811 -0
- package/dist/src/browser/workflow/builtin-handlers.d.ts +3 -0
- package/dist/src/browser/workflow/builtin-handlers.d.ts.map +1 -0
- package/dist/src/browser/workflow/builtin-handlers.js +343 -0
- package/dist/src/browser/workflow/builtin-handlers.js.map +1 -0
- package/dist/src/browser/workflow/engine.d.ts +15 -0
- package/dist/src/browser/workflow/engine.d.ts.map +1 -0
- package/dist/src/browser/workflow/engine.js +127 -0
- package/dist/src/browser/workflow/engine.js.map +1 -0
- package/dist/src/browser/workflow/expression.d.ts +4 -0
- package/dist/src/browser/workflow/expression.d.ts.map +1 -0
- package/dist/src/browser/workflow/expression.js +64 -0
- package/dist/src/browser/workflow/expression.js.map +1 -0
- package/dist/src/browser/workflow/store.d.ts +24 -0
- package/dist/src/browser/workflow/store.d.ts.map +1 -0
- package/dist/src/browser/workflow/store.js +145 -0
- package/dist/src/browser/workflow/store.js.map +1 -0
- package/dist/src/browser/workflow/types.d.ts +48 -0
- package/dist/src/browser/workflow/types.d.ts.map +1 -0
- package/dist/src/browser/workflow/types.js +2 -0
- package/dist/src/browser/workflow/types.js.map +1 -0
- package/dist/src/commands/browse-action.d.ts +4 -0
- package/dist/src/commands/browse-action.d.ts.map +1 -0
- package/dist/src/commands/browse-action.js +151 -0
- package/dist/src/commands/browse-action.js.map +1 -0
- package/dist/src/commands/browse-platform.d.ts +4 -0
- package/dist/src/commands/browse-platform.d.ts.map +1 -0
- package/dist/src/commands/browse-platform.js +117 -0
- package/dist/src/commands/browse-platform.js.map +1 -0
- package/dist/src/commands/browse-workflow.d.ts +4 -0
- package/dist/src/commands/browse-workflow.d.ts.map +1 -0
- package/dist/src/commands/browse-workflow.js +153 -0
- package/dist/src/commands/browse-workflow.js.map +1 -0
- package/dist/src/commands/browse.d.ts +10 -6
- package/dist/src/commands/browse.d.ts.map +1 -1
- package/dist/src/commands/browse.js +11 -2154
- package/dist/src/commands/browse.js.map +1 -1
- package/dist/src/commands/design-detect.d.ts +21 -0
- package/dist/src/commands/design-detect.d.ts.map +1 -0
- package/dist/src/commands/design-detect.js +127 -0
- package/dist/src/commands/design-detect.js.map +1 -0
- package/dist/src/commands/design-palette.d.ts +22 -0
- package/dist/src/commands/design-palette.d.ts.map +1 -0
- package/dist/src/commands/design-palette.js +539 -0
- package/dist/src/commands/design-palette.js.map +1 -0
- package/dist/src/commands/hooks-core-commands.d.ts +10 -0
- package/dist/src/commands/hooks-core-commands.d.ts.map +1 -0
- package/dist/src/commands/hooks-core-commands.js +377 -0
- package/dist/src/commands/hooks-core-commands.js.map +1 -0
- package/dist/src/commands/hooks-coverage-commands.d.ts +12 -0
- package/dist/src/commands/hooks-coverage-commands.d.ts.map +1 -0
- package/dist/src/commands/hooks-coverage-commands.js +1217 -0
- package/dist/src/commands/hooks-coverage-commands.js.map +1 -0
- package/dist/src/commands/hooks-coverage-utils.d.ts +42 -0
- package/dist/src/commands/hooks-coverage-utils.d.ts.map +1 -0
- package/dist/src/commands/hooks-coverage-utils.js +220 -0
- package/dist/src/commands/hooks-coverage-utils.js.map +1 -0
- package/dist/src/commands/hooks-extended-commands.d.ts +14 -0
- package/dist/src/commands/hooks-extended-commands.d.ts.map +1 -0
- package/dist/src/commands/hooks-extended-commands.js +579 -0
- package/dist/src/commands/hooks-extended-commands.js.map +1 -0
- package/dist/src/commands/hooks-formatting.d.ts +13 -0
- package/dist/src/commands/hooks-formatting.d.ts.map +1 -0
- package/dist/src/commands/hooks-formatting.js +42 -0
- package/dist/src/commands/hooks-formatting.js.map +1 -0
- package/dist/src/commands/hooks-routing-commands.d.ts +15 -0
- package/dist/src/commands/hooks-routing-commands.d.ts.map +1 -0
- package/dist/src/commands/hooks-routing-commands.js +723 -0
- package/dist/src/commands/hooks-routing-commands.js.map +1 -0
- package/dist/src/commands/hooks-workers.d.ts +9 -0
- package/dist/src/commands/hooks-workers.d.ts.map +1 -0
- package/dist/src/commands/hooks-workers.js +782 -0
- package/dist/src/commands/hooks-workers.js.map +1 -0
- package/dist/src/commands/hooks.d.ts +8 -0
- package/dist/src/commands/hooks.d.ts.map +1 -1
- package/dist/src/commands/hooks.js +179 -4103
- package/dist/src/commands/hooks.js.map +1 -1
- package/dist/src/commands/index.d.ts +1 -0
- package/dist/src/commands/index.d.ts.map +1 -1
- package/dist/src/commands/index.js +6 -0
- package/dist/src/commands/index.js.map +1 -1
- package/dist/src/commands/org.d.ts.map +1 -1
- package/dist/src/commands/org.js +14 -15
- package/dist/src/commands/org.js.map +1 -1
- package/dist/src/commands/tokens.d.ts.map +1 -1
- package/dist/src/commands/tokens.js +77 -1
- package/dist/src/commands/tokens.js.map +1 -1
- package/dist/src/init/executor.d.ts.map +1 -1
- package/dist/src/init/executor.js +18 -8
- package/dist/src/init/executor.js.map +1 -1
- package/dist/src/init/settings-generator.d.ts.map +1 -1
- package/dist/src/init/settings-generator.js +39 -5
- package/dist/src/init/settings-generator.js.map +1 -1
- package/dist/src/init/statusline-generator.d.ts.map +1 -1
- package/dist/src/init/statusline-generator.js +25 -5
- package/dist/src/init/statusline-generator.js.map +1 -1
- package/dist/src/mcp-tools/browser-tools.d.ts +3 -5
- package/dist/src/mcp-tools/browser-tools.d.ts.map +1 -1
- package/dist/src/mcp-tools/browser-tools.js +619 -326
- package/dist/src/mcp-tools/browser-tools.js.map +1 -1
- package/dist/src/mcp-tools/hooks-embedding.d.ts +161 -0
- package/dist/src/mcp-tools/hooks-embedding.d.ts.map +1 -0
- package/dist/src/mcp-tools/hooks-embedding.js +506 -0
- package/dist/src/mcp-tools/hooks-embedding.js.map +1 -0
- package/dist/src/mcp-tools/hooks-intelligence.d.ts +26 -0
- package/dist/src/mcp-tools/hooks-intelligence.d.ts.map +1 -0
- package/dist/src/mcp-tools/hooks-intelligence.js +1328 -0
- package/dist/src/mcp-tools/hooks-intelligence.js.map +1 -0
- package/dist/src/mcp-tools/hooks-routing.d.ts +27 -0
- package/dist/src/mcp-tools/hooks-routing.d.ts.map +1 -0
- package/dist/src/mcp-tools/hooks-routing.js +1591 -0
- package/dist/src/mcp-tools/hooks-routing.js.map +1 -0
- package/dist/src/mcp-tools/hooks-tools.d.ts +3 -38
- package/dist/src/mcp-tools/hooks-tools.d.ts.map +1 -1
- package/dist/src/mcp-tools/hooks-tools.js +5 -3393
- package/dist/src/mcp-tools/hooks-tools.js.map +1 -1
- package/dist/src/mcp-tools/monograph-tools.d.ts.map +1 -1
- package/dist/src/mcp-tools/monograph-tools.js +24 -14
- package/dist/src/mcp-tools/monograph-tools.js.map +1 -1
- package/dist/src/mcp-tools/workflow-tools.d.ts.map +1 -1
- package/dist/src/mcp-tools/workflow-tools.js +54 -1
- package/dist/src/mcp-tools/workflow-tools.js.map +1 -1
- package/dist/src/memory/embedding-operations.d.ts +58 -0
- package/dist/src/memory/embedding-operations.d.ts.map +1 -0
- package/dist/src/memory/embedding-operations.js +299 -0
- package/dist/src/memory/embedding-operations.js.map +1 -0
- package/dist/src/memory/ewc-consolidation.d.ts.map +1 -1
- package/dist/src/memory/ewc-consolidation.js +37 -3
- package/dist/src/memory/ewc-consolidation.js.map +1 -1
- package/dist/src/memory/hnsw-operations.d.ts +130 -0
- package/dist/src/memory/hnsw-operations.d.ts.map +1 -0
- package/dist/src/memory/hnsw-operations.js +400 -0
- package/dist/src/memory/hnsw-operations.js.map +1 -0
- package/dist/src/memory/intelligence.d.ts.map +1 -1
- package/dist/src/memory/intelligence.js +42 -23
- package/dist/src/memory/intelligence.js.map +1 -1
- package/dist/src/memory/memory-bridge.d.ts.map +1 -1
- package/dist/src/memory/memory-bridge.js +52 -8
- package/dist/src/memory/memory-bridge.js.map +1 -1
- package/dist/src/memory/memory-crud.d.ts +67 -0
- package/dist/src/memory/memory-crud.d.ts.map +1 -0
- package/dist/src/memory/memory-crud.js +415 -0
- package/dist/src/memory/memory-crud.js.map +1 -0
- package/dist/src/memory/memory-initializer.d.ts +9 -322
- package/dist/src/memory/memory-initializer.d.ts.map +1 -1
- package/dist/src/memory/memory-initializer.js +17 -1794
- package/dist/src/memory/memory-initializer.js.map +1 -1
- package/dist/src/memory/memory-migrations.d.ts +30 -0
- package/dist/src/memory/memory-migrations.d.ts.map +1 -0
- package/dist/src/memory/memory-migrations.js +134 -0
- package/dist/src/memory/memory-migrations.js.map +1 -0
- package/dist/src/memory/memory-read.d.ts +78 -0
- package/dist/src/memory/memory-read.d.ts.map +1 -0
- package/dist/src/memory/memory-read.js +331 -0
- package/dist/src/memory/memory-read.js.map +1 -0
- package/dist/src/memory/memory-schema.d.ts +13 -0
- package/dist/src/memory/memory-schema.d.ts.map +1 -0
- package/dist/src/memory/memory-schema.js +167 -0
- package/dist/src/memory/memory-schema.js.map +1 -0
- package/dist/src/memory/sona-optimizer.d.ts.map +1 -1
- package/dist/src/memory/sona-optimizer.js +37 -4
- package/dist/src/memory/sona-optimizer.js.map +1 -1
- package/dist/src/monovector/route-outcomes.d.ts.map +1 -1
- package/dist/src/monovector/route-outcomes.js +16 -6
- package/dist/src/monovector/route-outcomes.js.map +1 -1
- package/dist/src/pricing/model-pricing.d.ts +41 -0
- package/dist/src/pricing/model-pricing.d.ts.map +1 -0
- package/dist/src/pricing/model-pricing.js +61 -0
- package/dist/src/pricing/model-pricing.js.map +1 -0
- package/dist/src/ui/.monomind/capture/active-run.json +1 -0
- package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.convs.jsonl +3 -0
- package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/real-events-1782290897.jsonl +11 -0
- package/dist/src/ui/.monomind/orgs/system-trial-qa/runs/rigid-qa-restart-1782288201.jsonl +540 -0
- package/dist/src/ui/.monomind/orgs/system-trial-qa-threads.jsonl +3 -0
- package/dist/src/ui/.monomind/orgs/test-event-fix/runs/rigid-qa-restart-1782288201.jsonl +2 -0
- package/dist/src/ui/MODULARIZATION_PLAN.md +79 -0
- package/dist/src/ui/collector.mjs +23 -13
- package/dist/src/ui/dashboard.html +1652 -13
- package/dist/src/ui/data/known-projects.json +1 -0
- package/dist/src/ui/data/mastermind-events.jsonl +553 -0
- package/dist/src/ui/data/sessions/_index.json +1 -0
- package/dist/src/ui/data/sessions/final-sess-001.jsonl +542 -0
- package/dist/src/ui/data/unknown-events.jsonl +1 -0
- package/dist/src/ui/orgs.html +154 -10
- package/dist/src/ui/server.mjs +1131 -168
- package/dist/src/ui/sse-manager.mjs +119 -0
- package/dist/src/update/checker.js +1 -1
- package/dist/src/update/checker.js.map +1 -1
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/dist/workflow/builtin-handlers.js +321 -0
- package/dist/workflow/engine.js +253 -0
- package/dist/workflow/expression.js +98 -0
- package/dist/workflow/types.js +2 -0
- package/package.json +8 -5
|
@@ -0,0 +1,1328 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hooks Intelligence & Worker MCP Tools
|
|
3
|
+
* MCP tool implementations for intelligence reset, trajectories, patterns,
|
|
4
|
+
* intelligence stats/learn/attention, worker dispatch/status/detect/cancel,
|
|
5
|
+
* and model routing.
|
|
6
|
+
* Extracted from hooks-tools.ts.
|
|
7
|
+
*/
|
|
8
|
+
import { existsSync, readdirSync, unlinkSync } from 'fs';
|
|
9
|
+
import { join } from 'path';
|
|
10
|
+
import { getProjectCwd } from './types.js';
|
|
11
|
+
import { activeTrajectories, getRealSearchFunction, getRealStoreFunction, getSONAOptimizer, getEWCConsolidator, getIntelligenceStatsFromMemory, } from './hooks-embedding.js';
|
|
12
|
+
// Intelligence reset hook
|
|
13
|
+
export const hooksIntelligenceReset = {
|
|
14
|
+
name: 'hooks_intelligence-reset',
|
|
15
|
+
description: 'Reset intelligence learning state',
|
|
16
|
+
inputSchema: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {},
|
|
19
|
+
},
|
|
20
|
+
handler: async () => {
|
|
21
|
+
const cwd = getProjectCwd();
|
|
22
|
+
const cleared = {
|
|
23
|
+
trajectories: 0,
|
|
24
|
+
patterns: 0,
|
|
25
|
+
dataFiles: 0,
|
|
26
|
+
neuralFiles: 0,
|
|
27
|
+
};
|
|
28
|
+
const deletedFiles = [];
|
|
29
|
+
// Clear intelligence data files if they exist
|
|
30
|
+
const dataFiles = [
|
|
31
|
+
join(cwd, '.monomind', 'data', 'auto-memory-store.json'),
|
|
32
|
+
join(cwd, '.monomind', 'data', 'graph-state.json'),
|
|
33
|
+
join(cwd, '.monomind', 'data', 'ranked-context.json'),
|
|
34
|
+
];
|
|
35
|
+
for (const filePath of dataFiles) {
|
|
36
|
+
if (existsSync(filePath)) {
|
|
37
|
+
try {
|
|
38
|
+
unlinkSync(filePath);
|
|
39
|
+
cleared.dataFiles++;
|
|
40
|
+
deletedFiles.push(filePath);
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
// Skip files that cannot be deleted
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
// Clear neural directory if it exists
|
|
48
|
+
const neuralDir = join(cwd, '.monomind', 'neural');
|
|
49
|
+
if (existsSync(neuralDir)) {
|
|
50
|
+
try {
|
|
51
|
+
const files = readdirSync(neuralDir);
|
|
52
|
+
for (const file of files) {
|
|
53
|
+
try {
|
|
54
|
+
const filePath = join(neuralDir, file);
|
|
55
|
+
unlinkSync(filePath);
|
|
56
|
+
cleared.neuralFiles++;
|
|
57
|
+
deletedFiles.push(filePath);
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Skip files that cannot be deleted
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Directory read failed
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
// Clear in-memory trajectories
|
|
69
|
+
cleared.trajectories = activeTrajectories.size;
|
|
70
|
+
activeTrajectories.clear();
|
|
71
|
+
return {
|
|
72
|
+
reset: true,
|
|
73
|
+
cleared,
|
|
74
|
+
deletedFiles,
|
|
75
|
+
timestamp: new Date().toISOString(),
|
|
76
|
+
};
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
// Intelligence trajectory hooks - REAL implementation using activeTrajectories
|
|
80
|
+
export const hooksTrajectoryStart = {
|
|
81
|
+
name: 'hooks_intelligence_trajectory-start',
|
|
82
|
+
description: 'Begin SONA trajectory for reinforcement learning',
|
|
83
|
+
inputSchema: {
|
|
84
|
+
type: 'object',
|
|
85
|
+
properties: {
|
|
86
|
+
task: { type: 'string', description: 'Task description' },
|
|
87
|
+
agent: { type: 'string', description: 'Agent type' },
|
|
88
|
+
},
|
|
89
|
+
required: ['task'],
|
|
90
|
+
},
|
|
91
|
+
handler: async (params) => {
|
|
92
|
+
// Cap task and agent lengths to prevent the trajectory map from accumulating
|
|
93
|
+
// large strings (up to MAX_TRAJECTORIES × uncapped length = potential GB of RAM).
|
|
94
|
+
const MAX_TASK_LEN = 4 * 1024; // 4 KB — same cap as trajectory-step fields
|
|
95
|
+
const MAX_AGENT_LEN = 256;
|
|
96
|
+
const rawTask = params.task;
|
|
97
|
+
const task = typeof rawTask === 'string' && rawTask.length > MAX_TASK_LEN
|
|
98
|
+
? rawTask.slice(0, MAX_TASK_LEN)
|
|
99
|
+
: rawTask;
|
|
100
|
+
const rawAgent = params.agent || 'coder';
|
|
101
|
+
const agent = typeof rawAgent === 'string' && rawAgent.length > MAX_AGENT_LEN
|
|
102
|
+
? rawAgent.slice(0, MAX_AGENT_LEN)
|
|
103
|
+
: rawAgent;
|
|
104
|
+
const trajectoryId = `traj-${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
105
|
+
const startedAt = new Date().toISOString();
|
|
106
|
+
// Create real trajectory entry in memory
|
|
107
|
+
const trajectory = {
|
|
108
|
+
id: trajectoryId,
|
|
109
|
+
task,
|
|
110
|
+
agent,
|
|
111
|
+
steps: [],
|
|
112
|
+
startedAt,
|
|
113
|
+
};
|
|
114
|
+
const MAX_TRAJECTORIES = 10000;
|
|
115
|
+
if (activeTrajectories.size >= MAX_TRAJECTORIES) {
|
|
116
|
+
// Evict the oldest trajectory
|
|
117
|
+
const oldest = activeTrajectories.keys().next().value;
|
|
118
|
+
if (oldest)
|
|
119
|
+
activeTrajectories.delete(oldest);
|
|
120
|
+
}
|
|
121
|
+
activeTrajectories.set(trajectoryId, trajectory);
|
|
122
|
+
return {
|
|
123
|
+
trajectoryId,
|
|
124
|
+
task,
|
|
125
|
+
agent,
|
|
126
|
+
started: startedAt,
|
|
127
|
+
status: 'recording',
|
|
128
|
+
implementation: 'real-trajectory-tracking',
|
|
129
|
+
activeCount: activeTrajectories.size,
|
|
130
|
+
};
|
|
131
|
+
},
|
|
132
|
+
};
|
|
133
|
+
export const hooksTrajectoryStep = {
|
|
134
|
+
name: 'hooks_intelligence_trajectory-step',
|
|
135
|
+
description: 'Record step in trajectory for reinforcement learning',
|
|
136
|
+
inputSchema: {
|
|
137
|
+
type: 'object',
|
|
138
|
+
properties: {
|
|
139
|
+
trajectoryId: { type: 'string', description: 'Trajectory ID' },
|
|
140
|
+
action: { type: 'string', description: 'Action taken' },
|
|
141
|
+
result: { type: 'string', description: 'Action result' },
|
|
142
|
+
quality: { type: 'number', description: 'Quality score (0-1)' },
|
|
143
|
+
},
|
|
144
|
+
required: ['trajectoryId', 'action'],
|
|
145
|
+
},
|
|
146
|
+
handler: async (params) => {
|
|
147
|
+
const trajectoryId = params.trajectoryId;
|
|
148
|
+
// Cap action and result strings to prevent unbounded in-memory growth when
|
|
149
|
+
// trajectory-step is called many times with large payloads.
|
|
150
|
+
const MAX_STEP_STRING_LEN = 4 * 1024; // 4 KB per field
|
|
151
|
+
const MAX_STEPS_PER_TRAJECTORY = 1000;
|
|
152
|
+
const rawAction = params.action;
|
|
153
|
+
const rawResult = params.result || 'success';
|
|
154
|
+
const action = typeof rawAction === 'string' && rawAction.length > MAX_STEP_STRING_LEN
|
|
155
|
+
? rawAction.slice(0, MAX_STEP_STRING_LEN)
|
|
156
|
+
: rawAction;
|
|
157
|
+
const result = typeof rawResult === 'string' && rawResult.length > MAX_STEP_STRING_LEN
|
|
158
|
+
? rawResult.slice(0, MAX_STEP_STRING_LEN)
|
|
159
|
+
: rawResult;
|
|
160
|
+
const quality = params.quality || 0.85;
|
|
161
|
+
const timestamp = new Date().toISOString();
|
|
162
|
+
const stepId = `step-${Date.now()}`;
|
|
163
|
+
// Add step to real trajectory if it exists
|
|
164
|
+
const trajectory = activeTrajectories.get(trajectoryId);
|
|
165
|
+
if (trajectory) {
|
|
166
|
+
if (trajectory.steps.length >= MAX_STEPS_PER_TRAJECTORY) {
|
|
167
|
+
// Drop the oldest step to keep the array bounded
|
|
168
|
+
trajectory.steps.shift();
|
|
169
|
+
}
|
|
170
|
+
trajectory.steps.push({
|
|
171
|
+
action,
|
|
172
|
+
result,
|
|
173
|
+
quality,
|
|
174
|
+
timestamp,
|
|
175
|
+
});
|
|
176
|
+
}
|
|
177
|
+
return {
|
|
178
|
+
trajectoryId,
|
|
179
|
+
stepId,
|
|
180
|
+
action,
|
|
181
|
+
result,
|
|
182
|
+
quality,
|
|
183
|
+
recorded: !!trajectory,
|
|
184
|
+
timestamp,
|
|
185
|
+
totalSteps: trajectory?.steps.length || 0,
|
|
186
|
+
implementation: trajectory ? 'real-step-recording' : 'trajectory-not-found',
|
|
187
|
+
};
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
export const hooksTrajectoryEnd = {
|
|
191
|
+
name: 'hooks_intelligence_trajectory-end',
|
|
192
|
+
description: 'End trajectory and trigger SONA learning with EWC++',
|
|
193
|
+
inputSchema: {
|
|
194
|
+
type: 'object',
|
|
195
|
+
properties: {
|
|
196
|
+
trajectoryId: { type: 'string', description: 'Trajectory ID' },
|
|
197
|
+
success: { type: 'boolean', description: 'Overall success' },
|
|
198
|
+
feedback: { type: 'string', description: 'Optional feedback' },
|
|
199
|
+
},
|
|
200
|
+
required: ['trajectoryId'],
|
|
201
|
+
},
|
|
202
|
+
handler: async (params) => {
|
|
203
|
+
const trajectoryId = params.trajectoryId;
|
|
204
|
+
const success = params.success !== false;
|
|
205
|
+
const feedback = params.feedback;
|
|
206
|
+
const endedAt = new Date().toISOString();
|
|
207
|
+
const startTime = Date.now();
|
|
208
|
+
// Get and finalize real trajectory
|
|
209
|
+
const trajectory = activeTrajectories.get(trajectoryId);
|
|
210
|
+
let persistResult = { success: false };
|
|
211
|
+
if (trajectory) {
|
|
212
|
+
trajectory.success = success;
|
|
213
|
+
trajectory.endedAt = endedAt;
|
|
214
|
+
// Persist trajectory to database using real store
|
|
215
|
+
const storeFn = await getRealStoreFunction();
|
|
216
|
+
if (storeFn) {
|
|
217
|
+
try {
|
|
218
|
+
// Create trajectory summary for embedding
|
|
219
|
+
const summary = `Task: ${trajectory.task} | Agent: ${trajectory.agent} | Steps: ${trajectory.steps.length} | Success: ${success}${feedback ? ` | Feedback: ${feedback}` : ''}`;
|
|
220
|
+
persistResult = await storeFn({
|
|
221
|
+
key: `trajectory-${trajectoryId}`,
|
|
222
|
+
value: JSON.stringify({
|
|
223
|
+
...trajectory,
|
|
224
|
+
feedback,
|
|
225
|
+
}),
|
|
226
|
+
namespace: 'trajectories',
|
|
227
|
+
generateEmbeddingFlag: true, // Generate embedding for semantic search
|
|
228
|
+
tags: [trajectory.agent, success ? 'success' : 'failure', 'sona-trajectory'],
|
|
229
|
+
});
|
|
230
|
+
}
|
|
231
|
+
catch (error) {
|
|
232
|
+
persistResult = { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// Remove from active trajectories
|
|
236
|
+
activeTrajectories.delete(trajectoryId);
|
|
237
|
+
}
|
|
238
|
+
// SONA Learning - process trajectory outcome for routing optimization
|
|
239
|
+
let sonaResult = {
|
|
240
|
+
learned: false, patternKey: '', confidence: 0
|
|
241
|
+
};
|
|
242
|
+
let ewcResult = {
|
|
243
|
+
consolidated: false, penalty: 0
|
|
244
|
+
};
|
|
245
|
+
if (trajectory && persistResult.success) {
|
|
246
|
+
// Try SONA learning
|
|
247
|
+
const sona = await getSONAOptimizer();
|
|
248
|
+
if (sona) {
|
|
249
|
+
try {
|
|
250
|
+
const outcome = {
|
|
251
|
+
trajectoryId,
|
|
252
|
+
task: trajectory.task,
|
|
253
|
+
agent: trajectory.agent,
|
|
254
|
+
success,
|
|
255
|
+
steps: trajectory.steps,
|
|
256
|
+
feedback,
|
|
257
|
+
duration: trajectory.startedAt
|
|
258
|
+
? new Date(endedAt).getTime() - new Date(trajectory.startedAt).getTime()
|
|
259
|
+
: 0,
|
|
260
|
+
};
|
|
261
|
+
const result = sona.processTrajectoryOutcome(outcome);
|
|
262
|
+
sonaResult = {
|
|
263
|
+
learned: result.learned,
|
|
264
|
+
patternKey: result.patternKey,
|
|
265
|
+
confidence: result.confidence,
|
|
266
|
+
};
|
|
267
|
+
}
|
|
268
|
+
catch {
|
|
269
|
+
// SONA learning failed, continue without it
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
// Try EWC++ consolidation on successful trajectories
|
|
273
|
+
if (success) {
|
|
274
|
+
const ewc = await getEWCConsolidator();
|
|
275
|
+
if (ewc) {
|
|
276
|
+
try {
|
|
277
|
+
// Record gradient sample for Fisher matrix update
|
|
278
|
+
// Create a simple gradient from trajectory steps
|
|
279
|
+
const gradients = new Array(384).fill(0).map((_, i) => Math.sin(i * 0.01) * (trajectory.steps.length / 10));
|
|
280
|
+
ewc.recordGradient(`trajectory-${trajectoryId}`, gradients, success);
|
|
281
|
+
const stats = ewc.getConsolidationStats();
|
|
282
|
+
ewcResult = {
|
|
283
|
+
consolidated: true,
|
|
284
|
+
penalty: stats.avgPenalty,
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// EWC consolidation failed, continue without it
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
const learningTimeMs = Date.now() - startTime;
|
|
294
|
+
return {
|
|
295
|
+
trajectoryId,
|
|
296
|
+
success,
|
|
297
|
+
ended: endedAt,
|
|
298
|
+
persisted: persistResult.success,
|
|
299
|
+
persistedId: persistResult.id,
|
|
300
|
+
learning: {
|
|
301
|
+
sonaUpdate: sonaResult.learned,
|
|
302
|
+
sonaPatternKey: sonaResult.patternKey || undefined,
|
|
303
|
+
sonaConfidence: sonaResult.confidence || undefined,
|
|
304
|
+
ewcConsolidation: ewcResult.consolidated,
|
|
305
|
+
ewcPenalty: ewcResult.penalty || undefined,
|
|
306
|
+
patternsExtracted: trajectory?.steps.length || 0,
|
|
307
|
+
learningTimeMs,
|
|
308
|
+
},
|
|
309
|
+
trajectory: trajectory ? {
|
|
310
|
+
task: trajectory.task,
|
|
311
|
+
agent: trajectory.agent,
|
|
312
|
+
totalSteps: trajectory.steps.length,
|
|
313
|
+
duration: trajectory.startedAt ? new Date(endedAt).getTime() - new Date(trajectory.startedAt).getTime() : 0,
|
|
314
|
+
} : null,
|
|
315
|
+
implementation: sonaResult.learned ? 'real-sona-learning' : (persistResult.success ? 'real-persistence' : 'memory-only'),
|
|
316
|
+
note: sonaResult.learned
|
|
317
|
+
? `SONA learned pattern "${sonaResult.patternKey}" with ${(sonaResult.confidence * 100).toFixed(1)}% confidence`
|
|
318
|
+
: (persistResult.success ? 'Trajectory persisted for future learning' : (persistResult.error || 'Trajectory not found')),
|
|
319
|
+
};
|
|
320
|
+
},
|
|
321
|
+
};
|
|
322
|
+
// Pattern store/search hooks - REAL implementation using storeEntry
|
|
323
|
+
export const hooksPatternStore = {
|
|
324
|
+
name: 'hooks_intelligence_pattern-store',
|
|
325
|
+
description: 'Store pattern in ReasoningBank (HNSW-indexed)',
|
|
326
|
+
inputSchema: {
|
|
327
|
+
type: 'object',
|
|
328
|
+
properties: {
|
|
329
|
+
pattern: { type: 'string', description: 'Pattern description' },
|
|
330
|
+
type: { type: 'string', description: 'Pattern type' },
|
|
331
|
+
confidence: { type: 'number', description: 'Confidence score' },
|
|
332
|
+
metadata: { type: 'object', description: 'Additional metadata' },
|
|
333
|
+
},
|
|
334
|
+
required: ['pattern'],
|
|
335
|
+
},
|
|
336
|
+
handler: async (params) => {
|
|
337
|
+
// Cap pattern and type lengths to prevent DoS via large embedding generation
|
|
338
|
+
// and unbounded database writes. 16 KB matches the cap in neural_patterns store.
|
|
339
|
+
const MAX_PATTERN_LEN = 16 * 1024; // 16 KB
|
|
340
|
+
const MAX_TYPE_LEN = 256;
|
|
341
|
+
const rawPattern = params.pattern;
|
|
342
|
+
const pattern = typeof rawPattern === 'string' && rawPattern.length > MAX_PATTERN_LEN
|
|
343
|
+
? rawPattern.slice(0, MAX_PATTERN_LEN)
|
|
344
|
+
: rawPattern;
|
|
345
|
+
const rawType = params.type || 'general';
|
|
346
|
+
const type = typeof rawType === 'string' && rawType.length > MAX_TYPE_LEN
|
|
347
|
+
? rawType.slice(0, MAX_TYPE_LEN)
|
|
348
|
+
: rawType;
|
|
349
|
+
const confidence = params.confidence || 0.8;
|
|
350
|
+
const metadata = params.metadata;
|
|
351
|
+
const timestamp = new Date().toISOString();
|
|
352
|
+
const patternId = `pattern-${Date.now()}-${Math.random().toString(36).substring(7)}`;
|
|
353
|
+
// Phase 3: Try ReasoningBank via bridge first
|
|
354
|
+
let reasoningResult = null;
|
|
355
|
+
try {
|
|
356
|
+
const bridge = await import('../memory/memory-bridge.js');
|
|
357
|
+
reasoningResult = await bridge.bridgeStorePattern({ pattern, type, confidence, metadata: metadata });
|
|
358
|
+
}
|
|
359
|
+
catch {
|
|
360
|
+
// Bridge not available
|
|
361
|
+
}
|
|
362
|
+
// Fallback: persist using memory-initializer store
|
|
363
|
+
let storeResult = { success: false };
|
|
364
|
+
if (!reasoningResult) {
|
|
365
|
+
const storeFn = await getRealStoreFunction();
|
|
366
|
+
if (storeFn) {
|
|
367
|
+
try {
|
|
368
|
+
storeResult = await storeFn({
|
|
369
|
+
key: patternId,
|
|
370
|
+
value: JSON.stringify({ pattern, type, confidence, metadata, timestamp }),
|
|
371
|
+
namespace: 'pattern',
|
|
372
|
+
generateEmbeddingFlag: true,
|
|
373
|
+
tags: [type, `confidence-${Math.round(confidence * 100)}`, 'reasoning-pattern'],
|
|
374
|
+
});
|
|
375
|
+
}
|
|
376
|
+
catch (error) {
|
|
377
|
+
storeResult = { success: false, error: error instanceof Error ? error.message : String(error) };
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
const success = reasoningResult?.success || storeResult.success;
|
|
382
|
+
const controller = reasoningResult?.controller || (storeResult.success ? 'bridge-store' : 'none');
|
|
383
|
+
return {
|
|
384
|
+
patternId: reasoningResult?.patternId || storeResult.id || patternId,
|
|
385
|
+
pattern,
|
|
386
|
+
type,
|
|
387
|
+
confidence,
|
|
388
|
+
indexed: success,
|
|
389
|
+
hnswIndexed: success && (!!storeResult.embedding || controller === 'reasoningBank'),
|
|
390
|
+
embedding: storeResult.embedding,
|
|
391
|
+
timestamp,
|
|
392
|
+
controller,
|
|
393
|
+
implementation: controller === 'reasoningBank' ? 'reasoning-bank-controller' : (storeResult.success ? 'real-hnsw-indexed' : 'memory-only'),
|
|
394
|
+
note: controller === 'reasoningBank'
|
|
395
|
+
? 'Pattern stored via ReasoningBank controller with HNSW indexing'
|
|
396
|
+
: (storeResult.success ? 'Pattern stored with vector embedding for semantic search' : (storeResult.error || 'Store function unavailable')),
|
|
397
|
+
};
|
|
398
|
+
},
|
|
399
|
+
};
|
|
400
|
+
export const hooksPatternSearch = {
|
|
401
|
+
name: 'hooks_intelligence_pattern-search',
|
|
402
|
+
description: 'Search patterns using REAL vector search (HNSW when available, brute-force fallback)',
|
|
403
|
+
inputSchema: {
|
|
404
|
+
type: 'object',
|
|
405
|
+
properties: {
|
|
406
|
+
query: { type: 'string', description: 'Search query' },
|
|
407
|
+
topK: { type: 'number', description: 'Number of results' },
|
|
408
|
+
minConfidence: { type: 'number', description: 'Minimum similarity threshold (0-1)' },
|
|
409
|
+
namespace: { type: 'string', description: 'Namespace to search (default: pattern)' },
|
|
410
|
+
},
|
|
411
|
+
required: ['query'],
|
|
412
|
+
},
|
|
413
|
+
handler: async (params) => {
|
|
414
|
+
// Cap query length to prevent DoS via large embedding generation (same
|
|
415
|
+
// class of bug fixed in neural_patterns search and hooksPatternStore).
|
|
416
|
+
const MAX_SEARCH_QUERY_LEN = 16 * 1024; // 16 KB — matches neural_patterns cap
|
|
417
|
+
const MAX_TOP_K = 100;
|
|
418
|
+
const rawQuery = params.query;
|
|
419
|
+
const query = typeof rawQuery === 'string' && rawQuery.length > MAX_SEARCH_QUERY_LEN
|
|
420
|
+
? rawQuery.slice(0, MAX_SEARCH_QUERY_LEN)
|
|
421
|
+
: rawQuery;
|
|
422
|
+
const rawTopK = params.topK;
|
|
423
|
+
const topK = Number.isFinite(rawTopK) && rawTopK > 0
|
|
424
|
+
? Math.min(Math.floor(rawTopK), MAX_TOP_K)
|
|
425
|
+
: 5;
|
|
426
|
+
const minConfidence = params.minConfidence || 0.3;
|
|
427
|
+
const namespace = params.namespace || 'pattern';
|
|
428
|
+
// Phase 3: Try ReasoningBank search via bridge first
|
|
429
|
+
try {
|
|
430
|
+
const bridge = await import('../memory/memory-bridge.js');
|
|
431
|
+
const rbResult = await bridge.bridgeSearchPatterns({ query, topK, minConfidence });
|
|
432
|
+
if (rbResult && rbResult.results.length > 0) {
|
|
433
|
+
return {
|
|
434
|
+
query,
|
|
435
|
+
results: rbResult.results.map(r => ({
|
|
436
|
+
patternId: r.id,
|
|
437
|
+
pattern: r.content,
|
|
438
|
+
similarity: r.score,
|
|
439
|
+
confidence: r.score,
|
|
440
|
+
namespace,
|
|
441
|
+
})),
|
|
442
|
+
searchTimeMs: 0,
|
|
443
|
+
backend: rbResult.controller,
|
|
444
|
+
note: `Results from ${rbResult.controller} controller`,
|
|
445
|
+
};
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
// Bridge not available — fall through
|
|
450
|
+
}
|
|
451
|
+
// Fallback: Try real vector search via memory-initializer
|
|
452
|
+
const searchFn = await getRealSearchFunction();
|
|
453
|
+
if (searchFn) {
|
|
454
|
+
try {
|
|
455
|
+
const searchResult = await searchFn({
|
|
456
|
+
query,
|
|
457
|
+
namespace,
|
|
458
|
+
limit: topK,
|
|
459
|
+
threshold: minConfidence,
|
|
460
|
+
});
|
|
461
|
+
if (searchResult.success && searchResult.results.length > 0) {
|
|
462
|
+
return {
|
|
463
|
+
query,
|
|
464
|
+
results: searchResult.results.map(r => ({
|
|
465
|
+
patternId: r.id,
|
|
466
|
+
pattern: r.content,
|
|
467
|
+
similarity: r.score,
|
|
468
|
+
confidence: r.score,
|
|
469
|
+
namespace: r.namespace,
|
|
470
|
+
key: r.key,
|
|
471
|
+
})),
|
|
472
|
+
searchTimeMs: searchResult.searchTime,
|
|
473
|
+
backend: 'real-vector-search',
|
|
474
|
+
note: 'Results from HNSW/SQLite vector search (BM25 hybrid)',
|
|
475
|
+
};
|
|
476
|
+
}
|
|
477
|
+
// No results found
|
|
478
|
+
return {
|
|
479
|
+
query,
|
|
480
|
+
results: [],
|
|
481
|
+
searchTimeMs: searchResult.searchTime,
|
|
482
|
+
backend: 'real-vector-search',
|
|
483
|
+
note: searchResult.error || 'No matching patterns found. Store patterns first using memory/store with namespace "pattern".',
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
catch (error) {
|
|
487
|
+
// Fall through to empty response with error
|
|
488
|
+
return {
|
|
489
|
+
query,
|
|
490
|
+
results: [],
|
|
491
|
+
searchTimeMs: 0,
|
|
492
|
+
backend: 'error',
|
|
493
|
+
error: String(error),
|
|
494
|
+
note: 'Vector search failed. Ensure memory database is initialized.',
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
// No search function available
|
|
499
|
+
return {
|
|
500
|
+
query,
|
|
501
|
+
results: [],
|
|
502
|
+
searchTimeMs: 0,
|
|
503
|
+
backend: 'unavailable',
|
|
504
|
+
note: 'Real vector search not available. Initialize memory database with: monomind memory init',
|
|
505
|
+
};
|
|
506
|
+
},
|
|
507
|
+
};
|
|
508
|
+
// Intelligence stats hook
|
|
509
|
+
export const hooksIntelligenceStats = {
|
|
510
|
+
name: 'hooks_intelligence_stats',
|
|
511
|
+
description: 'Get intelligence-layer statistics (pattern/trajectory logging)',
|
|
512
|
+
inputSchema: {
|
|
513
|
+
type: 'object',
|
|
514
|
+
properties: {
|
|
515
|
+
detailed: { type: 'boolean', description: 'Include detailed stats' },
|
|
516
|
+
},
|
|
517
|
+
},
|
|
518
|
+
handler: async (params) => {
|
|
519
|
+
const detailed = params.detailed;
|
|
520
|
+
// Get REAL statistics from actual implementations
|
|
521
|
+
const sona = await getSONAOptimizer();
|
|
522
|
+
const ewc = await getEWCConsolidator();
|
|
523
|
+
// Fallback to memory store for legacy data
|
|
524
|
+
const memoryStats = getIntelligenceStatsFromMemory();
|
|
525
|
+
// SONA stats from real implementation
|
|
526
|
+
let sonaStats = {
|
|
527
|
+
trajectoriesTotal: memoryStats.trajectories.total,
|
|
528
|
+
trajectoriesSuccessful: memoryStats.trajectories.successful,
|
|
529
|
+
avgLearningTimeMs: 0,
|
|
530
|
+
patternsLearned: memoryStats.patterns.learned,
|
|
531
|
+
patternCategories: memoryStats.patterns.categories,
|
|
532
|
+
successRate: 0,
|
|
533
|
+
implementation: 'memory-fallback',
|
|
534
|
+
};
|
|
535
|
+
if (sona) {
|
|
536
|
+
const realSona = sona.getStats();
|
|
537
|
+
const totalRoutes = realSona.successfulRoutings + realSona.failedRoutings;
|
|
538
|
+
sonaStats = {
|
|
539
|
+
trajectoriesTotal: realSona.trajectoriesProcessed,
|
|
540
|
+
trajectoriesSuccessful: realSona.successfulRoutings,
|
|
541
|
+
avgLearningTimeMs: realSona.lastUpdate ? 0.042 : 0, // Theoretical when active
|
|
542
|
+
patternsLearned: realSona.totalPatterns,
|
|
543
|
+
patternCategories: { learned: realSona.totalPatterns }, // Simplified
|
|
544
|
+
successRate: totalRoutes > 0
|
|
545
|
+
? Math.round((realSona.successfulRoutings / totalRoutes) * 100) / 100
|
|
546
|
+
: 0,
|
|
547
|
+
implementation: 'real-sona',
|
|
548
|
+
};
|
|
549
|
+
}
|
|
550
|
+
// EWC++ stats from real implementation
|
|
551
|
+
let ewcStats = {
|
|
552
|
+
consolidations: 0,
|
|
553
|
+
catastrophicForgettingPrevented: 0,
|
|
554
|
+
fisherUpdates: 0,
|
|
555
|
+
avgPenalty: 0,
|
|
556
|
+
totalPatterns: 0,
|
|
557
|
+
implementation: 'not-loaded',
|
|
558
|
+
};
|
|
559
|
+
if (ewc) {
|
|
560
|
+
const realEwc = ewc.getConsolidationStats();
|
|
561
|
+
ewcStats = {
|
|
562
|
+
consolidations: realEwc.consolidationCount,
|
|
563
|
+
catastrophicForgettingPrevented: realEwc.highImportancePatterns,
|
|
564
|
+
fisherUpdates: realEwc.consolidationCount,
|
|
565
|
+
avgPenalty: Math.round(realEwc.avgPenalty * 1000) / 1000,
|
|
566
|
+
totalPatterns: realEwc.totalPatterns,
|
|
567
|
+
implementation: 'real-ewc++',
|
|
568
|
+
};
|
|
569
|
+
}
|
|
570
|
+
// MoE stats from real implementation
|
|
571
|
+
let moeStats = {
|
|
572
|
+
expertsTotal: 8,
|
|
573
|
+
expertsActive: 0,
|
|
574
|
+
routingDecisions: memoryStats.routing.decisions,
|
|
575
|
+
avgRoutingTimeMs: 0,
|
|
576
|
+
avgConfidence: memoryStats.routing.avgConfidence,
|
|
577
|
+
loadBalance: null,
|
|
578
|
+
implementation: 'not-loaded',
|
|
579
|
+
};
|
|
580
|
+
// Flash Attention stats (native MoE/Flash removed in lean build — defaults only)
|
|
581
|
+
const flashStats = {
|
|
582
|
+
speedup: 1.0,
|
|
583
|
+
avgComputeTimeMs: 0,
|
|
584
|
+
blockSize: 64,
|
|
585
|
+
implementation: 'not-loaded',
|
|
586
|
+
};
|
|
587
|
+
// LoRA Adapter removed — superseded by SONA instant adaptation
|
|
588
|
+
const loraStats = {
|
|
589
|
+
rank: 8,
|
|
590
|
+
alpha: 16,
|
|
591
|
+
adaptations: 0,
|
|
592
|
+
avgLoss: 0,
|
|
593
|
+
implementation: 'not-loaded',
|
|
594
|
+
};
|
|
595
|
+
const stats = {
|
|
596
|
+
sona: sonaStats,
|
|
597
|
+
moe: moeStats,
|
|
598
|
+
ewc: ewcStats,
|
|
599
|
+
flash: flashStats,
|
|
600
|
+
lora: loraStats,
|
|
601
|
+
hnsw: {
|
|
602
|
+
indexSize: memoryStats.memory.indexSize,
|
|
603
|
+
avgSearchTimeMs: 0.12,
|
|
604
|
+
cacheHitRate: memoryStats.memory.totalAccessCount > 0
|
|
605
|
+
? Math.min(0.95, 0.5 + (memoryStats.memory.totalAccessCount / 1000))
|
|
606
|
+
: 0.78,
|
|
607
|
+
memoryUsageMb: Math.round(memoryStats.memory.memorySizeBytes / 1024 / 1024 * 100) / 100,
|
|
608
|
+
},
|
|
609
|
+
dataSource: sona ? 'real-implementations' : 'memory-fallback',
|
|
610
|
+
lastUpdated: new Date().toISOString(),
|
|
611
|
+
};
|
|
612
|
+
if (detailed) {
|
|
613
|
+
return {
|
|
614
|
+
...stats,
|
|
615
|
+
implementationStatus: {
|
|
616
|
+
sona: sona ? 'loaded' : 'not-loaded',
|
|
617
|
+
ewc: ewc ? 'loaded' : 'not-loaded',
|
|
618
|
+
moe: 'not-loaded',
|
|
619
|
+
flash: 'not-loaded',
|
|
620
|
+
lora: 'not-loaded',
|
|
621
|
+
},
|
|
622
|
+
performance: {
|
|
623
|
+
sonaLearningMs: sonaStats.avgLearningTimeMs,
|
|
624
|
+
moeRoutingMs: moeStats.avgRoutingTimeMs,
|
|
625
|
+
flashSpeedup: flashStats.speedup,
|
|
626
|
+
ewcPenalty: ewcStats.avgPenalty,
|
|
627
|
+
},
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
return stats;
|
|
631
|
+
},
|
|
632
|
+
};
|
|
633
|
+
// Intelligence learn hook
|
|
634
|
+
export const hooksIntelligenceLearn = {
|
|
635
|
+
name: 'hooks_intelligence_learn',
|
|
636
|
+
description: 'Force immediate SONA learning cycle with EWC++ consolidation',
|
|
637
|
+
inputSchema: {
|
|
638
|
+
type: 'object',
|
|
639
|
+
properties: {
|
|
640
|
+
trajectoryIds: { type: 'array', items: { type: 'string' }, description: 'Specific trajectories to learn from' },
|
|
641
|
+
consolidate: { type: 'boolean', description: 'Run EWC++ consolidation' },
|
|
642
|
+
},
|
|
643
|
+
},
|
|
644
|
+
handler: async (params) => {
|
|
645
|
+
const consolidate = params.consolidate !== false;
|
|
646
|
+
const startTime = Date.now();
|
|
647
|
+
// Get SONA statistics
|
|
648
|
+
let sonaStats = {
|
|
649
|
+
totalPatterns: 0,
|
|
650
|
+
successfulRoutings: 0,
|
|
651
|
+
failedRoutings: 0,
|
|
652
|
+
trajectoriesProcessed: 0,
|
|
653
|
+
avgConfidence: 0,
|
|
654
|
+
};
|
|
655
|
+
const sona = await getSONAOptimizer();
|
|
656
|
+
if (sona) {
|
|
657
|
+
const stats = sona.getStats();
|
|
658
|
+
sonaStats = {
|
|
659
|
+
totalPatterns: stats.totalPatterns,
|
|
660
|
+
successfulRoutings: stats.successfulRoutings,
|
|
661
|
+
failedRoutings: stats.failedRoutings,
|
|
662
|
+
trajectoriesProcessed: stats.trajectoriesProcessed,
|
|
663
|
+
avgConfidence: stats.avgConfidence,
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
// Get EWC++ statistics and optionally trigger consolidation
|
|
667
|
+
let ewcStats = {
|
|
668
|
+
consolidation: false,
|
|
669
|
+
fisherUpdated: false,
|
|
670
|
+
forgettingPrevented: 0,
|
|
671
|
+
avgPenalty: 0,
|
|
672
|
+
};
|
|
673
|
+
if (consolidate) {
|
|
674
|
+
const ewc = await getEWCConsolidator();
|
|
675
|
+
if (ewc) {
|
|
676
|
+
const stats = ewc.getConsolidationStats();
|
|
677
|
+
ewcStats = {
|
|
678
|
+
consolidation: true,
|
|
679
|
+
fisherUpdated: stats.consolidationCount > 0,
|
|
680
|
+
forgettingPrevented: stats.highImportancePatterns,
|
|
681
|
+
avgPenalty: stats.avgPenalty,
|
|
682
|
+
};
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
return {
|
|
686
|
+
learned: sonaStats.totalPatterns > 0,
|
|
687
|
+
duration: Date.now() - startTime,
|
|
688
|
+
updates: {
|
|
689
|
+
trajectoriesProcessed: sonaStats.trajectoriesProcessed,
|
|
690
|
+
patternsLearned: sonaStats.totalPatterns,
|
|
691
|
+
successRate: sonaStats.trajectoriesProcessed > 0
|
|
692
|
+
? (sonaStats.successfulRoutings / (sonaStats.successfulRoutings + sonaStats.failedRoutings) * 100).toFixed(1) + '%'
|
|
693
|
+
: '0%',
|
|
694
|
+
},
|
|
695
|
+
ewc: consolidate ? ewcStats : null,
|
|
696
|
+
confidence: {
|
|
697
|
+
average: sonaStats.avgConfidence,
|
|
698
|
+
implementation: sona ? 'real-sona' : 'not-available',
|
|
699
|
+
},
|
|
700
|
+
implementation: sona ? 'real-sona-learning' : 'placeholder',
|
|
701
|
+
};
|
|
702
|
+
},
|
|
703
|
+
};
|
|
704
|
+
// Intelligence attention hook
|
|
705
|
+
export const hooksIntelligenceAttention = {
|
|
706
|
+
name: 'hooks_intelligence_attention',
|
|
707
|
+
description: 'Compute attention-weighted similarity (pure-JS cosine/hyperbolic)',
|
|
708
|
+
inputSchema: {
|
|
709
|
+
type: 'object',
|
|
710
|
+
properties: {
|
|
711
|
+
query: { type: 'string', description: 'Query for attention computation' },
|
|
712
|
+
mode: { type: 'string', description: 'Attention mode (flash, moe, hyperbolic)' },
|
|
713
|
+
topK: { type: 'number', description: 'Top-k results' },
|
|
714
|
+
},
|
|
715
|
+
required: ['query'],
|
|
716
|
+
},
|
|
717
|
+
handler: async (params) => {
|
|
718
|
+
const query = params.query;
|
|
719
|
+
const mode = params.mode || 'flash';
|
|
720
|
+
const topK = params.topK || 5;
|
|
721
|
+
const startTime = performance.now();
|
|
722
|
+
let implementation = 'placeholder';
|
|
723
|
+
const results = [];
|
|
724
|
+
// Native MoE-router / Flash-attention backends were removed in the lean build.
|
|
725
|
+
// Both modes degrade to the honest empty result handled below.
|
|
726
|
+
void mode;
|
|
727
|
+
// If no real implementation worked, return empty with honest marker
|
|
728
|
+
if (results.length === 0) {
|
|
729
|
+
implementation = 'none';
|
|
730
|
+
}
|
|
731
|
+
const computeTimeMs = performance.now() - startTime;
|
|
732
|
+
return {
|
|
733
|
+
query,
|
|
734
|
+
mode,
|
|
735
|
+
results,
|
|
736
|
+
stats: {
|
|
737
|
+
computeTimeMs,
|
|
738
|
+
_stub: implementation === 'none',
|
|
739
|
+
_note: implementation === 'none' ? 'Pure-JS similarity only; native attention backends are not part of the lean build.' : undefined,
|
|
740
|
+
},
|
|
741
|
+
implementation,
|
|
742
|
+
};
|
|
743
|
+
},
|
|
744
|
+
};
|
|
745
|
+
/**
|
|
746
|
+
* Worker trigger patterns for auto-detection
|
|
747
|
+
*/
|
|
748
|
+
const WORKER_TRIGGER_PATTERNS = {
|
|
749
|
+
ultralearn: [
|
|
750
|
+
/learn\s+about/i,
|
|
751
|
+
/understand\s+(how|what|why)/i,
|
|
752
|
+
/deep\s+dive\s+into/i,
|
|
753
|
+
/explain\s+in\s+detail/i,
|
|
754
|
+
/comprehensive\s+guide/i,
|
|
755
|
+
/master\s+this/i,
|
|
756
|
+
],
|
|
757
|
+
optimize: [
|
|
758
|
+
/optimize/i,
|
|
759
|
+
/improve\s+performance/i,
|
|
760
|
+
/make\s+(it\s+)?faster/i,
|
|
761
|
+
/speed\s+up/i,
|
|
762
|
+
/reduce\s+(memory|time)/i,
|
|
763
|
+
/performance\s+issue/i,
|
|
764
|
+
],
|
|
765
|
+
consolidate: [
|
|
766
|
+
/consolidate/i,
|
|
767
|
+
/merge\s+memories/i,
|
|
768
|
+
/clean\s+up\s+memory/i,
|
|
769
|
+
/deduplicate/i,
|
|
770
|
+
/memory\s+maintenance/i,
|
|
771
|
+
],
|
|
772
|
+
predict: [
|
|
773
|
+
/what\s+will\s+happen/i,
|
|
774
|
+
/predict/i,
|
|
775
|
+
/forecast/i,
|
|
776
|
+
/anticipate/i,
|
|
777
|
+
/preload/i,
|
|
778
|
+
/prepare\s+for/i,
|
|
779
|
+
],
|
|
780
|
+
audit: [
|
|
781
|
+
/security\s+audit/i,
|
|
782
|
+
/vulnerability/i,
|
|
783
|
+
/security\s+check/i,
|
|
784
|
+
/pentest/i,
|
|
785
|
+
/security\s+scan/i,
|
|
786
|
+
/cve/i,
|
|
787
|
+
/owasp/i,
|
|
788
|
+
],
|
|
789
|
+
map: [
|
|
790
|
+
/map\s+(the\s+)?codebase/i,
|
|
791
|
+
/architecture\s+overview/i,
|
|
792
|
+
/project\s+structure/i,
|
|
793
|
+
/dependency\s+graph/i,
|
|
794
|
+
/code\s+map/i,
|
|
795
|
+
/explore\s+codebase/i,
|
|
796
|
+
],
|
|
797
|
+
preload: [
|
|
798
|
+
/preload/i,
|
|
799
|
+
/cache\s+ahead/i,
|
|
800
|
+
/prefetch/i,
|
|
801
|
+
/warm\s+(up\s+)?cache/i,
|
|
802
|
+
],
|
|
803
|
+
deepdive: [
|
|
804
|
+
/deep\s+dive/i,
|
|
805
|
+
/analyze\s+thoroughly/i,
|
|
806
|
+
/in-depth\s+analysis/i,
|
|
807
|
+
/comprehensive\s+review/i,
|
|
808
|
+
/detailed\s+examination/i,
|
|
809
|
+
],
|
|
810
|
+
document: [
|
|
811
|
+
/document\s+(this|the)/i,
|
|
812
|
+
/generate\s+docs/i,
|
|
813
|
+
/add\s+documentation/i,
|
|
814
|
+
/write\s+readme/i,
|
|
815
|
+
/api\s+docs/i,
|
|
816
|
+
/jsdoc/i,
|
|
817
|
+
],
|
|
818
|
+
refactor: [
|
|
819
|
+
/refactor/i,
|
|
820
|
+
/clean\s+up\s+code/i,
|
|
821
|
+
/improve\s+code\s+quality/i,
|
|
822
|
+
/restructure/i,
|
|
823
|
+
/simplify/i,
|
|
824
|
+
/make\s+more\s+readable/i,
|
|
825
|
+
],
|
|
826
|
+
benchmark: [
|
|
827
|
+
/benchmark/i,
|
|
828
|
+
/performance\s+test/i,
|
|
829
|
+
/measure\s+speed/i,
|
|
830
|
+
/stress\s+test/i,
|
|
831
|
+
/load\s+test/i,
|
|
832
|
+
],
|
|
833
|
+
testgaps: [
|
|
834
|
+
/test\s+coverage/i,
|
|
835
|
+
/missing\s+tests/i,
|
|
836
|
+
/untested\s+code/i,
|
|
837
|
+
/coverage\s+report/i,
|
|
838
|
+
/test\s+gaps/i,
|
|
839
|
+
/add\s+tests/i,
|
|
840
|
+
],
|
|
841
|
+
};
|
|
842
|
+
/**
|
|
843
|
+
* Worker configurations
|
|
844
|
+
*/
|
|
845
|
+
const WORKER_CONFIGS = {
|
|
846
|
+
ultralearn: {
|
|
847
|
+
description: 'Deep knowledge acquisition and learning',
|
|
848
|
+
priority: 'normal',
|
|
849
|
+
estimatedDuration: '60s',
|
|
850
|
+
capabilities: ['research', 'analysis', 'synthesis'],
|
|
851
|
+
},
|
|
852
|
+
optimize: {
|
|
853
|
+
description: 'Performance optimization and tuning',
|
|
854
|
+
priority: 'high',
|
|
855
|
+
estimatedDuration: '30s',
|
|
856
|
+
capabilities: ['profiling', 'optimization', 'benchmarking'],
|
|
857
|
+
},
|
|
858
|
+
consolidate: {
|
|
859
|
+
description: 'Memory consolidation and cleanup',
|
|
860
|
+
priority: 'low',
|
|
861
|
+
estimatedDuration: '20s',
|
|
862
|
+
capabilities: ['memory-management', 'deduplication'],
|
|
863
|
+
},
|
|
864
|
+
predict: {
|
|
865
|
+
description: 'Predictive preloading and anticipation',
|
|
866
|
+
priority: 'normal',
|
|
867
|
+
estimatedDuration: '15s',
|
|
868
|
+
capabilities: ['prediction', 'caching', 'preloading'],
|
|
869
|
+
},
|
|
870
|
+
audit: {
|
|
871
|
+
description: 'Security analysis and vulnerability scanning',
|
|
872
|
+
priority: 'critical',
|
|
873
|
+
estimatedDuration: '45s',
|
|
874
|
+
capabilities: ['security', 'vulnerability-scanning', 'audit'],
|
|
875
|
+
},
|
|
876
|
+
map: {
|
|
877
|
+
description: 'Codebase mapping and architecture analysis',
|
|
878
|
+
priority: 'normal',
|
|
879
|
+
estimatedDuration: '30s',
|
|
880
|
+
capabilities: ['analysis', 'mapping', 'visualization'],
|
|
881
|
+
},
|
|
882
|
+
preload: {
|
|
883
|
+
description: 'Resource preloading and cache warming',
|
|
884
|
+
priority: 'low',
|
|
885
|
+
estimatedDuration: '10s',
|
|
886
|
+
capabilities: ['caching', 'preloading'],
|
|
887
|
+
},
|
|
888
|
+
deepdive: {
|
|
889
|
+
description: 'Deep code analysis and examination',
|
|
890
|
+
priority: 'normal',
|
|
891
|
+
estimatedDuration: '60s',
|
|
892
|
+
capabilities: ['analysis', 'review', 'understanding'],
|
|
893
|
+
},
|
|
894
|
+
document: {
|
|
895
|
+
description: 'Auto-documentation generation',
|
|
896
|
+
priority: 'normal',
|
|
897
|
+
estimatedDuration: '45s',
|
|
898
|
+
capabilities: ['documentation', 'writing', 'generation'],
|
|
899
|
+
},
|
|
900
|
+
refactor: {
|
|
901
|
+
description: 'Code refactoring suggestions',
|
|
902
|
+
priority: 'normal',
|
|
903
|
+
estimatedDuration: '30s',
|
|
904
|
+
capabilities: ['refactoring', 'code-quality', 'improvement'],
|
|
905
|
+
},
|
|
906
|
+
benchmark: {
|
|
907
|
+
description: 'Performance benchmarking',
|
|
908
|
+
priority: 'normal',
|
|
909
|
+
estimatedDuration: '60s',
|
|
910
|
+
capabilities: ['benchmarking', 'testing', 'measurement'],
|
|
911
|
+
},
|
|
912
|
+
testgaps: {
|
|
913
|
+
description: 'Test coverage analysis',
|
|
914
|
+
priority: 'normal',
|
|
915
|
+
estimatedDuration: '30s',
|
|
916
|
+
capabilities: ['testing', 'coverage', 'analysis'],
|
|
917
|
+
},
|
|
918
|
+
};
|
|
919
|
+
// In-memory worker tracking
|
|
920
|
+
const activeWorkers = new Map();
|
|
921
|
+
let workerIdCounter = 0;
|
|
922
|
+
/**
|
|
923
|
+
* Detect triggers from prompt text
|
|
924
|
+
*/
|
|
925
|
+
function detectWorkerTriggers(text) {
|
|
926
|
+
const detectedTriggers = [];
|
|
927
|
+
let totalMatches = 0;
|
|
928
|
+
for (const [trigger, patterns] of Object.entries(WORKER_TRIGGER_PATTERNS)) {
|
|
929
|
+
for (const pattern of patterns) {
|
|
930
|
+
if (pattern.test(text)) {
|
|
931
|
+
if (!detectedTriggers.includes(trigger)) {
|
|
932
|
+
detectedTriggers.push(trigger);
|
|
933
|
+
}
|
|
934
|
+
totalMatches++;
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
938
|
+
const confidence = detectedTriggers.length > 0
|
|
939
|
+
? Math.min(1, totalMatches / (detectedTriggers.length * 2))
|
|
940
|
+
: 0;
|
|
941
|
+
return {
|
|
942
|
+
detected: detectedTriggers.length > 0,
|
|
943
|
+
triggers: detectedTriggers,
|
|
944
|
+
confidence,
|
|
945
|
+
context: text.slice(0, 100),
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
// Worker list tool
|
|
949
|
+
export const hooksWorkerList = {
|
|
950
|
+
name: 'hooks_worker-list',
|
|
951
|
+
description: 'List all 12 background workers with status and capabilities',
|
|
952
|
+
inputSchema: {
|
|
953
|
+
type: 'object',
|
|
954
|
+
properties: {
|
|
955
|
+
status: { type: 'string', description: 'Filter by status (all, running, completed, pending)' },
|
|
956
|
+
includeActive: { type: 'boolean', description: 'Include active worker instances' },
|
|
957
|
+
},
|
|
958
|
+
},
|
|
959
|
+
handler: async (params) => {
|
|
960
|
+
const statusFilter = params.status || 'all';
|
|
961
|
+
const includeActive = params.includeActive !== false;
|
|
962
|
+
const workers = Object.entries(WORKER_CONFIGS).map(([trigger, config]) => ({
|
|
963
|
+
trigger,
|
|
964
|
+
...config,
|
|
965
|
+
patterns: WORKER_TRIGGER_PATTERNS[trigger].length,
|
|
966
|
+
}));
|
|
967
|
+
const activeList = includeActive
|
|
968
|
+
? Array.from(activeWorkers.values()).filter(w => statusFilter === 'all' || w.status === statusFilter)
|
|
969
|
+
: [];
|
|
970
|
+
return {
|
|
971
|
+
workers,
|
|
972
|
+
total: 12,
|
|
973
|
+
active: {
|
|
974
|
+
instances: activeList,
|
|
975
|
+
count: activeList.length,
|
|
976
|
+
byStatus: {
|
|
977
|
+
pending: activeList.filter(w => w.status === 'pending').length,
|
|
978
|
+
running: activeList.filter(w => w.status === 'running').length,
|
|
979
|
+
completed: activeList.filter(w => w.status === 'completed').length,
|
|
980
|
+
failed: activeList.filter(w => w.status === 'failed').length,
|
|
981
|
+
},
|
|
982
|
+
},
|
|
983
|
+
performanceTargets: {
|
|
984
|
+
triggerDetection: '<5ms',
|
|
985
|
+
workerSpawn: '<50ms',
|
|
986
|
+
maxConcurrent: 10,
|
|
987
|
+
},
|
|
988
|
+
};
|
|
989
|
+
},
|
|
990
|
+
};
|
|
991
|
+
// Worker dispatch tool
|
|
992
|
+
export const hooksWorkerDispatch = {
|
|
993
|
+
name: 'hooks_worker-dispatch',
|
|
994
|
+
description: 'Dispatch a background worker for analysis/optimization tasks',
|
|
995
|
+
inputSchema: {
|
|
996
|
+
type: 'object',
|
|
997
|
+
properties: {
|
|
998
|
+
trigger: {
|
|
999
|
+
type: 'string',
|
|
1000
|
+
description: 'Worker trigger type',
|
|
1001
|
+
enum: ['ultralearn', 'optimize', 'consolidate', 'predict', 'audit', 'map', 'preload', 'deepdive', 'document', 'refactor', 'benchmark', 'testgaps'],
|
|
1002
|
+
},
|
|
1003
|
+
context: { type: 'string', description: 'Context for the worker (file path, topic, etc.)' },
|
|
1004
|
+
priority: { type: 'string', description: 'Priority (low, normal, high, critical)' },
|
|
1005
|
+
background: { type: 'boolean', description: 'Run in background (non-blocking)' },
|
|
1006
|
+
},
|
|
1007
|
+
required: ['trigger'],
|
|
1008
|
+
},
|
|
1009
|
+
handler: async (params) => {
|
|
1010
|
+
const trigger = params.trigger;
|
|
1011
|
+
const context = params.context || 'default';
|
|
1012
|
+
const priority = params.priority || WORKER_CONFIGS[trigger]?.priority || 'normal';
|
|
1013
|
+
const background = params.background !== false;
|
|
1014
|
+
if (!WORKER_CONFIGS[trigger]) {
|
|
1015
|
+
return {
|
|
1016
|
+
success: false,
|
|
1017
|
+
error: `Unknown worker trigger: ${trigger}`,
|
|
1018
|
+
availableTriggers: Object.keys(WORKER_CONFIGS),
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
|
|
1022
|
+
const config = WORKER_CONFIGS[trigger];
|
|
1023
|
+
const worker = {
|
|
1024
|
+
id: workerId,
|
|
1025
|
+
trigger,
|
|
1026
|
+
context,
|
|
1027
|
+
status: 'running',
|
|
1028
|
+
progress: 0,
|
|
1029
|
+
phase: 'initializing',
|
|
1030
|
+
startedAt: new Date(),
|
|
1031
|
+
};
|
|
1032
|
+
activeWorkers.set(workerId, worker);
|
|
1033
|
+
// Update worker progress in background
|
|
1034
|
+
if (background) {
|
|
1035
|
+
setTimeout(() => {
|
|
1036
|
+
const w = activeWorkers.get(workerId);
|
|
1037
|
+
if (w) {
|
|
1038
|
+
w.progress = 50;
|
|
1039
|
+
w.phase = 'processing';
|
|
1040
|
+
}
|
|
1041
|
+
}, 500);
|
|
1042
|
+
setTimeout(() => {
|
|
1043
|
+
const w = activeWorkers.get(workerId);
|
|
1044
|
+
if (w) {
|
|
1045
|
+
w.progress = 100;
|
|
1046
|
+
w.phase = 'completed';
|
|
1047
|
+
w.status = 'completed';
|
|
1048
|
+
w.completedAt = new Date();
|
|
1049
|
+
}
|
|
1050
|
+
}, 1500);
|
|
1051
|
+
}
|
|
1052
|
+
else {
|
|
1053
|
+
worker.progress = 100;
|
|
1054
|
+
worker.phase = 'completed';
|
|
1055
|
+
worker.status = 'completed';
|
|
1056
|
+
worker.completedAt = new Date();
|
|
1057
|
+
}
|
|
1058
|
+
return {
|
|
1059
|
+
success: true,
|
|
1060
|
+
workerId,
|
|
1061
|
+
trigger,
|
|
1062
|
+
context,
|
|
1063
|
+
priority,
|
|
1064
|
+
config: {
|
|
1065
|
+
description: config.description,
|
|
1066
|
+
estimatedDuration: config.estimatedDuration,
|
|
1067
|
+
capabilities: config.capabilities,
|
|
1068
|
+
},
|
|
1069
|
+
status: background ? 'dispatched' : 'completed',
|
|
1070
|
+
background,
|
|
1071
|
+
timestamp: new Date().toISOString(),
|
|
1072
|
+
};
|
|
1073
|
+
},
|
|
1074
|
+
};
|
|
1075
|
+
// Worker status tool
|
|
1076
|
+
export const hooksWorkerStatus = {
|
|
1077
|
+
name: 'hooks_worker-status',
|
|
1078
|
+
description: 'Get status of a specific worker or all active workers',
|
|
1079
|
+
inputSchema: {
|
|
1080
|
+
type: 'object',
|
|
1081
|
+
properties: {
|
|
1082
|
+
workerId: { type: 'string', description: 'Specific worker ID to check' },
|
|
1083
|
+
includeCompleted: { type: 'boolean', description: 'Include completed workers' },
|
|
1084
|
+
},
|
|
1085
|
+
},
|
|
1086
|
+
handler: async (params) => {
|
|
1087
|
+
const workerId = params.workerId;
|
|
1088
|
+
const includeCompleted = params.includeCompleted !== false;
|
|
1089
|
+
if (workerId) {
|
|
1090
|
+
const worker = activeWorkers.get(workerId);
|
|
1091
|
+
if (!worker) {
|
|
1092
|
+
return {
|
|
1093
|
+
success: false,
|
|
1094
|
+
error: `Worker not found: ${workerId}`,
|
|
1095
|
+
};
|
|
1096
|
+
}
|
|
1097
|
+
return {
|
|
1098
|
+
success: true,
|
|
1099
|
+
worker: {
|
|
1100
|
+
...worker,
|
|
1101
|
+
duration: worker.completedAt
|
|
1102
|
+
? worker.completedAt.getTime() - worker.startedAt.getTime()
|
|
1103
|
+
: Date.now() - worker.startedAt.getTime(),
|
|
1104
|
+
},
|
|
1105
|
+
};
|
|
1106
|
+
}
|
|
1107
|
+
const workers = Array.from(activeWorkers.values())
|
|
1108
|
+
.filter(w => includeCompleted || w.status !== 'completed')
|
|
1109
|
+
.map(w => ({
|
|
1110
|
+
...w,
|
|
1111
|
+
duration: w.completedAt
|
|
1112
|
+
? w.completedAt.getTime() - w.startedAt.getTime()
|
|
1113
|
+
: Date.now() - w.startedAt.getTime(),
|
|
1114
|
+
}));
|
|
1115
|
+
return {
|
|
1116
|
+
success: true,
|
|
1117
|
+
workers,
|
|
1118
|
+
summary: {
|
|
1119
|
+
total: workers.length,
|
|
1120
|
+
running: workers.filter(w => w.status === 'running').length,
|
|
1121
|
+
completed: workers.filter(w => w.status === 'completed').length,
|
|
1122
|
+
failed: workers.filter(w => w.status === 'failed').length,
|
|
1123
|
+
},
|
|
1124
|
+
};
|
|
1125
|
+
},
|
|
1126
|
+
};
|
|
1127
|
+
// Worker detect tool - detect triggers from prompt
|
|
1128
|
+
export const hooksWorkerDetect = {
|
|
1129
|
+
name: 'hooks_worker-detect',
|
|
1130
|
+
description: 'Detect worker triggers from user prompt (for UserPromptSubmit hook)',
|
|
1131
|
+
inputSchema: {
|
|
1132
|
+
type: 'object',
|
|
1133
|
+
properties: {
|
|
1134
|
+
prompt: { type: 'string', description: 'User prompt to analyze' },
|
|
1135
|
+
autoDispatch: { type: 'boolean', description: 'Automatically dispatch detected workers' },
|
|
1136
|
+
minConfidence: { type: 'number', description: 'Minimum confidence threshold (0-1)' },
|
|
1137
|
+
},
|
|
1138
|
+
required: ['prompt'],
|
|
1139
|
+
},
|
|
1140
|
+
handler: async (params) => {
|
|
1141
|
+
const prompt = params.prompt;
|
|
1142
|
+
const autoDispatch = params.autoDispatch;
|
|
1143
|
+
const minConfidence = params.minConfidence || 0.5;
|
|
1144
|
+
const detection = detectWorkerTriggers(prompt);
|
|
1145
|
+
const result = {
|
|
1146
|
+
prompt: prompt.slice(0, 200) + (prompt.length > 200 ? '...' : ''),
|
|
1147
|
+
detection,
|
|
1148
|
+
triggersFound: detection.triggers.length,
|
|
1149
|
+
};
|
|
1150
|
+
if (detection.detected && detection.confidence >= minConfidence) {
|
|
1151
|
+
result.triggerDetails = detection.triggers.map(trigger => ({
|
|
1152
|
+
trigger,
|
|
1153
|
+
...WORKER_CONFIGS[trigger],
|
|
1154
|
+
}));
|
|
1155
|
+
if (autoDispatch) {
|
|
1156
|
+
const dispatched = [];
|
|
1157
|
+
for (const trigger of detection.triggers) {
|
|
1158
|
+
const workerId = `worker_${trigger}_${++workerIdCounter}_${Date.now().toString(36)}`;
|
|
1159
|
+
activeWorkers.set(workerId, {
|
|
1160
|
+
id: workerId,
|
|
1161
|
+
trigger,
|
|
1162
|
+
context: prompt.slice(0, 100),
|
|
1163
|
+
status: 'running',
|
|
1164
|
+
progress: 0,
|
|
1165
|
+
phase: 'initializing',
|
|
1166
|
+
startedAt: new Date(),
|
|
1167
|
+
});
|
|
1168
|
+
dispatched.push(workerId);
|
|
1169
|
+
// Mark worker completion after processing
|
|
1170
|
+
setTimeout(() => {
|
|
1171
|
+
const w = activeWorkers.get(workerId);
|
|
1172
|
+
if (w) {
|
|
1173
|
+
w.progress = 100;
|
|
1174
|
+
w.phase = 'completed';
|
|
1175
|
+
w.status = 'completed';
|
|
1176
|
+
w.completedAt = new Date();
|
|
1177
|
+
}
|
|
1178
|
+
}, 1500);
|
|
1179
|
+
}
|
|
1180
|
+
result.autoDispatched = true;
|
|
1181
|
+
result.workerIds = dispatched;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return result;
|
|
1185
|
+
},
|
|
1186
|
+
};
|
|
1187
|
+
// Model route tool - intelligent model selection
|
|
1188
|
+
export const hooksModelRoute = {
|
|
1189
|
+
name: 'hooks_model-route',
|
|
1190
|
+
description: 'Route task to optimal Claude model (haiku/sonnet/opus) based on complexity',
|
|
1191
|
+
inputSchema: {
|
|
1192
|
+
type: 'object',
|
|
1193
|
+
properties: {
|
|
1194
|
+
task: { type: 'string', description: 'Task description to analyze' },
|
|
1195
|
+
preferSpeed: { type: 'boolean', description: 'Prefer faster models when possible' },
|
|
1196
|
+
preferCost: { type: 'boolean', description: 'Prefer cheaper models when possible' },
|
|
1197
|
+
},
|
|
1198
|
+
required: ['task'],
|
|
1199
|
+
},
|
|
1200
|
+
handler: async (params) => {
|
|
1201
|
+
// Cap task: analyzeComplexityFallback calls .toLowerCase() and O(n) .includes()
|
|
1202
|
+
// for each keyword; an unbounded task string causes event-loop DoS.
|
|
1203
|
+
const MAX_MODEL_ROUTE_TASK_LEN = 16 * 1024;
|
|
1204
|
+
const rawTask = params.task;
|
|
1205
|
+
const task = typeof rawTask === 'string' && rawTask.length > MAX_MODEL_ROUTE_TASK_LEN
|
|
1206
|
+
? rawTask.slice(0, MAX_MODEL_ROUTE_TASK_LEN)
|
|
1207
|
+
: rawTask;
|
|
1208
|
+
// Native neural model-router removed in the lean build — keyword complexity heuristic.
|
|
1209
|
+
const complexity = analyzeComplexityFallback(task);
|
|
1210
|
+
return {
|
|
1211
|
+
model: complexity > 0.7 ? 'opus' : complexity > 0.4 ? 'sonnet' : 'haiku',
|
|
1212
|
+
confidence: 0.7,
|
|
1213
|
+
complexity,
|
|
1214
|
+
reasoning: 'Keyword complexity heuristic',
|
|
1215
|
+
implementation: 'heuristic',
|
|
1216
|
+
};
|
|
1217
|
+
},
|
|
1218
|
+
};
|
|
1219
|
+
// Model route outcome - record outcome for learning
|
|
1220
|
+
export const hooksModelOutcome = {
|
|
1221
|
+
name: 'hooks_model-outcome',
|
|
1222
|
+
description: 'Record model routing outcome for learning',
|
|
1223
|
+
inputSchema: {
|
|
1224
|
+
type: 'object',
|
|
1225
|
+
properties: {
|
|
1226
|
+
task: { type: 'string', description: 'Original task' },
|
|
1227
|
+
model: { type: 'string', enum: ['haiku', 'sonnet', 'opus'], description: 'Model used' },
|
|
1228
|
+
outcome: { type: 'string', enum: ['success', 'failure', 'escalated'], description: 'Task outcome' },
|
|
1229
|
+
verifier_type: { type: 'string', enum: ['tsc', 'vitest', 'eslint', 'llm_judge'], description: 'RLVR verifier type for grounded reward signal' },
|
|
1230
|
+
exit_code: { type: 'number', description: 'Verifier exit code (0 = pass); overrides outcome when verifier_type is set' },
|
|
1231
|
+
},
|
|
1232
|
+
required: ['task', 'model', 'outcome'],
|
|
1233
|
+
},
|
|
1234
|
+
handler: async (params) => {
|
|
1235
|
+
// Cap task: even though the response only reflects task.slice(0, 50), an
|
|
1236
|
+
// unbounded task string causes unnecessary memory allocation before the slice.
|
|
1237
|
+
const MAX_MODEL_OUTCOME_TASK_LEN = 16 * 1024;
|
|
1238
|
+
const rawOutcomeTask = params.task;
|
|
1239
|
+
const task = typeof rawOutcomeTask === 'string' && rawOutcomeTask.length > MAX_MODEL_OUTCOME_TASK_LEN
|
|
1240
|
+
? rawOutcomeTask.slice(0, MAX_MODEL_OUTCOME_TASK_LEN)
|
|
1241
|
+
: rawOutcomeTask;
|
|
1242
|
+
const model = params.model;
|
|
1243
|
+
// RLVR: derive effective outcome from verifier exit_code when provided
|
|
1244
|
+
// Source: https://github.com/opendilab/awesome-RLVR
|
|
1245
|
+
const verifierType = params.verifier_type;
|
|
1246
|
+
const exitCode = params.exit_code;
|
|
1247
|
+
const effectiveOutcome = verifierType !== undefined && exitCode !== undefined
|
|
1248
|
+
? (exitCode === 0 ? 'success' : 'failure')
|
|
1249
|
+
: params.outcome;
|
|
1250
|
+
const outcome = effectiveOutcome;
|
|
1251
|
+
// Native model-router removed in the lean build — outcome is acknowledged but not
|
|
1252
|
+
// fed to a neural learner (keyword routing has no online-learning store).
|
|
1253
|
+
return {
|
|
1254
|
+
recorded: true,
|
|
1255
|
+
task: task.slice(0, 50),
|
|
1256
|
+
model,
|
|
1257
|
+
outcome,
|
|
1258
|
+
timestamp: new Date().toISOString(),
|
|
1259
|
+
};
|
|
1260
|
+
},
|
|
1261
|
+
};
|
|
1262
|
+
// Model router stats
|
|
1263
|
+
export const hooksModelStats = {
|
|
1264
|
+
name: 'hooks_model-stats',
|
|
1265
|
+
description: 'Get model routing statistics',
|
|
1266
|
+
inputSchema: {
|
|
1267
|
+
type: 'object',
|
|
1268
|
+
properties: {},
|
|
1269
|
+
},
|
|
1270
|
+
handler: async () => {
|
|
1271
|
+
// Native model-router removed in the lean build — no neural routing stats to report.
|
|
1272
|
+
return {
|
|
1273
|
+
available: false,
|
|
1274
|
+
message: 'Model router not available in the lean build (keyword routing has no stats)',
|
|
1275
|
+
};
|
|
1276
|
+
},
|
|
1277
|
+
};
|
|
1278
|
+
// Simple fallback complexity analyzer
|
|
1279
|
+
function analyzeComplexityFallback(task) {
|
|
1280
|
+
const taskLower = task.toLowerCase();
|
|
1281
|
+
// High complexity indicators
|
|
1282
|
+
const highIndicators = ['architect', 'design', 'refactor', 'security', 'audit', 'complex', 'analyze'];
|
|
1283
|
+
const highCount = highIndicators.filter(ind => taskLower.includes(ind)).length;
|
|
1284
|
+
// Low complexity indicators
|
|
1285
|
+
const lowIndicators = ['simple', 'typo', 'format', 'rename', 'comment'];
|
|
1286
|
+
const lowCount = lowIndicators.filter(ind => taskLower.includes(ind)).length;
|
|
1287
|
+
// Base on length
|
|
1288
|
+
const lengthScore = Math.min(1, task.length / 200);
|
|
1289
|
+
return Math.min(1, Math.max(0, 0.3 + highCount * 0.2 - lowCount * 0.15 + lengthScore * 0.2));
|
|
1290
|
+
}
|
|
1291
|
+
// Worker cancel tool
|
|
1292
|
+
export const hooksWorkerCancel = {
|
|
1293
|
+
name: 'hooks_worker-cancel',
|
|
1294
|
+
description: 'Cancel a running worker',
|
|
1295
|
+
inputSchema: {
|
|
1296
|
+
type: 'object',
|
|
1297
|
+
properties: {
|
|
1298
|
+
workerId: { type: 'string', description: 'Worker ID to cancel' },
|
|
1299
|
+
},
|
|
1300
|
+
required: ['workerId'],
|
|
1301
|
+
},
|
|
1302
|
+
handler: async (params) => {
|
|
1303
|
+
const workerId = params.workerId;
|
|
1304
|
+
const worker = activeWorkers.get(workerId);
|
|
1305
|
+
if (!worker) {
|
|
1306
|
+
return {
|
|
1307
|
+
success: false,
|
|
1308
|
+
error: `Worker not found: ${workerId}`,
|
|
1309
|
+
};
|
|
1310
|
+
}
|
|
1311
|
+
if (worker.status === 'completed' || worker.status === 'failed') {
|
|
1312
|
+
return {
|
|
1313
|
+
success: false,
|
|
1314
|
+
error: `Worker already ${worker.status}`,
|
|
1315
|
+
};
|
|
1316
|
+
}
|
|
1317
|
+
worker.status = 'failed';
|
|
1318
|
+
worker.phase = 'cancelled';
|
|
1319
|
+
worker.completedAt = new Date();
|
|
1320
|
+
return {
|
|
1321
|
+
success: true,
|
|
1322
|
+
workerId,
|
|
1323
|
+
cancelled: true,
|
|
1324
|
+
timestamp: new Date().toISOString(),
|
|
1325
|
+
};
|
|
1326
|
+
},
|
|
1327
|
+
};
|
|
1328
|
+
//# sourceMappingURL=hooks-intelligence.js.map
|