0xray 2.1.4 → 2.2.1

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 (186) hide show
  1. package/.opencode/codex.codex +1 -1
  2. package/.opencode/commands/dependency-audit.md +3 -3
  3. package/.opencode/enforcer-config.json +2 -2
  4. package/.opencode/init.sh +1 -1
  5. package/AGENTS.md +6 -6
  6. package/README.md +4 -4
  7. package/dist/AGENTS.md +6 -6
  8. package/dist/CHANGELOG.md +39 -0
  9. package/dist/README.md +4 -4
  10. package/dist/agents/code-reviewer.js +1 -1
  11. package/dist/analytics/routing-refiner.js +1 -1
  12. package/dist/cli/commands/govern.d.ts +29 -0
  13. package/dist/cli/commands/govern.js +152 -0
  14. package/dist/cli/index.js +29 -216
  15. package/dist/core/boot-orchestrator.js +2 -2
  16. package/dist/core/features-config.js +1 -1
  17. package/dist/core/framework-logger.d.ts +1 -0
  18. package/dist/core/framework-logger.js +57 -2
  19. package/dist/delegation/index.d.ts +1 -2
  20. package/dist/delegation/index.js +1 -2
  21. package/dist/enforcement/enforcer-tools.js +1 -1
  22. package/dist/execution/proposal-applier.d.ts +1 -9
  23. package/dist/execution/proposal-applier.js +18 -173
  24. package/dist/governance/codex-policy.service.d.ts +7 -25
  25. package/dist/governance/codex-policy.service.js +8 -26
  26. package/dist/governance/governance-core.d.ts +22 -28
  27. package/dist/governance/governance-core.js +31 -101
  28. package/dist/governance/governance-service.d.ts +1 -0
  29. package/dist/governance/governance-service.js +67 -4
  30. package/dist/governance/governance-types.d.ts +5 -2
  31. package/dist/inference/index.d.ts +3 -4
  32. package/dist/inference/inference-accumulator.js +1 -1
  33. package/dist/inference/inference-cycle.d.ts +12 -18
  34. package/dist/inference/inference-cycle.js +120 -335
  35. package/dist/integrations/base/index.d.ts +0 -1
  36. package/dist/integrations/base/index.js +0 -2
  37. package/dist/integrations/grok/hooks/pre-tool-use.js +4 -18
  38. package/dist/integrations/hermes-agent/bridge.mjs +9 -0
  39. package/dist/mcps/config/server-config-registry.js +1 -1
  40. package/dist/mcps/governance.server.js +4 -5
  41. package/dist/mcps/knowledge-skills/api-design.server.js +10 -0
  42. package/dist/mcps/knowledge-skills/architecture-patterns.server.js +10 -0
  43. package/dist/mcps/knowledge-skills/bug-triage-specialist.server.js +10 -0
  44. package/dist/mcps/knowledge-skills/code-analyzer.server.js +10 -0
  45. package/dist/mcps/knowledge-skills/code-review.server.js +10 -0
  46. package/dist/mcps/knowledge-skills/content-creator.server.js +10 -0
  47. package/dist/mcps/knowledge-skills/database-design.server.js +10 -0
  48. package/dist/mcps/knowledge-skills/devops-deployment.server.js +10 -0
  49. package/dist/mcps/knowledge-skills/git-workflow.server.js +10 -0
  50. package/dist/mcps/knowledge-skills/growth-strategist.server.js +10 -0
  51. package/dist/mcps/knowledge-skills/log-monitor.server.js +10 -0
  52. package/dist/mcps/knowledge-skills/mobile-development.server.js +10 -0
  53. package/dist/mcps/knowledge-skills/multimodal-looker.server.js +10 -0
  54. package/dist/mcps/knowledge-skills/performance-optimization.server.js +10 -0
  55. package/dist/mcps/knowledge-skills/project-analysis.server.js +10 -0
  56. package/dist/mcps/knowledge-skills/refactoring-strategies.server.js +10 -0
  57. package/dist/mcps/knowledge-skills/security-audit.server.js +10 -0
  58. package/dist/mcps/knowledge-skills/seo-consultant.server.js +10 -0
  59. package/dist/mcps/knowledge-skills/skill-invocation.server.d.ts +4 -0
  60. package/dist/mcps/knowledge-skills/skill-invocation.server.js +33 -14
  61. package/dist/mcps/knowledge-skills/strategist.server.js +10 -0
  62. package/dist/mcps/knowledge-skills/tech-writer.server.js +11 -1
  63. package/dist/mcps/knowledge-skills/testing-strategy.server.js +10 -0
  64. package/dist/mcps/knowledge-skills/ui-ux-design.server.js +10 -0
  65. package/dist/mcps/registry.json +1 -1
  66. package/dist/mcps/simulation/server-simulations.js +1 -1
  67. package/dist/metrics/agent-metrics.d.ts +2 -1
  68. package/dist/nucleus/govern-http.d.ts +59 -0
  69. package/dist/nucleus/govern-http.js +172 -0
  70. package/dist/nucleus/index.d.ts +14 -0
  71. package/dist/nucleus/index.js +9 -0
  72. package/dist/nucleus/kernel.d.ts +51 -0
  73. package/dist/nucleus/kernel.js +62 -0
  74. package/dist/nucleus/plugin-registry.d.ts +104 -0
  75. package/dist/nucleus/plugin-registry.js +147 -0
  76. package/dist/orchestrator/orchestrator.d.ts +0 -1
  77. package/dist/orchestrator/orchestrator.js +0 -21
  78. package/dist/postprocessor/PostProcessor.d.ts +13 -1
  79. package/dist/postprocessor/PostProcessor.js +41 -1
  80. package/dist/postprocessor/autofix/AutoFixEngine.d.ts +0 -8
  81. package/dist/postprocessor/autofix/AutoFixEngine.js +0 -54
  82. package/dist/postprocessor/metamorphosis/MetamorphosisEngine.d.ts +25 -0
  83. package/dist/postprocessor/metamorphosis/MetamorphosisEngine.js +10 -0
  84. package/dist/postprocessor/metamorphosis/SelfProposalEngine.d.ts +68 -0
  85. package/dist/postprocessor/metamorphosis/SelfProposalEngine.js +371 -0
  86. package/dist/skills/orchestrator/SKILL.md +1 -1
  87. package/dist/skills/registry.json +1 -1
  88. package/dist/state/index.d.ts +0 -2
  89. package/package.json +4 -3
  90. package/scripts/node/universal-version-manager.js +9 -9
  91. package/scripts/node/validate-mcp-connectivity.js +1 -1
  92. package/src/mcps/config/__tests__/server-config-registry.test.ts +6 -15
  93. package/src/mcps/config/server-config-registry.ts +1 -1
  94. package/src/mcps/governance.server.ts +4 -6
  95. package/src/mcps/knowledge-skills/api-design.server.ts +9 -0
  96. package/src/mcps/knowledge-skills/architecture-patterns.server.ts +9 -0
  97. package/src/mcps/knowledge-skills/bug-triage-specialist.server.ts +9 -0
  98. package/src/mcps/knowledge-skills/code-analyzer.server.ts +9 -0
  99. package/src/mcps/knowledge-skills/code-review.server.ts +9 -0
  100. package/src/mcps/knowledge-skills/content-creator.server.ts +9 -0
  101. package/src/mcps/knowledge-skills/database-design.server.ts +9 -0
  102. package/src/mcps/knowledge-skills/devops-deployment.server.ts +9 -0
  103. package/src/mcps/knowledge-skills/git-workflow.server.ts +9 -0
  104. package/src/mcps/knowledge-skills/growth-strategist.server.ts +9 -0
  105. package/src/mcps/knowledge-skills/log-monitor.server.ts +9 -0
  106. package/src/mcps/knowledge-skills/mobile-development.server.ts +9 -0
  107. package/src/mcps/knowledge-skills/multimodal-looker.server.ts +9 -0
  108. package/src/mcps/knowledge-skills/performance-optimization.server.ts +9 -0
  109. package/src/mcps/knowledge-skills/project-analysis.server.ts +9 -0
  110. package/src/mcps/knowledge-skills/refactoring-strategies.server.ts +9 -0
  111. package/src/mcps/knowledge-skills/security-audit.server.ts +9 -0
  112. package/src/mcps/knowledge-skills/seo-consultant.server.ts +9 -0
  113. package/src/mcps/knowledge-skills/session-management.server.ts +1 -0
  114. package/src/mcps/knowledge-skills/skill-invocation.server.ts +44 -29
  115. package/src/mcps/knowledge-skills/strategist.server.ts +9 -0
  116. package/src/mcps/knowledge-skills/tech-writer.server.ts +10 -1
  117. package/src/mcps/knowledge-skills/testing-strategy.server.ts +9 -0
  118. package/src/mcps/knowledge-skills/ui-ux-design.server.ts +9 -0
  119. package/src/mcps/registry.json +1 -1
  120. package/src/mcps/simulation/server-simulations.ts +1 -1
  121. package/src/opencode/codex.codex +1 -1
  122. package/src/opencode/commands/dependency-audit.md +3 -3
  123. package/src/opencode/enforcer-config.json +2 -2
  124. package/src/skills/orchestrator/SKILL.md +1 -1
  125. package/src/skills/registry.json +1 -1
  126. package/xray/codex.json +1 -1
  127. package/xray/config.json +1 -1
  128. package/xray/features.json +1 -1
  129. package/xray/integrations.json +3 -3
  130. package/.opencode/agents/testing-best-practices.yml +0 -12
  131. package/dist/analytics/consent-manager.d.ts +0 -93
  132. package/dist/analytics/consent-manager.js +0 -258
  133. package/dist/analytics/simple-pattern-analyzer.d.ts +0 -80
  134. package/dist/analytics/simple-pattern-analyzer.js +0 -297
  135. package/dist/cli/commands/analytics-disable.d.ts +0 -9
  136. package/dist/cli/commands/analytics-disable.js +0 -72
  137. package/dist/cli/commands/analytics-enable-action.d.ts +0 -8
  138. package/dist/cli/commands/analytics-enable-action.js +0 -82
  139. package/dist/cli/commands/analytics-preview.d.ts +0 -9
  140. package/dist/cli/commands/analytics-preview.js +0 -106
  141. package/dist/cli/commands/analytics-status.d.ts +0 -9
  142. package/dist/cli/commands/analytics-status.js +0 -68
  143. package/dist/cli/server.d.ts +0 -1
  144. package/dist/cli/server.js +0 -147
  145. package/dist/core/errors.d.ts +0 -3
  146. package/dist/core/errors.js +0 -10
  147. package/dist/core/logging-config.d.ts +0 -11
  148. package/dist/core/logging-config.js +0 -43
  149. package/dist/core/trace-context.d.ts +0 -12
  150. package/dist/core/trace-context.js +0 -33
  151. package/dist/delegation/voting-coordinator.d.ts +0 -49
  152. package/dist/delegation/voting-coordinator.js +0 -375
  153. package/dist/enforcement/test-auto-healing.d.ts +0 -83
  154. package/dist/enforcement/test-auto-healing.js +0 -325
  155. package/dist/integrations/base/ExampleIntegration.d.ts +0 -47
  156. package/dist/integrations/base/ExampleIntegration.js +0 -181
  157. package/dist/mcps/knowledge-skills/testing-best-practices.server.d.ts +0 -34
  158. package/dist/mcps/knowledge-skills/testing-best-practices.server.js +0 -831
  159. package/dist/mcps/orchestrator.server.d.ts +0 -10
  160. package/dist/mcps/orchestrator.server.js +0 -19
  161. package/dist/orchestrator/self-direction-activation.d.ts +0 -109
  162. package/dist/orchestrator/self-direction-activation.js +0 -245
  163. package/dist/orchestrator/universal-librarian-consultation.d.ts +0 -98
  164. package/dist/orchestrator/universal-librarian-consultation.js +0 -216
  165. package/dist/orchestrator/universal-registry-bridge.d.ts +0 -85
  166. package/dist/orchestrator/universal-registry-bridge.js +0 -247
  167. package/dist/performance/performance-budget-enforcer.d.ts +0 -158
  168. package/dist/performance/performance-budget-enforcer.js +0 -434
  169. package/dist/performance/performance-regression-tester.d.ts +0 -108
  170. package/dist/performance/performance-regression-tester.js +0 -342
  171. package/dist/skills/testing-best-practices/SKILL.md +0 -37
  172. package/dist/state/context-providers.d.ts +0 -4
  173. package/dist/state/context-providers.js +0 -1
  174. package/dist/state/state-types.d.ts +0 -5
  175. package/dist/state/state-types.js +0 -1
  176. package/dist/utils/batch-operations.d.ts +0 -25
  177. package/dist/utils/batch-operations.js +0 -292
  178. package/dist/utils/test-template-generator.d.ts +0 -25
  179. package/dist/utils/test-template-generator.js +0 -178
  180. package/dist/utils/token-manager.d.ts +0 -48
  181. package/dist/utils/token-manager.js +0 -163
  182. package/src/mcps/knowledge-skills/testing-best-practices.server.test.ts +0 -136
  183. package/src/mcps/knowledge-skills/testing-best-practices.server.ts +0 -1183
  184. package/src/mcps/orchestrator.server.ts +0 -34
  185. package/src/opencode/agents/testing-best-practices.yml +0 -12
  186. package/src/skills/testing-best-practices/SKILL.md +0 -37
