0xray 4.0.34 → 4.0.35

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (155) hide show
  1. package/.grok-plugin/plugin.json +1 -1
  2. package/.xray/codex.json +12 -4
  3. package/.xray/features.json +1 -1
  4. package/AGENTS-consumer.md +6 -6
  5. package/AGENTS.md +5 -5
  6. package/README.md +2 -2
  7. package/dist/AGENTS.md +5 -5
  8. package/dist/CHANGELOG.md +16 -0
  9. package/dist/README.md +2 -2
  10. package/dist/cli/index.js +2 -5
  11. package/dist/governance/governance-service.js +1 -1
  12. package/dist/integrations/base/README.md +1 -9
  13. package/dist/integrations/base/index.d.ts +0 -1
  14. package/dist/integrations/base/index.js +0 -2
  15. package/dist/integrations/governance/index.js +31 -8
  16. package/dist/integrations/grok/hooks/grok-hook-utils.js +1 -1
  17. package/dist/integrations/grok/hooks/session-start.js +12 -0
  18. package/dist/integrations/hooks/goggles-pipeline.mjs +62 -11
  19. package/dist/integrations/hooks/host-truth.mjs +74 -0
  20. package/dist/integrations/hooks/station-hook-runtime.cjs +3 -0
  21. package/dist/integrations/openclaw/plugin/xray-pre-tool/package.json +1 -1
  22. package/dist/mcps/knowledge-skills/storyteller.server.js +0 -1
  23. package/dist/nucleus/delegation-gate.d.ts +2 -2
  24. package/dist/nucleus/delegation-gate.js +13 -2
  25. package/dist/nucleus/work-freshness.mjs +189 -0
  26. package/dist/processors/implementations/agents-md-validation-processor.js +1 -1
  27. package/docs-site/docs/plates/boot.md +17 -2
  28. package/docs-site/docs/plates/governance.md +3 -2
  29. package/docs-site/docs/plates/index.md +3 -1
  30. package/docs-site/docs/plates/memory-recall.md +26 -35
  31. package/docs-site/docs/plates/orchestration.md +39 -35
  32. package/docs-site/docs/plates/processor.md +34 -36
  33. package/docs-site/docs/plates/reporting.md +3 -8
  34. package/docs-site/docs/plates/routing.md +22 -11
  35. package/package.json +2 -2
  36. package/scripts/foundry/release.mjs +48 -5
  37. package/scripts/mjs/test-consumer-readiness.mjs +1 -0
  38. package/scripts/mjs/test-mcp-functionality.mjs +14 -9
  39. package/scripts/node/basic-security-audit.cjs +0 -1
  40. package/scripts/node/bridge-mcp-wiring.cjs +66 -3
  41. package/scripts/node/postinstall.cjs +1 -1
  42. package/scripts/node/prepare-consumer.cjs +11 -7
  43. package/scripts/node/setup-dev.cjs +18 -26
  44. package/scripts/node/validate-mcp-connectivity.js +2 -1
  45. package/src/integrations/openclaw/plugin/xray-pre-tool/package.json +1 -1
  46. package/src/mcps/knowledge-skills/storyteller.server.ts +0 -1
  47. package/xray/agents_template.md +5 -5
  48. package/xray/codex.json +12 -4
  49. package/xray/features.json +1 -1
  50. package/dist/agents/known-names.d.ts +0 -26
  51. package/dist/agents/known-names.js +0 -72
  52. package/dist/analytics/consent-manager.d.ts +0 -92
  53. package/dist/analytics/consent-manager.js +0 -257
  54. package/dist/benchmark/performance-benchmark.d.ts +0 -103
  55. package/dist/benchmark/performance-benchmark.js +0 -373
  56. package/dist/cli/commands/analytics-disable.d.ts +0 -9
  57. package/dist/cli/commands/analytics-disable.js +0 -72
  58. package/dist/cli/commands/analytics-enable-action.d.ts +0 -8
  59. package/dist/cli/commands/analytics-enable-action.js +0 -82
  60. package/dist/cli/commands/analytics-preview.d.ts +0 -9
  61. package/dist/cli/commands/analytics-preview.js +0 -106
  62. package/dist/cli/commands/analytics-status.d.ts +0 -9
  63. package/dist/cli/commands/analytics-status.js +0 -68
  64. package/dist/cli/commands/enforce.d.ts +0 -12
  65. package/dist/cli/commands/enforce.js +0 -78
  66. package/dist/cli/commands/govern.d.ts +0 -29
  67. package/dist/cli/commands/govern.js +0 -149
  68. package/dist/cli/commands/security-audit.d.ts +0 -23
  69. package/dist/cli/commands/security-audit.js +0 -219
  70. package/dist/cli/server.d.ts +0 -1
  71. package/dist/cli/server.js +0 -147
  72. package/dist/config/routing-mappings.d.ts +0 -26
  73. package/dist/config/routing-mappings.js +0 -151
  74. package/dist/core/bridge.mjs +0 -922
  75. package/dist/core/trace-context.d.ts +0 -12
  76. package/dist/core/trace-context.js +0 -33
  77. package/dist/enforcement/index.d.ts +0 -22
  78. package/dist/enforcement/index.js +0 -40
  79. package/dist/enforcement/loaders/index.d.ts +0 -36
  80. package/dist/enforcement/loaders/index.js +0 -39
  81. package/dist/enforcement/test-auto-healing.d.ts +0 -83
  82. package/dist/enforcement/test-auto-healing.js +0 -325
  83. package/dist/inference/index.d.ts +0 -10
  84. package/dist/inference/index.js +0 -5
  85. package/dist/infrastructure/iac-validator.d.ts +0 -150
  86. package/dist/infrastructure/iac-validator.js +0 -465
  87. package/dist/infrastructure/schemas/cloud-schemas.d.ts +0 -482
  88. package/dist/infrastructure/schemas/cloud-schemas.js +0 -488
  89. package/dist/integrations/base/ExampleIntegration.d.ts +0 -46
  90. package/dist/integrations/base/ExampleIntegration.js +0 -180
  91. package/dist/integrations/enforcement-gate.d.ts +0 -44
  92. package/dist/integrations/enforcement-gate.js +0 -348
  93. package/dist/mcps/connection/connection-manager.d.ts +0 -39
  94. package/dist/mcps/connection/connection-manager.js +0 -79
  95. package/dist/mcps/index.d.ts +0 -17
  96. package/dist/mcps/index.js +0 -65
  97. package/dist/mcps/orchestrator/index.d.ts +0 -6
  98. package/dist/mcps/orchestrator/index.js +0 -5
  99. package/dist/metrics/index.d.ts +0 -6
  100. package/dist/metrics/index.js +0 -6
  101. package/dist/orchestrator/self-direction-activation.d.ts +0 -108
  102. package/dist/orchestrator/self-direction-activation.js +0 -244
  103. package/dist/orchestrator/universal-registry-bridge.d.ts +0 -84
  104. package/dist/orchestrator/universal-registry-bridge.js +0 -246
  105. package/dist/performance/performance-budget-enforcer.d.ts +0 -157
  106. package/dist/performance/performance-budget-enforcer.js +0 -433
  107. package/dist/performance/performance-regression-tester.d.ts +0 -107
  108. package/dist/performance/performance-regression-tester.js +0 -341
  109. package/dist/postprocessor/analysis/CodeChangeAnalyzer.d.ts +0 -11
  110. package/dist/postprocessor/analysis/CodeChangeAnalyzer.js +0 -50
  111. package/dist/postprocessor/config/ProcessorConfigLoader.d.ts +0 -44
  112. package/dist/postprocessor/config/ProcessorConfigLoader.js +0 -16
  113. package/dist/postprocessor/integration.d.ts +0 -156
  114. package/dist/postprocessor/integration.js +0 -194
  115. package/dist/postprocessor/metamorphosis/index.d.ts +0 -2
  116. package/dist/postprocessor/metamorphosis/index.js +0 -1
  117. package/dist/postprocessor/redeploy/RetryHandler.d.ts +0 -49
  118. package/dist/postprocessor/redeploy/RetryHandler.js +0 -118
  119. package/dist/processors/implementations/session-capture-processor.d.ts +0 -14
  120. package/dist/processors/implementations/session-capture-processor.js +0 -37
  121. package/dist/public/XrayService.d.ts +0 -17
  122. package/dist/public/XrayService.js +0 -40
  123. package/dist/public/index.d.ts +0 -4
  124. package/dist/public/index.js +0 -2
  125. package/dist/security/comprehensive-security-audit.d.ts +0 -157
  126. package/dist/security/comprehensive-security-audit.js +0 -1004
  127. package/dist/security/index.d.ts +0 -13
  128. package/dist/security/index.js +0 -13
  129. package/dist/security/security-agent-coordinator.d.ts +0 -71
  130. package/dist/security/security-agent-coordinator.js +0 -203
  131. package/dist/security/security-hardening-system.d.ts +0 -238
  132. package/dist/security/security-hardening-system.js +0 -726
  133. package/dist/security/security-orchestration-layer.d.ts +0 -118
  134. package/dist/security/security-orchestration-layer.js +0 -495
  135. package/dist/testing/memory-regression-suite.d.ts +0 -105
  136. package/dist/testing/memory-regression-suite.js +0 -258
  137. package/dist/tools/assess-complexity-tool.d.ts +0 -28
  138. package/dist/tools/assess-complexity-tool.js +0 -44
  139. package/dist/tools/query-routing-tool.d.ts +0 -17
  140. package/dist/tools/query-routing-tool.js +0 -59
  141. package/dist/utils/batch-operations.d.ts +0 -25
  142. package/dist/utils/batch-operations.js +0 -292
  143. package/dist/utils/task-graph.d.ts +0 -29
  144. package/dist/utils/task-graph.js +0 -106
  145. package/dist/utils/test-template-generator.d.ts +0 -25
  146. package/dist/utils/test-template-generator.js +0 -178
  147. package/dist/utils/token-manager.d.ts +0 -48
  148. package/dist/utils/token-manager.js +0 -163
  149. package/dist/validation/agent-config-validator.d.ts +0 -110
  150. package/dist/validation/agent-config-validator.js +0 -280
  151. package/dist/validation/orchestration-flow-validator.d.ts +0 -87
  152. package/dist/validation/orchestration-flow-validator.js +0 -606
  153. package/src/mcps/connection/connection-manager.ts +0 -91
  154. package/src/mcps/index.ts +0 -80
  155. package/src/mcps/orchestrator/index.ts +0 -29