@@ -1,21 +1,10 @@
1
1
  import * as fs from "fs";
2
2
  import * as path from "path";
3
- import { spawnSync } from "child_process";
4
3
  import { frameworkLogger } from "../core/framework-logger.js";
5
- function sanitizeGitArgument(s) {
6
- if (!/^[a-zA-Z0-9 \-_.\/@]+$/.test(s)) {
7
- throw new Error("Invalid git argument: contains disallowed characters");
8
- }
9
- return s;
10
- }
11
4
  export class ProposalApplier {
12
5
  projectRoot;
13
- codeChangeCallback;
14
- reviewCallback;
15
- constructor(projectRoot = process.cwd(), codeChangeCallback, reviewCallback) {
6
+ constructor(projectRoot = process.cwd()) {
16
7
  this.projectRoot = projectRoot;
17
- this.codeChangeCallback = codeChangeCallback;
18
- this.reviewCallback = reviewCallback;
19
8
  }
20
9
  async applyProposals(proposals) {
21
10
  frameworkLogger.log("execution", "proposal-applier-start", "info", {
@@ -23,112 +12,26 @@ export class ProposalApplier {
23
12
  });
24
13
  const results = [];
25
14
  for (const proposal of proposals) {
26
- const result = await this.applyProposal(proposal);
27
- results.push(result);
28
- }
29
- return results;
30
- }
31
- async applyProposal(p) {
32
- frameworkLogger.log("execution", "apply-proposal", "info", {
33
- proposalId: p.id,
34
- type: p.type,
35
- });
36
- if (p.type === "codify") {
37
- return this.applyCodification(p);
38
- }
39
- const branchName = `inference/${p.type}-${Date.now()}`;
40
- const isGit = this.isInsideGitRepo();
41
- try {
42
- this.recordAppliedProposal(p);
43
- const changedFiles = [
44
- path.relative(this.projectRoot, this.getAppliedMarkerPath(p)),
45
- ];
46
- if (isGit) {
47
- const branchR = spawnSync('git', ['checkout', '-b', branchName], { cwd: this.projectRoot, stdio: 'pipe' });
48
- if (branchR.status !== 0) {
49
- throw new Error(`git checkout -b failed: ${(branchR.stderr || '').toString().trim()}`);
50
- }
15
+ if (proposal.type === "codify") {
16
+ results.push(this.applyCodification(proposal));
51
17
  }
52
- if (this.codeChangeCallback) {
53
- const changed = await this.codeChangeCallback(p);
54
- if (!changed) {
55
- if (isGit) {
56
- spawnSync('git', ['checkout', 'master'], { cwd: this.projectRoot, stdio: 'pipe' });
57
- spawnSync('git', ['branch', '-D', branchName], { cwd: this.projectRoot, stdio: 'pipe' });
58
- }
59
- return {
60
- proposalId: p.id,
61
- success: false,
62
- error: "Code change returned false (no changes applied)",
63
- };
64
- }
18
+ else {
19
+ this.recordAppliedProposal(proposal);
20
+ const changedFiles = [
21
+ path.relative(this.projectRoot, this.getAppliedMarkerPath(proposal)),
22
+ ];
23
+ results.push({
24
+ proposalId: proposal.id,
25
+ success: true,
26
+ filesChanged: changedFiles,
27
+ details: [
28
+ "Proposal recorded by Autonomous Engine (ProposalApplier)",
29
+ `type=${proposal.type}`,
30
+ ],
31
+ });
65
32
  }
66
- if (isGit) {
67
- const addR = spawnSync('git', ['add', '-A'], { cwd: this.projectRoot, stdio: 'pipe' });
68
- if (addR.status !== 0) {
69
- throw new Error(`git add failed: ${(addR.stderr || '').toString().trim()}`);
70
- }
71
- const commitR = spawnSync('git', ['commit', '-m', p.title], { cwd: this.projectRoot, stdio: 'pipe' });
72
- if (commitR.status !== 0) {
73
- throw new Error(`git commit failed: ${(commitR.stderr || '').toString().trim()}`);
74
- }
75
- const prUrl = this.createPR(p, branchName);
76
- if (prUrl) {
77
- frameworkLogger.log("execution", "pr-created", "info", {
78
- prUrl,
79
- proposalId: p.id,
80
- });
81
- }
82
- if (this.reviewCallback && prUrl) {
83
- const review = await this.reviewCallback(p, prUrl);
84
- if (review === "no-go") {
85
- frameworkLogger.log("execution", "review-no-go", "warning", {
86
- proposalId: p.id,
87
- prUrl,
88
- });
89
- spawnSync('git', ['checkout', 'master'], { cwd: this.projectRoot, stdio: 'pipe' });
90
- spawnSync('git', ['branch', '-D', branchName], { cwd: this.projectRoot, stdio: 'pipe' });
91
- return {
92
- proposalId: p.id,
93
- success: false,
94
- error: "Researcher review rejected proposal",
95
- };
96
- }
97
- }
98
- spawnSync('git', ['checkout', 'master'], { cwd: this.projectRoot, stdio: 'pipe' });
99
- }
100
- return {
101
- proposalId: p.id,
102
- success: true,
103
- filesChanged: changedFiles,
104
- details: [
105
- "Proposal applied by Autonomous Engine (ProposalApplier)",
106
- isGit ? `branch=${branchName}` : "non-git (marker only)",
107
- `type=${p.type}`,
108
- ],
109
- };
110
- }
111
- catch (err) {
112
- const errorMsg = err.message;
113
- frameworkLogger.log("execution", "apply-proposal-error", "error", {
114
- proposalId: p.id,
115
- error: errorMsg,
116
- });
117
- if (isGit) {
118
- try {
119
- spawnSync('git', ['checkout', 'master'], { cwd: this.projectRoot, stdio: 'pipe' });
120
- spawnSync('git', ['branch', '-D', branchName], { cwd: this.projectRoot, stdio: 'pipe' });
121
- }
122
- catch {
123
- // ignore cleanup
124
- }
125
- }
126
- return {
127
- proposalId: p.id,
128
- success: false,
129
- error: errorMsg,
130
- };
131
33
  }
34
+ return results;
132
35
  }
133
36
  applyCodification(p) {
134
37
  try {
@@ -159,19 +62,6 @@ export class ProposalApplier {
159
62
  return { proposalId: p.id, success: false, error: errorMsg };
160
63
  }
161
64
  }
162
- isInsideGitRepo() {
163
- try {
164
- const r = spawnSync('git', ['rev-parse', '--is-inside-work-tree'], {
165
- cwd: this.projectRoot,
166
- stdio: 'pipe',
167
- timeout: 2000,
168
- });
169
- return r.status === 0;
170
- }
171
- catch {
172
- return false;
173
- }
174
- }
175
65
  getAppliedMarkerPath(p) {
176
66
  const appliedDir = path.join(this.projectRoot, "docs", "inference", "applied");
177
67
  if (!fs.existsSync(appliedDir)) {
@@ -206,49 +96,4 @@ export class ProposalApplier {
206
96
  module: "v2-refactor",
207
97
  });
208
98
  }
209
- createPR(p, branchName) {
210
- try {
211
- sanitizeGitArgument(p.title);
212
- sanitizeGitArgument(branchName);
213
- const pushR = spawnSync('git', ['push', '-u', 'origin', branchName], {
214
- cwd: this.projectRoot,
215
- stdio: 'pipe',
216
- timeout: 30000,
217
- });
218
- if (pushR.status !== 0) {
219
- throw new Error(`git push failed: ${(pushR.stderr || '').toString().trim()}`);
220
- }
221
- const body = [
222
- "## Inference Proposal (Autonomous Engine)",
223
- "",
224
- p.description,
225
- "",
226
- `**Type:** ${p.type} **Confidence:** ${(p.confidence * 100).toFixed(0)}%`,
227
- "",
228
- "## Evidence",
229
- p.evidence.slice(0, 5).join("\n"),
230
- "",
231
- "Executed by ProposalApplier (Engine-owned) — V2 Phase 1.",
232
- ].join("\n");
233
- const ghR = spawnSync('gh', ['pr', 'create', '--head', branchName, '--title', p.title, '--body', body], {
234
- cwd: this.projectRoot,
235
- encoding: 'utf-8',
236
- stdio: 'pipe',
237
- timeout: 30000,
238
- });
239
- if (ghR.status !== 0) {
240
- throw new Error(`gh pr create failed: ${ghR.stderr || 'unknown error'}`);
241
- }
242
- return (ghR.stdout || '').trim();
243
- }
244
- catch (err) {
245
- frameworkLogger.log("execution", "pr-create-failed", "warning", {
246
- error: String(err),
247
- proposalId: p.id,
248
- module: "v2-refactor",
249
- });
250
- return "";
251
- }
252
- }
253
99
  }
254
- export const proposalApplier = new ProposalApplier();
@@ -1,32 +1,15 @@
1
1
  /**
2
2
  * CodexPolicyService
3
3
  *
4
- * The initial Governance-owned Single Source of Truth (SSOT) for Codex / policy loading.
5
- * This is the V2-P1-S02-REAL first concrete migration slice.
4
+ * Governance-owned Single Source of Truth (SSOT) for Codex / policy loading.
6
5
  *
7
- * Role (per 3-subsystem architecture + researcher mapping):
8
- * - External Governance (Decision Layer & SSOT) owns "what the policy is".
9
- * - All consumers (enforcement CodexLoader, injectors, formatters, MCP surfaces, plugins)
10
- * will eventually ask here instead of performing direct fs reads.
6
+ * Role: External Governance owns "what the policy is".
7
+ * Consumers (enforcers, injectors, formatters, MCPs, plugins) should ask here
8
+ * instead of direct fs reads or scattered loaders.
11
9
  *
12
- * Current scope (minimal safe skeleton):
13
- * - Read-only query surface.
14
- * - Uses canonical resolveCodexPath + async file load (no duplication of resolution logic).
15
- * - Returns ActiveCodexSnapshot compatible with the existing get_active_codex MCP tool.
16
- * - Provides getTermCount() with safe 60-term fallback (preserves prior behavior of bypasses).
17
- * - Full frameworkLogger discipline on every load/decision/error.
18
- * - No caching in v1 skeleton (additive later); no mutation; no enforcement.
19
- *
20
- * First wired consumer: src/mcps/enforcer-tools.server.ts (getCodexTermCount bypass removed;
21
- * now delegates through this service).
22
- *
23
- * Next recommended slices (documented in researcher mapping append):
24
- * - Wire governance.server.ts handleGetActiveCodex to delegate (remove its direct read).
25
- * - S02b/S02c follow-ups: update codex-injector, context-loader, codex-formatter, plugin.
26
- * - Make CodexLoader delegate its raw data load here, then re-export from governance.
27
- *
28
- * @module governance/codex-policy.service
29
- * @version 2.0.0-s02-real
10
+ * Provides read-only ActiveCodexSnapshot and term count.
11
+ * Uses canonical resolveCodexPath.
12
+ * Full frameworkLogger on all paths.
30
13
  */
31
14
  import type { ActiveCodexSnapshot, ICodexPolicyProvider } from './governance-types.js';
32
15
  /**
@@ -54,4 +37,3 @@ export declare class CodexPolicyService implements ICodexPolicyProvider {
54
37
  getTermCount(): Promise<number>;
55
38
  }
56
39
  export declare function getCodexPolicyService(): CodexPolicyService;
57
- export { CodexPolicyService as default };
@@ -1,32 +1,15 @@
1
1
  /**
2
2
  * CodexPolicyService
3
3
  *
4
- * The initial Governance-owned Single Source of Truth (SSOT) for Codex / policy loading.
5
- * This is the V2-P1-S02-REAL first concrete migration slice.
4
+ * Governance-owned Single Source of Truth (SSOT) for Codex / policy loading.
6
5
  *
7
- * Role (per 3-subsystem architecture + researcher mapping):
8
- * - External Governance (Decision Layer & SSOT) owns "what the policy is".
9
- * - All consumers (enforcement CodexLoader, injectors, formatters, MCP surfaces, plugins)
10
- * will eventually ask here instead of performing direct fs reads.
6
+ * Role: External Governance owns "what the policy is".
7
+ * Consumers (enforcers, injectors, formatters, MCPs, plugins) should ask here
8
+ * instead of direct fs reads or scattered loaders.
11
9
  *
12
- * Current scope (minimal safe skeleton):
13
- * - Read-only query surface.
14
- * - Uses canonical resolveCodexPath + async file load (no duplication of resolution logic).
15
- * - Returns ActiveCodexSnapshot compatible with the existing get_active_codex MCP tool.
16
- * - Provides getTermCount() with safe 60-term fallback (preserves prior behavior of bypasses).
17
- * - Full frameworkLogger discipline on every load/decision/error.
18
- * - No caching in v1 skeleton (additive later); no mutation; no enforcement.
19
- *
20
- * First wired consumer: src/mcps/enforcer-tools.server.ts (getCodexTermCount bypass removed;
21
- * now delegates through this service).
22
- *
23
- * Next recommended slices (documented in researcher mapping append):
24
- * - Wire governance.server.ts handleGetActiveCodex to delegate (remove its direct read).
25
- * - S02b/S02c follow-ups: update codex-injector, context-loader, codex-formatter, plugin.
26
- * - Make CodexLoader delegate its raw data load here, then re-export from governance.
27
- *
28
- * @module governance/codex-policy.service
29
- * @version 2.0.0-s02-real
10
+ * Provides read-only ActiveCodexSnapshot and term count.
11
+ * Uses canonical resolveCodexPath.
12
+ * Full frameworkLogger on all paths.
30
13
  */
31
14
  import { frameworkLogger } from '../core/framework-logger.js';
32
15
  import { resolveCodexPath } from '../core/config-paths.js';
@@ -120,7 +103,7 @@ export class CodexPolicyService {
120
103
  is_fallback: isFallback,
121
104
  note: isFallback
122
105
  ? 'Governance CodexPolicyService — builtin fallback (no external codex.json resolved)'
123
- : 'Returned via Governance CodexPolicyService — V2 Single Source of Truth (S02-REAL)',
106
+ : 'Returned via Governance CodexPolicyService',
124
107
  dynamo_required: true,
125
108
  ...(includeRaw ? { codex: data } : {}),
126
109
  };
@@ -164,4 +147,3 @@ export function getCodexPolicyService() {
164
147
  return codexPolicyServiceInstance;
165
148
  }
166
149
  // Also export the class for direct construction in tests / advanced wiring
167
- export { CodexPolicyService as default };
@@ -1,41 +1,35 @@
1
1
  /**
2
2
  * Pure governance decision logic.
3
- * This module contains the PHI/TAU matrix and merging rules.
3
+ * This module contains the merging rules and metamorphosis scoring.
4
4
  * It has no side effects and does not call any MCPs.
5
5
  *
6
6
  * This is the shared "pure logic" that both the Governance MCP
7
7
  * and any HTTP deployment (Vercel) can use.
8
8
  */
9
9
  import type { GovernanceVote, GovernanceResult } from './governance-types.js';
10
- export interface DecisionMatrixInput {
11
- resonance: number;
12
- isotopicRatio: number;
13
- vortexVolume?: number;
14
- historicalCoherence?: number;
15
- solarActivity?: 'quiet' | 'moderate' | 'active' | 'storm';
16
- moralTension?: 'Aligned' | 'Mild' | 'Significant' | 'Critical';
17
- moralScore?: number;
18
- moralFusion?: number;
19
- }
20
- export interface DecisionMatrixOutput {
21
- recommendation: 'PASS' | 'NEEDS_REVISION' | 'REJECT';
22
- confidence: number;
23
- voteWeight: number;
24
- reasons: string[];
25
- moralOverride?: 'rejected_critical' | 'downgraded_significant' | 'none';
26
- }
27
- export declare const MORAL_OVERRIDE_LEVELS: {
28
- Critical: "rejected_critical";
29
- Significant: "downgraded_significant";
30
- Mild: "none";
31
- Aligned: "none";
32
- };
33
- export type MoralOverrideThreshold = 'Critical' | 'Significant' | 'Mild' | 'Aligned' | 'disabled';
34
10
  /**
35
- * The core PHI/TAU decision matrix.
36
- * Extracted so it can be shared between local MCP and deployed HTTP versions.
11
+ * Calculate metamorphosis resonance score for self-evolution proposals.
12
+ *
13
+ * Evaluates whether a proposal increases the system's capacity to govern
14
+ * complex future states. Uses the existing Dynamo resonance signal plus
15
+ * checks for self-improvement indicators.
16
+ *
17
+ * Scoring rubric (0-1):
18
+ * - Base: governance vote confidence (averageConfidence)
19
+ * - Boost: +0.1 if proposal adds new capacity (type=automate/codify)
20
+ * - Boost: +0.05 if historical coherence is strong (>0.8)
21
+ * - Penalty: -0.15 if proposal removes existing capacity (type=compliance-only)
22
+ * - Floor: 0.0, Ceiling: 1.0
23
+ * - Threshold for approval: ≥ 0.7 (configurable via GovernOptions.metamorphosisThreshold)
24
+ *
25
+ * Only meaningful when proposal.type === 'metamorphosis' or source === 'metamorphosis'.
37
26
  */
38
- export declare function applyDecisionMatrix(input: DecisionMatrixInput): DecisionMatrixOutput;
27
+ export declare function calculateMetamorphosisScore(input: {
28
+ averageConfidence: number;
29
+ proposalType: string;
30
+ historicalCoherence?: number;
31
+ resonanceScore?: number;
32
+ }): number;
39
33
  /**
40
34
  * Simple weighted merge of votes from multiple servers + external.
41
35
  */
@@ -1,117 +1,47 @@
1
1
  /**
2
2
  * Pure governance decision logic.
3
- * This module contains the PHI/TAU matrix and merging rules.
3
+ * This module contains the merging rules and metamorphosis scoring.
4
4
  * It has no side effects and does not call any MCPs.
5
5
  *
6
6
  * This is the shared "pure logic" that both the Governance MCP
7
7
  * and any HTTP deployment (Vercel) can use.
8
8
  */
9
- // Blurrn constants (from chrono-warp-drive)
10
- const PHI = 1.666;
11
- const TAU = 0.865;
12
- export const MORAL_OVERRIDE_LEVELS = {
13
- Critical: 'rejected_critical',
14
- Significant: 'downgraded_significant',
15
- Mild: 'none',
16
- Aligned: 'none',
17
- };
18
9
  /**
19
- * The core PHI/TAU decision matrix.
20
- * Extracted so it can be shared between local MCP and deployed HTTP versions.
10
+ * Calculate metamorphosis resonance score for self-evolution proposals.
11
+ *
12
+ * Evaluates whether a proposal increases the system's capacity to govern
13
+ * complex future states. Uses the existing Dynamo resonance signal plus
14
+ * checks for self-improvement indicators.
15
+ *
16
+ * Scoring rubric (0-1):
17
+ * - Base: governance vote confidence (averageConfidence)
18
+ * - Boost: +0.1 if proposal adds new capacity (type=automate/codify)
19
+ * - Boost: +0.05 if historical coherence is strong (>0.8)
20
+ * - Penalty: -0.15 if proposal removes existing capacity (type=compliance-only)
21
+ * - Floor: 0.0, Ceiling: 1.0
22
+ * - Threshold for approval: ≥ 0.7 (configurable via GovernOptions.metamorphosisThreshold)
23
+ *
24
+ * Only meaningful when proposal.type === 'metamorphosis' or source === 'metamorphosis'.
21
25
  */
22
- export function applyDecisionMatrix(input) {
23
- const { resonance, isotopicRatio, vortexVolume = Number.MAX_VALUE, // large default so the low-mass check only triggers on explicit small values
24
- historicalCoherence = 0.8, solarActivity = 'quiet', moralTension, moralScore, moralFusion, } = input;
25
- const reasons = [];
26
- let recommendation = 'NEEDS_REVISION';
27
- let confidence = 0.75;
28
- let voteWeight = 1.0;
29
- let moralOverride = 'none';
30
- // Log moral fusion if present — weighted signal for transparency
31
- if (moralFusion != null) {
32
- reasons.push(`Moral-numerological fusion: ${(moralFusion * 100).toFixed(0)}%`);
26
+ export function calculateMetamorphosisScore(input) {
27
+ let score = input.averageConfidence;
28
+ // Self-improvement capacity: proposals that add automation or codification boost the score
29
+ if (input.proposalType === 'automate' || input.proposalType === 'codify') {
30
+ score += 0.10;
33
31
  }
34
- // Trinitarium Moral Overlay override
35
- // Critical tension always rejects — proposal violates moral alignment regardless of physics
36
- if (moralTension === 'Critical') {
37
- recommendation = 'REJECT';
38
- confidence = 0.92;
39
- voteWeight = 1.6;
40
- moralOverride = 'rejected_critical';
41
- reasons.push(`Critical moral tension — proposal violates moral alignment (score: ${moralScore != null ? (moralScore * 100).toFixed(0) + '%' : 'unknown'})`);
42
- return {
43
- recommendation,
44
- confidence: Math.min(0.99, Math.max(0.5, confidence)),
45
- voteWeight: Math.max(0.5, Math.min(1.8, voteWeight)),
46
- reasons,
47
- moralOverride,
48
- };
32
+ // Compliance-only proposals (guard type with no new capacity) get a penalty
33
+ if (input.proposalType === 'compliance') {
34
+ score -= 0.15;
49
35
  }
50
- // Significant tension downgrades PASS → NEEDS_REVISION
51
- let moralDowngrade = false;
52
- if (moralTension === 'Significant') {
53
- moralDowngrade = true;
54
- moralOverride = 'downgraded_significant';
55
- voteWeight *= 0.85;
56
- reasons.push(`Significant moral tension — proceed with caution (score: ${moralScore != null ? (moralScore * 100).toFixed(0) + '%' : 'unknown'})`);
36
+ // Strong historical coherence means the system is stable enough for self-evolution
37
+ if (input.historicalCoherence != null && input.historicalCoherence > 0.8) {
38
+ score += 0.05;
57
39
  }
58
- // Aligned tension boosts confidence slightly
59
- if (moralTension === 'Aligned' && moralScore != null) {
60
- confidence += 0.03;
61
- voteWeight *= 1.05;
62
- reasons.push(`Moral alignment confirmed (score: ${(moralScore * 100).toFixed(0)}%)`);
40
+ // High Dynamo resonance (Solar signal) supports self-evolution
41
+ if (input.resonanceScore != null && input.resonanceScore >= 0.82) {
42
+ score += 0.05;
63
43
  }
64
- if (resonance >= 0.92 && isotopicRatio >= 0.95) {
65
- recommendation = 'PASS';
66
- confidence = 0.97;
67
- voteWeight = 1.4;
68
- reasons.push('High symbiotic resonance (PHI-aligned)');
69
- }
70
- else if (resonance >= 0.82 && isotopicRatio >= 0.88) {
71
- recommendation = 'PASS';
72
- confidence = 0.89;
73
- voteWeight = 1.15;
74
- reasons.push('Solid alignment above TAU threshold');
75
- }
76
- else if (resonance < 0.75 || isotopicRatio < 0.80) {
77
- recommendation = 'REJECT';
78
- confidence = 0.84;
79
- reasons.push('Signal below critical threshold (1 - TAU)');
80
- }
81
- else {
82
- reasons.push('Moderate resonance - requires refinement');
83
- }
84
- // Moral downgrade: Significant tension demotes PASS → NEEDS_REVISION
85
- if (moralDowngrade && recommendation === 'PASS') {
86
- recommendation = 'NEEDS_REVISION';
87
- reasons.push('Moral tension downgraded recommendation from PASS to NEEDS_REVISION');
88
- }
89
- if (vortexVolume < 2.5e25) {
90
- reasons.push('Low inertial mass (W x M = V)');
91
- if (recommendation === 'PASS')
92
- recommendation = 'NEEDS_REVISION';
93
- }
94
- if (historicalCoherence < 0.70) {
95
- reasons.push('Weak historical alignment with past decisions');
96
- if (recommendation === 'PASS')
97
- recommendation = 'NEEDS_REVISION';
98
- }
99
- else if (historicalCoherence > 0.90) {
100
- reasons.push('Strong continuity with previous governance');
101
- voteWeight *= 1.1;
102
- }
103
- // Solar adjustment (from chrono-warp-drive)
104
- if (solarActivity === 'active' || solarActivity === 'storm') {
105
- voteWeight *= 0.92;
106
- reasons.push('Elevated solar activity - increased caution applied');
107
- }
108
- return {
109
- recommendation,
110
- confidence: Math.min(0.99, Math.max(0.5, confidence)),
111
- voteWeight: Math.max(0.5, Math.min(1.8, voteWeight)),
112
- reasons,
113
- moralOverride,
114
- };
44
+ return Math.min(1.0, Math.max(0.0, Math.round(score * 100) / 100));
115
45
  }
116
46
  /**
117
47
  * Simple weighted merge of votes from multiple servers + external.
@@ -34,5 +34,6 @@ export declare class GovernanceService {
34
34
  private callExternalDynamo;
35
35
  private callInProcessSkillWithTimeout;
36
36
  private parseVoteFromText;
37
+ private isBuiltInSkill;
37
38
  }
38
39
  export declare function getGovernanceService(): GovernanceService;
@@ -17,8 +17,9 @@
17
17
  */
18
18
  import { mcpClientManager } from '../mcps/mcp-client.js';
19
19
  import { callInProcessSkill } from '../mcps/in-process-skill-registry.js';
20
+ import { pluginRegistry } from '../nucleus/plugin-registry.js';
20
21
  import { getGovernanceIntegration, } from '../integrations/governance/index.js';
21
- import { mergeVotes } from './governance-core.js';
22
+ import { mergeVotes, calculateMetamorphosisScore } from './governance-core.js';
22
23
  import { frameworkLogger } from '../core/framework-logger.js';
23
24
  export class GovernanceService {
24
25
  constructor() {
@@ -59,7 +60,7 @@ export class GovernanceService {
59
60
  }
60
61
  }
61
62
  // Run governance with end-to-end timeout
62
- const result = await this.runGovernanceWithTimeout(proposals, context, requireExternal, timeoutMs);
63
+ const result = await this.runGovernanceWithTimeout(proposals, context, requireExternal, timeoutMs, options?.metamorphosisThreshold);
63
64
  // Check abstention threshold
64
65
  if (result.results.length > 0 && maxAbstentionThreshold < 1.0) {
65
66
  const totalVotes = result.results.reduce((sum, r) => sum + r.votes.length, 0);
@@ -91,7 +92,7 @@ export class GovernanceService {
91
92
  },
92
93
  };
93
94
  }
94
- async runGovernanceWithTimeout(proposals, context, requireExternal, timeoutMs) {
95
+ async runGovernanceWithTimeout(proposals, context, requireExternal, timeoutMs, metamorphosisThreshold) {
95
96
  const controller = new AbortController();
96
97
  const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
97
98
  try {
@@ -112,13 +113,33 @@ export class GovernanceService {
112
113
  ...(externalVotes[index] || []),
113
114
  ];
114
115
  const merged = mergeVotes(votes);
115
- return {
116
+ const isMetamorphosis = proposal.type === 'metamorphosis' || proposal.source === 'metamorphosis';
117
+ const result = {
116
118
  proposalId: proposal.id,
117
119
  finalDecision: merged.finalDecision,
118
120
  averageConfidence: merged.averageConfidence,
119
121
  votes,
120
122
  reasoningSummary: merged.reasoningSummary,
121
123
  };
124
+ // Metamorphosis resonance scoring: only for self-evolution proposals
125
+ if (isMetamorphosis) {
126
+ const threshold = metamorphosisThreshold ?? 0.7;
127
+ const metaInput = {
128
+ averageConfidence: merged.averageConfidence,
129
+ proposalType: proposal.type,
130
+ };
131
+ const externalConfidence = externalVotes[index]?.[0]?.confidence;
132
+ if (externalConfidence !== undefined) {
133
+ metaInput.historicalCoherence = externalConfidence;
134
+ }
135
+ result.metamorphosisScore = calculateMetamorphosisScore(metaInput);
136
+ // Reject metamorphosis proposals that don't meet the threshold
137
+ if (result.metamorphosisScore < threshold && result.finalDecision === 'approve') {
138
+ result.finalDecision = 'needs_revision';
139
+ result.reasoningSummary += ` | Metamorphosis score ${result.metamorphosisScore} below threshold ${threshold}`;
140
+ }
141
+ }
142
+ return result;
122
143
  });
123
144
  return { results };
124
145
  }
@@ -129,6 +150,45 @@ export class GovernanceService {
129
150
  async callSkillServer(serverName, proposals, context) {
130
151
  const votes = [];
131
152
  const useInProcess = process.env.VERCEL === '1';
153
+ // v3: Try pluginRegistry first for dynamically registered skills.
154
+ // Built-in skills (code-review, security-audit, researcher) fall through
155
+ // to MCP or in-process paths. Custom plugins registered via
156
+ // pluginRegistry.register() are resolved here.
157
+ if (pluginRegistry.has(serverName) && !this.isBuiltInSkill(serverName)) {
158
+ frameworkLogger.log('governance-service', 'plugin-skill-resolved', 'info', {
159
+ server: serverName,
160
+ mode: 'plugin-registry',
161
+ });
162
+ for (const proposal of proposals) {
163
+ try {
164
+ const result = await pluginRegistry.callSkill(serverName, {
165
+ proposalTitle: proposal.title,
166
+ proposalDescription: proposal.description,
167
+ evidence: proposal.evidence || [],
168
+ proposalType: proposal.type,
169
+ });
170
+ const text = result?.content?.[0]?.text || '';
171
+ const vote = this.parseVoteFromText(serverName, text);
172
+ votes.push(vote);
173
+ }
174
+ catch (error) {
175
+ frameworkLogger.log('governance-service', 'plugin-skill-error', 'error', {
176
+ server: serverName,
177
+ proposal: proposal.title,
178
+ error: error instanceof Error ? error.message : String(error),
179
+ mode: 'plugin-registry',
180
+ });
181
+ votes.push({
182
+ server: serverName,
183
+ decision: 'abstain',
184
+ confidence: 0.3,
185
+ reasoning: `Plugin skill ${serverName} failed: ${error instanceof Error ? error.message : 'Unknown error'}`,
186
+ });
187
+ }
188
+ }
189
+ return votes;
190
+ }
191
+ // Built-in skills: use MCP (standard surface) or in-process (Vercel)
132
192
  for (const proposal of proposals) {
133
193
  try {
134
194
  let text = '';
@@ -263,6 +323,9 @@ export class GovernanceService {
263
323
  reasoning: reasoningMatch?.[1]?.trim() || 'No reasoning provided',
264
324
  };
265
325
  }
326
+ isBuiltInSkill(name) {
327
+ return name === 'code-review' || name === 'security-audit' || name === 'researcher';
328
+ }
266
329
  }
267
330
  // Singleton for convenience
268
331
  let governanceServiceInstance = null;