@@ -1,180 +0,0 @@
1
- /**
2
- * Example Integration - Demonstrates using the BaseIntegration class
3
- *
4
- * This is a simple example showing how to create a custom integration
5
- * that extends the BaseIntegration class.
6
- *
7
- * @since 2026-03-15
8
- */
9
- import { BaseIntegration, createSimpleIntegration, } from "./index.js";
10
- /**
11
- * Example custom integration
12
- *
13
- * Demonstrates how to extend BaseIntegration with custom logic.
14
- */
15
- class ExampleIntegration extends BaseIntegration {
16
- /** Custom property for this integration */
17
- connectionString = "";
18
- connected = false;
19
- /**
20
- * Create a new ExampleIntegration
21
- *
22
- * @param config - Optional configuration
23
- */
24
- constructor(config) {
25
- super("example-integration", "1.0.0", {
26
- enabled: true,
27
- debug: false,
28
- logLevel: "info",
29
- ...config,
30
- });
31
- }
32
- /**
33
- * Set connection string
34
- */
35
- setConnectionString(connStr) {
36
- this.connectionString = connStr;
37
- }
38
- /**
39
- * Check if connected
40
- */
41
- isConnected() {
42
- return this.connected;
43
- }
44
- // ==========================================================================
45
- // Protected abstract method implementations
46
- // ==========================================================================
47
- /**
48
- * Perform integration-specific initialization
49
- */
50
- async performInitialization() {
51
- await this.log("info", "Starting initialization...");
52
- // Simulate async initialization (e.g., connecting to a service)
53
- await new Promise((resolve) => setTimeout(resolve, 100));
54
- if (this.connectionString) {
55
- // Would connect to external service here
56
- this.connected = true;
57
- await this.log("success", "Connected to service");
58
- }
59
- // Emit custom event
60
- this.emit("custom-initialized", { connected: this.connected });
61
- }
62
- /**
63
- * Perform integration-specific shutdown
64
- */
65
- async performShutdown() {
66
- await this.log("info", "Starting shutdown...");
67
- // Simulate async cleanup
68
- await new Promise((resolve) => setTimeout(resolve, 50));
69
- this.connected = false;
70
- await this.log("success", "Shutdown complete");
71
- }
72
- /**
73
- * Perform integration-specific health check
74
- */
75
- async performHealthCheck() {
76
- if (!this.connected) {
77
- return {
78
- healthy: false,
79
- message: "Not connected to service",
80
- details: { connectionString: !!this.connectionString },
81
- };
82
- }
83
- // In a real integration, you might ping the service here
84
- return {
85
- healthy: true,
86
- message: "Service connection healthy",
87
- details: { connected: true },
88
- };
89
- }
90
- }
91
- // ==========================================================================
92
- // Usage Examples
93
- // ==========================================================================
94
- /**
95
- * Example 1: Using a custom integration class
96
- */
97
- async function exampleCustomIntegration() {
98
- console.log("\n--- Example 1: Custom Integration ---");
99
- // Create integration
100
- const integration = new ExampleIntegration({
101
- debug: true,
102
- logLevel: "debug",
103
- });
104
- // Set connection string
105
- integration.setConnectionString("http://localhost:3000");
106
- // Setup event listener
107
- integration.on("initialized", (event) => {
108
- console.log("Integration initialized event:", event.type);
109
- });
110
- // Initialize
111
- await integration.initialize();
112
- // Check health
113
- const health = await integration.healthCheck();
114
- console.log("Health check:", health);
115
- // Get stats
116
- const stats = integration.getStats();
117
- console.log("Stats:", stats);
118
- // Shutdown
119
- await integration.shutdown();
120
- }
121
- /**
122
- * Example 2: Using createSimpleIntegration factory
123
- */
124
- async function exampleSimpleIntegration() {
125
- console.log("\n--- Example 2: Simple Integration ---");
126
- // Create a simple integration without subclassing
127
- const simple = createSimpleIntegration("simple-integration", "1.0.0",
128
- // Custom health check
129
- async () => ({
130
- healthy: true,
131
- message: "Always healthy",
132
- }),
133
- // Custom shutdown
134
- async () => {
135
- console.log("Custom cleanup performed");
136
- });
137
- // Initialize
138
- await simple.initialize();
139
- // Check health
140
- const health = await simple.healthCheck();
141
- console.log("Health check:", health);
142
- // Shutdown
143
- await simple.shutdown();
144
- }
145
- /**
146
- * Example 3: Error handling
147
- */
148
- async function exampleErrorHandling() {
149
- console.log("\n--- Example 3: Error Handling ---");
150
- // Create integration that will fail to initialize
151
- class FailingIntegration extends BaseIntegration {
152
- constructor() {
153
- super("failing-integration", "1.0.0");
154
- }
155
- async performInitialization() {
156
- throw new Error("Connection refused");
157
- }
158
- async performShutdown() {
159
- // Cleanup even on failure
160
- }
161
- async performHealthCheck() {
162
- return { healthy: false, message: "Not initialized" };
163
- }
164
- }
165
- const failing = new FailingIntegration();
166
- try {
167
- await failing.initialize();
168
- }
169
- catch (error) {
170
- console.log("Caught expected error:", error instanceof Error ? error.message : error);
171
- }
172
- }
173
- // Run examples if this file is executed directly
174
- // (In a real project, you would import and use the classes)
175
- // Export for use in other modules
176
- export { ExampleIntegration };
177
- // Example usage (uncomment to run):
178
- // exampleCustomIntegration().catch(console.error);
179
- // exampleSimpleIntegration().catch(console.error);
180
- // exampleErrorHandling().catch(console.error);
@@ -1,44 +0,0 @@
1
- /**
2
- * Enforcement Gate — shared v3 pipeline entry point for TUI/CLI integration hooks.
3
- *
4
- * Provides beforeToolHook (early ValidatorRegistry + block decision) and
5
- * afterToolHook (post-tool v3 PostProcessor loop + governance routing) that
6
- * all four host integrations (OpenCode, Hermes, Grok, OpenClaw) call from
7
- * their programmatic hook surfaces (tool.execute.before/after, onPreToolCall,
8
- * PreToolUse, onToolBefore/onToolAfter).
9
- *
10
- * This is the canonical "how a TUI/CLI tool leverages v3 cleanly."
11
- *
12
- * @module integrations/enforcement-gate
13
- */
14
- export interface GateViolation {
15
- ruleId: string;
16
- severity: string;
17
- message: string;
18
- suggestions?: string[];
19
- }
20
- export interface BeforeHookResult {
21
- allowed: boolean;
22
- blocked: boolean;
23
- violations: GateViolation[];
24
- resonance: number;
25
- duration: number;
26
- }
27
- export interface AfterHookResult {
28
- processed: boolean;
29
- violations: GateViolation[];
30
- processorResults: Array<{
31
- name: string;
32
- success: boolean;
33
- error?: string;
34
- }>;
35
- governanceTriggered: boolean;
36
- duration: number;
37
- }
38
- export interface GateContext {
39
- directory?: string;
40
- projectRoot?: string;
41
- sessionId?: string;
42
- }
43
- export declare function beforeToolHook(tool: string, args: Record<string, unknown> | null, _context?: GateContext): Promise<BeforeHookResult>;
44
- export declare function afterToolHook(tool: string, args: Record<string, unknown> | null, _result: unknown, _error: string | null, _context?: GateContext): Promise<AfterHookResult>;
@@ -1,348 +0,0 @@
1
- /**
2
- * Enforcement Gate — shared v3 pipeline entry point for TUI/CLI integration hooks.
3
- *
4
- * Provides beforeToolHook (early ValidatorRegistry + block decision) and
5
- * afterToolHook (post-tool v3 PostProcessor loop + governance routing) that
6
- * all four host integrations (OpenCode, Hermes, Grok, OpenClaw) call from
7
- * their programmatic hook surfaces (tool.execute.before/after, onPreToolCall,
8
- * PreToolUse, onToolBefore/onToolAfter).
9
- *
10
- * This is the canonical "how a TUI/CLI tool leverages v3 cleanly."
11
- *
12
- * @module integrations/enforcement-gate
13
- */
14
- import { frameworkLogger } from "../core/framework-logger.js";
15
- // ── Registry Cache ─────────────────────────────────────────────
16
- function getGlobalRegistry() {
17
- if (globalThis.xrayValidatorRegistry) {
18
- return globalThis.xrayValidatorRegistry;
19
- }
20
- return null;
21
- }
22
- async function loadRegistry() {
23
- const cached = getGlobalRegistry();
24
- if (cached)
25
- return cached;
26
- const candidatePaths = [
27
- () => import("../enforcement/validators/validator-registry.js"),
28
- () => import(/* skip-ts */ "../../node_modules/0xray/dist/enforcement/validators/validator-registry.js"),
29
- ];
30
- for (const load of candidatePaths) {
31
- try {
32
- const mod = await load();
33
- const registry = mod.globalValidatorRegistry;
34
- if (registry) {
35
- globalThis.xrayValidatorRegistry = registry;
36
- return registry;
37
- }
38
- }
39
- catch {
40
- continue;
41
- }
42
- }
43
- return null;
44
- }
45
- // ── v3 PostProcessor Loader ────────────────────────────────────
46
- async function loadV3PostProcessor() {
47
- const global = globalThis;
48
- if (global.xrayPostProcessor && typeof global.xrayPostProcessor.executePostProcessorLoop === "function") {
49
- return global.xrayPostProcessor;
50
- }
51
- // xrayPostProcessor fallback removed in v2.2
52
- return null;
53
- }
54
- // ── Context Builder ────────────────────────────────────────────
55
- function buildValidationContext(tool, args) {
56
- const op = mapToolToOperation(tool);
57
- const files = [];
58
- let newCode;
59
- if (args) {
60
- const filePath = args.filePath || args.path || args.file || "";
61
- if (filePath)
62
- files.push(filePath);
63
- if (typeof args.content === "string") {
64
- newCode = args.content;
65
- }
66
- else if (typeof args.code === "string") {
67
- newCode = args.code;
68
- }
69
- else if (args.content instanceof Map && args.content.size > 0) {
70
- newCode = Array.from(args.content.values()).join("\n");
71
- }
72
- else if (args.newCode instanceof Map && args.newCode.size > 0) {
73
- newCode = Array.from(args.newCode.values()).join("\n");
74
- }
75
- }
76
- return { operation: op, files, ...(newCode ? { newCode } : {}) };
77
- }
78
- function mapToolToOperation(tool) {
79
- const writeTools = /^(write|edit|create|modify|patch|insert|replace|apply_diff|overwrite_file|write_file)$/i;
80
- const readTools = /^(read|search|find|list|grep|glob|lookup|get)$/i;
81
- const execTools = /^(run|execute|bash|terminal|command|shell)$/i;
82
- if (writeTools.test(tool))
83
- return "write";
84
- if (readTools.test(tool))
85
- return "read";
86
- if (execTools.test(tool))
87
- return "execute";
88
- return "modify";
89
- }
90
- function isCodeProducingTool(tool) {
91
- return mapToolToOperation(tool) === "write" || mapToolToOperation(tool) === "modify";
92
- }
93
- // ── beforeToolHook ─────────────────────────────────────────────
94
- export async function beforeToolHook(tool, args, _context) {
95
- const start = Date.now();
96
- try {
97
- const registry = await loadRegistry();
98
- if (!registry) {
99
- await frameworkLogger.log("enforcement-gate", "before-hook-registry-unavailable", "warning", { tool });
100
- return { allowed: true, blocked: false, violations: [], resonance: 0.85, duration: Date.now() - start };
101
- }
102
- const validationCtx = buildValidationContext(tool, args);
103
- const allValidators = registry.getAllValidators();
104
- const violations = [];
105
- for (const v of allValidators) {
106
- try {
107
- const result = await v.validate(validationCtx);
108
- if (!result.passed) {
109
- violations.push({
110
- ruleId: v.ruleId || v.id,
111
- severity: v.severity || "warning",
112
- message: result.message || `${v.id} violation detected`,
113
- ...(result.suggestions ? { suggestions: result.suggestions } : { suggestions: [] }),
114
- });
115
- }
116
- }
117
- catch (valErr) {
118
- await frameworkLogger.log("enforcement-gate", "validator-error", "warning", {
119
- ruleId: v.id,
120
- error: String(valErr),
121
- });
122
- }
123
- }
124
- const blockingViolations = violations.filter((v) => v.severity === "error" || v.severity === "blocking");
125
- const blocked = blockingViolations.length > 0;
126
- let resonance = 1.0;
127
- for (const v of violations) {
128
- resonance -= v.severity === "error" || v.severity === "blocking" ? 0.15 : 0.05;
129
- }
130
- resonance = Math.max(0.1, Math.min(1.0, resonance));
131
- if (blocked || violations.length > 0) {
132
- await frameworkLogger.log("enforcement-gate", "before-hook-result", blocked ? "error" : "warning", {
133
- tool,
134
- blocked,
135
- violationCount: violations.length,
136
- resonance,
137
- duration: Date.now() - start,
138
- violations: violations.map((v) => `[${v.severity}] ${v.ruleId}: ${v.message}`),
139
- });
140
- }
141
- return {
142
- allowed: !blocked,
143
- blocked,
144
- violations,
145
- resonance,
146
- duration: Date.now() - start,
147
- };
148
- }
149
- catch (err) {
150
- await frameworkLogger.log("enforcement-gate", "before-hook-error", "error", {
151
- tool,
152
- error: String(err),
153
- });
154
- return { allowed: true, blocked: false, violations: [], resonance: 0.85, duration: Date.now() - start };
155
- }
156
- }
157
- // ── afterToolHook ──────────────────────────────────────────────
158
- export async function afterToolHook(tool, args, _result, _error, _context) {
159
- const start = Date.now();
160
- try {
161
- if (!isCodeProducingTool(tool)) {
162
- return { processed: false, violations: [], processorResults: [], governanceTriggered: false, duration: Date.now() - start };
163
- }
164
- await frameworkLogger.log("enforcement-gate", "after-hook-start", "info", { tool });
165
- const registry = await loadRegistry();
166
- const violations = [];
167
- const processorResults = [];
168
- // Step 1: Run per-pipeline validators (same as PostProcessor.ts:382-432)
169
- if (registry) {
170
- const validationCtx = buildValidationContext(tool, args);
171
- const pipelineRules = ["error-resolution", "loop-safety", "boot-wiring", "console-log-usage"];
172
- for (const ruleId of pipelineRules) {
173
- try {
174
- const v = registry.getValidator(ruleId);
175
- if (!v)
176
- continue;
177
- const result = await v.validate(validationCtx);
178
- if (!result.passed) {
179
- violations.push({
180
- ruleId,
181
- severity: v.severity || "warning",
182
- message: result.message || `${ruleId} violation`,
183
- ...(result.suggestions ? { suggestions: result.suggestions } : { suggestions: [] }),
184
- });
185
- }
186
- }
187
- catch (valErr) {
188
- await frameworkLogger.log("enforcement-gate", "pipeline-validator-error", "warning", {
189
- ruleId,
190
- error: String(valErr),
191
- });
192
- }
193
- }
194
- }
195
- // Step 2: Legacy ProcessorManager compat (test-auto-creation etc.)
196
- try {
197
- const stateManager = await loadStateManager();
198
- const ProcessorManager = await loadProcessorManager();
199
- if (ProcessorManager && stateManager) {
200
- const pm = new ProcessorManager(stateManager);
201
- const config = { preProcessors: ["preValidate", "codexCompliance", "versionCompliance"] };
202
- const registered = await pm.registerAllProcessors(config);
203
- processorResults.push({ name: "register-processors", success: true });
204
- if (registered) {
205
- const preCtx = {
206
- operation: mapToolToOperation(tool),
207
- files: args?.filePath ? [args.filePath] : [],
208
- directory: process.cwd(),
209
- };
210
- await pm.executePreProcessors(preCtx);
211
- processorResults.push({ name: "pre-processors", success: true });
212
- }
213
- }
214
- }
215
- catch (pmErr) {
216
- processorResults.push({ name: "processor-manager", success: false, error: String(pmErr) });
217
- await frameworkLogger.log("enforcement-gate", "processor-error", "warning", {
218
- tool,
219
- error: String(pmErr),
220
- });
221
- }
222
- // Step 3: Try v3 PostProcessor loop (with critical violations from pipeline validators)
223
- try {
224
- const v3pp = await loadV3PostProcessor();
225
- if (v3pp) {
226
- const critical = violations.filter(v => v.severity === "error" || v.severity === "blocking");
227
- const postCtx = {
228
- trigger: "manual",
229
- operation: mapToolToOperation(tool),
230
- filePath: args?.filePath || args?.path || "",
231
- directory: process.cwd(),
232
- newCode: buildValidationContext(tool, args).newCode || "",
233
- files: buildValidationContext(tool, args).files || [],
234
- tool,
235
- metadata: { source: "enforcement-gate", hookType: "integration" },
236
- criticalViolations: critical.length > 0 ? critical : undefined,
237
- };
238
- await v3pp.executePostProcessorLoop(postCtx);
239
- processorResults.push({ name: "v3-post-processor-loop", success: true });
240
- }
241
- }
242
- catch (v3Err) {
243
- processorResults.push({ name: "v3-post-processor-loop", success: false, error: String(v3Err) });
244
- await frameworkLogger.log("enforcement-gate", "v3-post-processor-error", "warning", {
245
- tool,
246
- error: String(v3Err),
247
- });
248
- }
249
- // Step 4: Check for proposal-like results
250
- let governanceTriggered = false;
251
- try {
252
- const result = _result;
253
- if (result && typeof result === "object" && "title" in result && "description" in result) {
254
- const { handleGovernRequest } = await import("../nucleus/index.js");
255
- const localMode = process.env.XRAY_LOCAL_MODE === "1" || process.env.XRAY_LOCAL_MODE === "true";
256
- const governanceResult = await handleGovernRequest({
257
- proposals: [
258
- {
259
- id: `gate-${Date.now()}`,
260
- type: String(result.type || "fix"),
261
- title: String(result.title || ""),
262
- description: String(result.description || ""),
263
- evidence: [],
264
- source: "manual",
265
- metadata: result,
266
- },
267
- ],
268
- options: {
269
- requireExternalDynamo: localMode ? false : undefined,
270
- },
271
- });
272
- governanceTriggered = governanceResult?.overallDecision === 'approve';
273
- if (governanceTriggered) {
274
- await frameworkLogger.log("enforcement-gate", "governance-triggered", "info", {
275
- tool,
276
- proposalTitle: String(result.title),
277
- });
278
- }
279
- }
280
- }
281
- catch (govErr) {
282
- await frameworkLogger.log("enforcement-gate", "governance-error", "warning", {
283
- tool,
284
- error: String(govErr),
285
- });
286
- }
287
- await frameworkLogger.log("enforcement-gate", "after-hook-complete", "info", {
288
- tool,
289
- violations: violations.length,
290
- processors: processorResults.length,
291
- governanceTriggered,
292
- duration: Date.now() - start,
293
- });
294
- return {
295
- processed: true,
296
- violations,
297
- processorResults,
298
- governanceTriggered,
299
- duration: Date.now() - start,
300
- };
301
- }
302
- catch (err) {
303
- await frameworkLogger.log("enforcement-gate", "after-hook-error", "error", {
304
- tool,
305
- error: String(err),
306
- });
307
- return { processed: false, violations: [], processorResults: [], governanceTriggered: false, duration: Date.now() - start };
308
- }
309
- }
310
- // ── Helpers ────────────────────────────────────────────────────
311
- async function loadStateManager() {
312
- const global = globalThis;
313
- if (global.xrayStateManager)
314
- return global.xrayStateManager;
315
- // xrayStateManager fallback removed in v2.2
316
- const candidatePaths = [
317
- () => import("../state/state-manager.js"),
318
- () => import(/* skip-ts */ "../../node_modules/0xray/dist/state/state-manager.js"),
319
- ];
320
- for (const load of candidatePaths) {
321
- try {
322
- const mod = await load();
323
- const SM = mod.XrayStateManager;
324
- if (SM)
325
- return SM;
326
- }
327
- catch {
328
- continue;
329
- }
330
- }
331
- return null;
332
- }
333
- async function loadProcessorManager() {
334
- const candidatePaths = [
335
- () => import("../processors/processor-manager.js"),
336
- () => import(/* skip-ts */ "../../node_modules/0xray/dist/processors/processor-manager.js"),
337
- ];
338
- for (const load of candidatePaths) {
339
- try {
340
- const mod = await load();
341
- return mod.ProcessorManager;
342
- }
343
- catch {
344
- continue;
345
- }
346
- }
347
- return null;
348
- }
@@ -1,39 +0,0 @@
1
- import { IMcpConnection, IServerConfig } from '../types/index.js';
2
- /**
3
- * Connection Manager
4
- * Manages MCP connection lifecycle and provides centralized access to connections
5
- */
6
- export declare class ConnectionManager {
7
- private connections;
8
- /**
9
- * Get or create a connection for a server
10
- * @param config - Server configuration
11
- * @returns Promise resolving to an MCP connection
12
- */
13
- getConnection(config: IServerConfig): Promise<IMcpConnection>;
14
- /**
15
- * Disconnect a specific server
16
- * @param serverName - Name of the server to disconnect
17
- */
18
- disconnect(serverName: string): Promise<void>;
19
- /**
20
- * Disconnect all managed connections
21
- */
22
- disconnectAll(): Promise<void>;
23
- /**
24
- * Check if a connection exists for a server
25
- * @param serverName - Name of the server
26
- * @returns True if connection exists and is connected
27
- */
28
- hasConnection(serverName: string): boolean;
29
- /**
30
- * Get all connected server names
31
- * @returns Array of server names
32
- */
33
- getConnectedServers(): string[];
34
- /**
35
- * Get the number of active connections
36
- * @returns Number of connections
37
- */
38
- getConnectionCount(): number;
39
- }
@@ -1,79 +0,0 @@
1
- import { McpConnection } from './mcp-connection.js';
2
- import { frameworkLogger } from '../../core/framework-logger.js';
3
- /**
4
- * Connection Manager
5
- * Manages MCP connection lifecycle and provides centralized access to connections
6
- */
7
- export class ConnectionManager {
8
- connections = new Map();
9
- /**
10
- * Get or create a connection for a server
11
- * @param config - Server configuration
12
- * @returns Promise resolving to an MCP connection
13
- */
14
- async getConnection(config) {
15
- const existingConnection = this.connections.get(config.serverName);
16
- if (existingConnection && existingConnection.isConnected) {
17
- return existingConnection;
18
- }
19
- // If existing connection is disconnected, remove it
20
- if (existingConnection) {
21
- await existingConnection.disconnect();
22
- this.connections.delete(config.serverName);
23
- }
24
- // Create new connection
25
- const connection = new McpConnection(config);
26
- await connection.connect();
27
- this.connections.set(config.serverName, connection);
28
- return connection;
29
- }
30
- /**
31
- * Disconnect a specific server
32
- * @param serverName - Name of the server to disconnect
33
- */
34
- async disconnect(serverName) {
35
- const connection = this.connections.get(serverName);
36
- if (connection) {
37
- await connection.disconnect();
38
- this.connections.delete(serverName);
39
- }
40
- }
41
- /**
42
- * Disconnect all managed connections
43
- */
44
- async disconnectAll() {
45
- const disconnectPromises = [];
46
- for (const [serverName, connection] of this.connections) {
47
- disconnectPromises.push(connection.disconnect().catch((error) => {
48
- frameworkLogger.log("connection-manager", "disconnect-error", "error", { serverName, error });
49
- }));
50
- }
51
- await Promise.all(disconnectPromises);
52
- this.connections.clear();
53
- }
54
- /**
55
- * Check if a connection exists for a server
56
- * @param serverName - Name of the server
57
- * @returns True if connection exists and is connected
58
- */
59
- hasConnection(serverName) {
60
- const connection = this.connections.get(serverName);
61
- return connection !== undefined && connection.isConnected;
62
- }
63
- /**
64
- * Get all connected server names
65
- * @returns Array of server names
66
- */
67
- getConnectedServers() {
68
- return Array.from(this.connections.entries())
69
- .filter(([, connection]) => connection.isConnected)
70
- .map(([name]) => name);
71
- }
72
- /**
73
- * Get the number of active connections
74
- * @returns Number of connections
75
- */
76
- getConnectionCount() {
77
- return this.getConnectedServers().length;
78
- }
79
- }