monomind 1.11.11 → 1.11.13

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 (227) hide show
  1. package/.claude/commands/mastermind/idea.md +1 -1
  2. package/.claude/commands/mastermind/master.md +1 -1
  3. package/.claude/skills/mastermind/_protocol.md +4 -4
  4. package/.claude/skills/mastermind/architect.md +7 -4
  5. package/.claude/skills/mastermind/autodev.md +4 -2
  6. package/.claude/skills/mastermind/build.md +3 -3
  7. package/.claude/skills/mastermind/content.md +3 -3
  8. package/.claude/skills/mastermind/createorg.md +2 -2
  9. package/.claude/skills/mastermind/finance.md +3 -3
  10. package/.claude/skills/mastermind/idea.md +8 -0
  11. package/.claude/skills/mastermind/marketing.md +3 -3
  12. package/.claude/skills/mastermind/ops.md +3 -3
  13. package/.claude/skills/mastermind/release.md +3 -3
  14. package/.claude/skills/mastermind/research.md +3 -3
  15. package/.claude/skills/mastermind/review.md +3 -3
  16. package/.claude/skills/mastermind/sales.md +3 -3
  17. package/package.json +1 -1
  18. package/packages/@monomind/cli/dist/src/index.js +19 -14
  19. package/packages/@monomind/cli/dist/src/init/statusline-generator.js +3 -3
  20. package/packages/@monomind/cli/dist/src/observability/replay-reader.d.ts +1 -1
  21. package/packages/@monomind/cli/dist/src/update/checker.js +24 -7
  22. package/packages/@monomind/cli/dist/src/update/index.d.ts +10 -0
  23. package/packages/@monomind/cli/dist/src/update/index.js +29 -2
  24. package/packages/@monomind/cli/package.json +1 -1
  25. package/packages/@monomind/cli/dist/src/agents/halt-signal.d.ts +0 -25
  26. package/packages/@monomind/cli/dist/src/agents/halt-signal.js +0 -76
  27. package/packages/@monomind/cli/dist/src/agents/index.d.ts +0 -18
  28. package/packages/@monomind/cli/dist/src/agents/index.js +0 -13
  29. package/packages/@monomind/cli/dist/src/agents/managed-agent.d.ts +0 -41
  30. package/packages/@monomind/cli/dist/src/agents/managed-agent.js +0 -69
  31. package/packages/@monomind/cli/dist/src/agents/prompt-experiment.d.ts +0 -23
  32. package/packages/@monomind/cli/dist/src/agents/prompt-experiment.js +0 -49
  33. package/packages/@monomind/cli/dist/src/agents/prompt-version-manager.d.ts +0 -22
  34. package/packages/@monomind/cli/dist/src/agents/prompt-version-manager.js +0 -80
  35. package/packages/@monomind/cli/dist/src/agents/registry-query.d.ts +0 -71
  36. package/packages/@monomind/cli/dist/src/agents/registry-query.js +0 -125
  37. package/packages/@monomind/cli/dist/src/agents/score-decay.d.ts +0 -19
  38. package/packages/@monomind/cli/dist/src/agents/score-decay.js +0 -22
  39. package/packages/@monomind/cli/dist/src/agents/shared-instructions-loader.d.ts +0 -13
  40. package/packages/@monomind/cli/dist/src/agents/shared-instructions-loader.js +0 -40
  41. package/packages/@monomind/cli/dist/src/agents/specialization-scorer.d.ts +0 -54
  42. package/packages/@monomind/cli/dist/src/agents/specialization-scorer.js +0 -212
  43. package/packages/@monomind/cli/dist/src/agents/termination-watcher.d.ts +0 -30
  44. package/packages/@monomind/cli/dist/src/agents/termination-watcher.js +0 -84
  45. package/packages/@monomind/cli/dist/src/agents/trigger-index.d.ts +0 -20
  46. package/packages/@monomind/cli/dist/src/agents/trigger-index.js +0 -38
  47. package/packages/@monomind/cli/dist/src/agents/trigger-scanner.d.ts +0 -64
  48. package/packages/@monomind/cli/dist/src/agents/trigger-scanner.js +0 -308
  49. package/packages/@monomind/cli/dist/src/agents/version-diff.d.ts +0 -18
  50. package/packages/@monomind/cli/dist/src/agents/version-diff.js +0 -64
  51. package/packages/@monomind/cli/dist/src/agents/version-store.d.ts +0 -60
  52. package/packages/@monomind/cli/dist/src/agents/version-store.js +0 -235
  53. package/packages/@monomind/cli/dist/src/benchmarks/pretrain/index.d.ts +0 -45
  54. package/packages/@monomind/cli/dist/src/benchmarks/pretrain/index.js +0 -404
  55. package/packages/@monomind/cli/dist/src/commands/agent-wasm.d.ts +0 -14
  56. package/packages/@monomind/cli/dist/src/commands/agent-wasm.js +0 -333
  57. package/packages/@monomind/cli/dist/src/commands/ui.js +0 -68
  58. package/packages/@monomind/cli/dist/src/consensus/index.d.ts +0 -7
  59. package/packages/@monomind/cli/dist/src/consensus/index.js +0 -6
  60. package/packages/@monomind/cli/dist/src/context/context-provider.d.ts +0 -44
  61. package/packages/@monomind/cli/dist/src/context/context-provider.js +0 -25
  62. package/packages/@monomind/cli/dist/src/context/git-state-provider.d.ts +0 -12
  63. package/packages/@monomind/cli/dist/src/context/git-state-provider.js +0 -34
  64. package/packages/@monomind/cli/dist/src/context/index.d.ts +0 -12
  65. package/packages/@monomind/cli/dist/src/context/index.js +0 -12
  66. package/packages/@monomind/cli/dist/src/context/project-conventions-provider.d.ts +0 -15
  67. package/packages/@monomind/cli/dist/src/context/project-conventions-provider.js +0 -19
  68. package/packages/@monomind/cli/dist/src/context/prompt-assembler.d.ts +0 -26
  69. package/packages/@monomind/cli/dist/src/context/prompt-assembler.js +0 -93
  70. package/packages/@monomind/cli/dist/src/context/task-history-provider.d.ts +0 -24
  71. package/packages/@monomind/cli/dist/src/context/task-history-provider.js +0 -32
  72. package/packages/@monomind/cli/dist/src/context/user-preferences-provider.d.ts +0 -14
  73. package/packages/@monomind/cli/dist/src/context/user-preferences-provider.js +0 -27
  74. package/packages/@monomind/cli/dist/src/dlq/dlq-reader.d.ts +0 -31
  75. package/packages/@monomind/cli/dist/src/dlq/dlq-reader.js +0 -81
  76. package/packages/@monomind/cli/dist/src/dlq/dlq-writer.d.ts +0 -24
  77. package/packages/@monomind/cli/dist/src/dlq/dlq-writer.js +0 -65
  78. package/packages/@monomind/cli/dist/src/dlq/index.d.ts +0 -10
  79. package/packages/@monomind/cli/dist/src/dlq/index.js +0 -7
  80. package/packages/@monomind/cli/dist/src/eval/dataset-manager.d.ts +0 -33
  81. package/packages/@monomind/cli/dist/src/eval/dataset-manager.js +0 -107
  82. package/packages/@monomind/cli/dist/src/eval/dataset-runner.d.ts +0 -23
  83. package/packages/@monomind/cli/dist/src/eval/dataset-runner.js +0 -59
  84. package/packages/@monomind/cli/dist/src/eval/index.d.ts +0 -10
  85. package/packages/@monomind/cli/dist/src/eval/index.js +0 -7
  86. package/packages/@monomind/cli/dist/src/eval/trace-collector.d.ts +0 -40
  87. package/packages/@monomind/cli/dist/src/eval/trace-collector.js +0 -102
  88. package/packages/@monomind/cli/dist/src/infrastructure/in-memory-repositories.d.ts +0 -68
  89. package/packages/@monomind/cli/dist/src/infrastructure/in-memory-repositories.js +0 -264
  90. package/packages/@monomind/cli/dist/src/interactive/interrupt.d.ts +0 -22
  91. package/packages/@monomind/cli/dist/src/interactive/interrupt.js +0 -71
  92. package/packages/@monomind/cli/dist/src/mcp/deprecation-injector.d.ts +0 -25
  93. package/packages/@monomind/cli/dist/src/mcp/deprecation-injector.js +0 -48
  94. package/packages/@monomind/cli/dist/src/mcp/tool-registry.d.ts +0 -61
  95. package/packages/@monomind/cli/dist/src/mcp/tool-registry.js +0 -246
  96. package/packages/@monomind/cli/dist/src/mcp-tools/wasm-agent-tools.d.ts +0 -9
  97. package/packages/@monomind/cli/dist/src/mcp-tools/wasm-agent-tools.js +0 -230
  98. package/packages/@monomind/cli/dist/src/model/complexity-scorer.d.ts +0 -21
  99. package/packages/@monomind/cli/dist/src/model/complexity-scorer.js +0 -106
  100. package/packages/@monomind/cli/dist/src/model/index.d.ts +0 -4
  101. package/packages/@monomind/cli/dist/src/model/index.js +0 -4
  102. package/packages/@monomind/cli/dist/src/model/model-settings.d.ts +0 -22
  103. package/packages/@monomind/cli/dist/src/model/model-settings.js +0 -33
  104. package/packages/@monomind/cli/dist/src/model/model-tier-resolver.d.ts +0 -24
  105. package/packages/@monomind/cli/dist/src/model/model-tier-resolver.js +0 -65
  106. package/packages/@monomind/cli/dist/src/monovector/capabilities.d.ts +0 -34
  107. package/packages/@monomind/cli/dist/src/monovector/capabilities.js +0 -37
  108. package/packages/@monomind/cli/dist/src/orchestration/index.d.ts +0 -7
  109. package/packages/@monomind/cli/dist/src/orchestration/index.js +0 -6
  110. package/packages/@monomind/cli/dist/src/orchestration/mode-dispatcher.d.ts +0 -11
  111. package/packages/@monomind/cli/dist/src/orchestration/mode-dispatcher.js +0 -31
  112. package/packages/@monomind/cli/dist/src/orchestration/routing-modes.d.ts +0 -68
  113. package/packages/@monomind/cli/dist/src/orchestration/routing-modes.js +0 -180
  114. package/packages/@monomind/cli/dist/src/plugins/tests/demo-plugin-store.d.ts +0 -7
  115. package/packages/@monomind/cli/dist/src/plugins/tests/demo-plugin-store.js +0 -126
  116. package/packages/@monomind/cli/dist/src/plugins/tests/standalone-test.d.ts +0 -12
  117. package/packages/@monomind/cli/dist/src/plugins/tests/standalone-test.js +0 -188
  118. package/packages/@monomind/cli/dist/src/plugins/tests/test-plugin-store.d.ts +0 -7
  119. package/packages/@monomind/cli/dist/src/plugins/tests/test-plugin-store.js +0 -206
  120. package/packages/@monomind/cli/dist/src/runtime/headless.d.ts +0 -60
  121. package/packages/@monomind/cli/dist/src/runtime/headless.js +0 -284
  122. package/packages/@monomind/cli/dist/src/services/agentic-flow-bridge.d.ts +0 -50
  123. package/packages/@monomind/cli/dist/src/services/agentic-flow-bridge.js +0 -95
  124. package/packages/@monomind/cli/dist/src/services/container-worker-pool.d.ts +0 -197
  125. package/packages/@monomind/cli/dist/src/services/container-worker-pool.js +0 -623
  126. package/packages/@monomind/cli/dist/src/services/index.d.ts +0 -13
  127. package/packages/@monomind/cli/dist/src/services/index.js +0 -11
  128. package/packages/@monomind/cli/dist/src/services/worker-queue.d.ts +0 -201
  129. package/packages/@monomind/cli/dist/src/services/worker-queue.js +0 -594
  130. package/packages/@monomind/cli/dist/src/swarm/communication-graph.d.ts +0 -25
  131. package/packages/@monomind/cli/dist/src/swarm/communication-graph.js +0 -77
  132. package/packages/@monomind/cli/dist/src/swarm/flow-enforcer.d.ts +0 -31
  133. package/packages/@monomind/cli/dist/src/swarm/flow-enforcer.js +0 -61
  134. package/packages/@monomind/cli/dist/src/swarm/flow-visualizer.d.ts +0 -19
  135. package/packages/@monomind/cli/dist/src/swarm/flow-visualizer.js +0 -68
  136. package/packages/@monomind/cli/dist/src/transfer/deploy-seraphine.d.ts +0 -13
  137. package/packages/@monomind/cli/dist/src/transfer/deploy-seraphine.js +0 -205
  138. package/packages/@monomind/cli/dist/src/transfer/store/tests/standalone-test.d.ts +0 -12
  139. package/packages/@monomind/cli/dist/src/transfer/store/tests/standalone-test.js +0 -190
  140. package/packages/@monomind/cli/dist/src/transfer/test-seraphine.d.ts +0 -6
  141. package/packages/@monomind/cli/dist/src/transfer/test-seraphine.js +0 -105
  142. package/packages/@monomind/cli/dist/src/transfer/tests/test-store.d.ts +0 -7
  143. package/packages/@monomind/cli/dist/src/transfer/tests/test-store.js +0 -214
  144. package/packages/@monomind/cli/dist/src/workflow/condition-evaluator.d.ts +0 -10
  145. package/packages/@monomind/cli/dist/src/workflow/condition-evaluator.js +0 -82
  146. package/packages/@monomind/cli/dist/src/workflow/context-resolver.d.ts +0 -12
  147. package/packages/@monomind/cli/dist/src/workflow/context-resolver.js +0 -23
  148. package/packages/@monomind/cli/dist/src/workflow/dag-builder.d.ts +0 -17
  149. package/packages/@monomind/cli/dist/src/workflow/dag-builder.js +0 -129
  150. package/packages/@monomind/cli/dist/src/workflow/dag-executor.d.ts +0 -9
  151. package/packages/@monomind/cli/dist/src/workflow/dag-executor.js +0 -116
  152. package/packages/@monomind/cli/dist/src/workflow/dag-types.d.ts +0 -41
  153. package/packages/@monomind/cli/dist/src/workflow/dag-types.js +0 -8
  154. package/packages/@monomind/cli/dist/src/workflow/dsl-parser.d.ts +0 -12
  155. package/packages/@monomind/cli/dist/src/workflow/dsl-parser.js +0 -20
  156. package/packages/@monomind/cli/dist/src/workflow/dsl-schema.d.ts +0 -165
  157. package/packages/@monomind/cli/dist/src/workflow/dsl-schema.js +0 -82
  158. package/packages/@monomind/cli/dist/src/workflow/index.d.ts +0 -13
  159. package/packages/@monomind/cli/dist/src/workflow/index.js +0 -11
  160. package/packages/@monomind/cli/dist/src/workflow/template-engine.d.ts +0 -11
  161. package/packages/@monomind/cli/dist/src/workflow/template-engine.js +0 -40
  162. package/packages/@monomind/cli/dist/src/workflow/workflow-executor.d.ts +0 -29
  163. package/packages/@monomind/cli/dist/src/workflow/workflow-executor.js +0 -227
  164. package/packages/@monomind/guidance/dist/adversarial.d.ts +0 -284
  165. package/packages/@monomind/guidance/dist/adversarial.js +0 -572
  166. package/packages/@monomind/guidance/dist/analyzer.d.ts +0 -530
  167. package/packages/@monomind/guidance/dist/analyzer.js +0 -2518
  168. package/packages/@monomind/guidance/dist/artifacts.d.ts +0 -283
  169. package/packages/@monomind/guidance/dist/artifacts.js +0 -356
  170. package/packages/@monomind/guidance/dist/authority.d.ts +0 -290
  171. package/packages/@monomind/guidance/dist/authority.js +0 -558
  172. package/packages/@monomind/guidance/dist/capabilities.d.ts +0 -209
  173. package/packages/@monomind/guidance/dist/capabilities.js +0 -485
  174. package/packages/@monomind/guidance/dist/coherence.d.ts +0 -233
  175. package/packages/@monomind/guidance/dist/coherence.js +0 -372
  176. package/packages/@monomind/guidance/dist/compiler.d.ts +0 -87
  177. package/packages/@monomind/guidance/dist/compiler.js +0 -419
  178. package/packages/@monomind/guidance/dist/conformance-kit.d.ts +0 -225
  179. package/packages/@monomind/guidance/dist/conformance-kit.js +0 -629
  180. package/packages/@monomind/guidance/dist/continue-gate.d.ts +0 -214
  181. package/packages/@monomind/guidance/dist/continue-gate.js +0 -353
  182. package/packages/@monomind/guidance/dist/crypto-utils.d.ts +0 -17
  183. package/packages/@monomind/guidance/dist/crypto-utils.js +0 -24
  184. package/packages/@monomind/guidance/dist/evolution.d.ts +0 -282
  185. package/packages/@monomind/guidance/dist/evolution.js +0 -500
  186. package/packages/@monomind/guidance/dist/gates.d.ts +0 -79
  187. package/packages/@monomind/guidance/dist/gates.js +0 -302
  188. package/packages/@monomind/guidance/dist/gateway.d.ts +0 -206
  189. package/packages/@monomind/guidance/dist/gateway.js +0 -452
  190. package/packages/@monomind/guidance/dist/generators.d.ts +0 -153
  191. package/packages/@monomind/guidance/dist/generators.js +0 -682
  192. package/packages/@monomind/guidance/dist/headless.d.ts +0 -177
  193. package/packages/@monomind/guidance/dist/headless.js +0 -342
  194. package/packages/@monomind/guidance/dist/hooks.d.ts +0 -109
  195. package/packages/@monomind/guidance/dist/hooks.js +0 -347
  196. package/packages/@monomind/guidance/dist/index.d.ts +0 -205
  197. package/packages/@monomind/guidance/dist/index.js +0 -321
  198. package/packages/@monomind/guidance/dist/ledger.d.ts +0 -162
  199. package/packages/@monomind/guidance/dist/ledger.js +0 -375
  200. package/packages/@monomind/guidance/dist/manifest-validator.d.ts +0 -289
  201. package/packages/@monomind/guidance/dist/manifest-validator.js +0 -838
  202. package/packages/@monomind/guidance/dist/memory-gate.d.ts +0 -222
  203. package/packages/@monomind/guidance/dist/memory-gate.js +0 -382
  204. package/packages/@monomind/guidance/dist/meta-governance.d.ts +0 -265
  205. package/packages/@monomind/guidance/dist/meta-governance.js +0 -348
  206. package/packages/@monomind/guidance/dist/optimizer.d.ts +0 -104
  207. package/packages/@monomind/guidance/dist/optimizer.js +0 -329
  208. package/packages/@monomind/guidance/dist/persistence.d.ts +0 -189
  209. package/packages/@monomind/guidance/dist/persistence.js +0 -464
  210. package/packages/@monomind/guidance/dist/proof.d.ts +0 -185
  211. package/packages/@monomind/guidance/dist/proof.js +0 -238
  212. package/packages/@monomind/guidance/dist/retriever.d.ts +0 -116
  213. package/packages/@monomind/guidance/dist/retriever.js +0 -394
  214. package/packages/@monomind/guidance/dist/ruvbot-integration.d.ts +0 -370
  215. package/packages/@monomind/guidance/dist/ruvbot-integration.js +0 -738
  216. package/packages/@monomind/guidance/dist/temporal.d.ts +0 -426
  217. package/packages/@monomind/guidance/dist/temporal.js +0 -658
  218. package/packages/@monomind/guidance/dist/trust.d.ts +0 -283
  219. package/packages/@monomind/guidance/dist/trust.js +0 -473
  220. package/packages/@monomind/guidance/dist/truth-anchors.d.ts +0 -276
  221. package/packages/@monomind/guidance/dist/truth-anchors.js +0 -488
  222. package/packages/@monomind/guidance/dist/types.d.ts +0 -378
  223. package/packages/@monomind/guidance/dist/types.js +0 -10
  224. package/packages/@monomind/guidance/dist/uncertainty.d.ts +0 -372
  225. package/packages/@monomind/guidance/dist/uncertainty.js +0 -619
  226. package/packages/@monomind/guidance/dist/wasm-kernel.d.ts +0 -48
  227. package/packages/@monomind/guidance/dist/wasm-kernel.js +0 -158
@@ -1,104 +0,0 @@
1
- /**
2
- * Optimizer Loop
3
- *
4
- * Weekly loop that edits guidance like code:
5
- * 1. Rank top violations by frequency and cost
6
- * 2. For the top 3, propose one rule change each
7
- * 3. Run the fixed task suite with and without the change
8
- * 4. Promote only if risk does not increase and rework decreases
9
- * 5. Record the decision in an ADR note
10
- *
11
- * Promotion rule: Local rules that win twice become root rules.
12
- *
13
- * @module @monomind/guidance/optimizer
14
- */
15
- import type { PolicyBundle, ViolationRanking, RuleChange, ABTestResult, OptimizationMetrics, RuleADR } from './types.js';
16
- import type { RunLedger } from './ledger.js';
17
- export interface OptimizerConfig {
18
- /** Number of top violations to address per cycle */
19
- topViolationsPerCycle: number;
20
- /** Minimum events required before optimization */
21
- minEventsForOptimization: number;
22
- /** Required improvement threshold for promotion (0-1) */
23
- improvementThreshold: number;
24
- /** Maximum risk increase tolerance (0-1) */
25
- maxRiskIncrease: number;
26
- /** Number of consecutive wins needed for promotion to root */
27
- promotionWins: number;
28
- /** ADR storage path */
29
- adrPath: string;
30
- }
31
- export declare class OptimizerLoop {
32
- private config;
33
- private proposedChanges;
34
- private testResults;
35
- private adrs;
36
- private promotionTracker;
37
- private lastOptimizationRun;
38
- constructor(config?: Partial<OptimizerConfig>);
39
- /**
40
- * Run a full optimization cycle
41
- *
42
- * Steps:
43
- * 1. Rank violations
44
- * 2. Propose changes for top N
45
- * 3. Evaluate changes against baseline
46
- * 4. Promote winners, record ADRs
47
- */
48
- runCycle(ledger: RunLedger, currentBundle: PolicyBundle): Promise<{
49
- rankings: ViolationRanking[];
50
- changes: RuleChange[];
51
- results: ABTestResult[];
52
- adrs: RuleADR[];
53
- promoted: string[];
54
- demoted: string[];
55
- }>;
56
- /**
57
- * Propose rule changes for top violations
58
- */
59
- proposeChanges(violations: ViolationRanking[], bundle: PolicyBundle): RuleChange[];
60
- /**
61
- * Propose modification to an existing rule
62
- */
63
- private proposeRuleModification;
64
- /**
65
- * Propose a new rule for unhandled violations
66
- */
67
- private proposeNewRule;
68
- /**
69
- * Evaluate a proposed change against baseline metrics
70
- */
71
- evaluateChange(change: RuleChange, baseline: OptimizationMetrics, ledger: RunLedger): ABTestResult;
72
- /**
73
- * Heuristic estimation of how a rule change would affect metrics.
74
- *
75
- * This does NOT run a real A/B test against live traffic — it applies
76
- * fixed multipliers per change-type to the baseline numbers. The
77
- * percentages (e.g. 40% for modify, 60% for add) are conservative
78
- * estimates, not measured values. Results should be treated as
79
- * directional guidance, not ground truth.
80
- */
81
- private simulateChangeEffect;
82
- /**
83
- * Record an ADR for a rule change decision
84
- */
85
- private recordADR;
86
- /**
87
- * Find a rule in the policy bundle
88
- */
89
- private findRule;
90
- /**
91
- * Apply promoted changes to a policy bundle
92
- */
93
- applyPromotions(bundle: PolicyBundle, promoted: string[], changes: RuleChange[]): PolicyBundle;
94
- get lastRun(): number | null;
95
- getADRs(): RuleADR[];
96
- getProposedChanges(): RuleChange[];
97
- getTestResults(): ABTestResult[];
98
- getPromotionTracker(): Map<string, number>;
99
- }
100
- /**
101
- * Create an optimizer instance
102
- */
103
- export declare function createOptimizer(config?: Partial<OptimizerConfig>): OptimizerLoop;
104
- //# sourceMappingURL=optimizer.d.ts.map
@@ -1,329 +0,0 @@
1
- /**
2
- * Optimizer Loop
3
- *
4
- * Weekly loop that edits guidance like code:
5
- * 1. Rank top violations by frequency and cost
6
- * 2. For the top 3, propose one rule change each
7
- * 3. Run the fixed task suite with and without the change
8
- * 4. Promote only if risk does not increase and rework decreases
9
- * 5. Record the decision in an ADR note
10
- *
11
- * Promotion rule: Local rules that win twice become root rules.
12
- *
13
- * @module @monomind/guidance/optimizer
14
- */
15
- import { randomUUID } from 'node:crypto';
16
- const DEFAULT_CONFIG = {
17
- topViolationsPerCycle: 3,
18
- minEventsForOptimization: 10,
19
- improvementThreshold: 0.1,
20
- maxRiskIncrease: 0.05,
21
- promotionWins: 2,
22
- adrPath: './docs/adrs',
23
- };
24
- // ============================================================================
25
- // Optimizer Loop
26
- // ============================================================================
27
- export class OptimizerLoop {
28
- config;
29
- proposedChanges = [];
30
- testResults = [];
31
- adrs = [];
32
- promotionTracker = new Map(); // ruleId -> win count
33
- lastOptimizationRun = null;
34
- constructor(config = {}) {
35
- this.config = { ...DEFAULT_CONFIG, ...config };
36
- }
37
- /**
38
- * Run a full optimization cycle
39
- *
40
- * Steps:
41
- * 1. Rank violations
42
- * 2. Propose changes for top N
43
- * 3. Evaluate changes against baseline
44
- * 4. Promote winners, record ADRs
45
- */
46
- async runCycle(ledger, currentBundle) {
47
- this.lastOptimizationRun = Date.now();
48
- // Step 1: Rank violations
49
- const rankings = ledger.rankViolations();
50
- if (rankings.length === 0) {
51
- return { rankings: [], changes: [], results: [], adrs: [], promoted: [], demoted: [] };
52
- }
53
- // Step 2: Propose changes for top violations
54
- const topViolations = rankings.slice(0, this.config.topViolationsPerCycle);
55
- const changes = this.proposeChanges(topViolations, currentBundle);
56
- this.proposedChanges.push(...changes);
57
- // Step 3: Evaluate each change
58
- const baselineMetrics = ledger.computeMetrics();
59
- const results = [];
60
- for (const change of changes) {
61
- const result = this.evaluateChange(change, baselineMetrics, ledger);
62
- results.push(result);
63
- this.testResults.push(result);
64
- }
65
- // Step 4: Promote winners, record ADRs
66
- const promoted = [];
67
- const demoted = [];
68
- const newAdrs = [];
69
- for (const result of results) {
70
- const adr = this.recordADR(result);
71
- newAdrs.push(adr);
72
- this.adrs.push(adr);
73
- if (result.shouldPromote) {
74
- // Track wins for promotion from local to root
75
- const ruleId = result.change.targetRuleId;
76
- const wins = (this.promotionTracker.get(ruleId) ?? 0) + 1;
77
- this.promotionTracker.set(ruleId, wins);
78
- if (wins >= this.config.promotionWins) {
79
- promoted.push(ruleId);
80
- }
81
- }
82
- else {
83
- // Demote if change failed
84
- const ruleId = result.change.targetRuleId;
85
- this.promotionTracker.set(ruleId, 0);
86
- if (result.change.changeType === 'promote') {
87
- demoted.push(ruleId);
88
- }
89
- }
90
- }
91
- return {
92
- rankings,
93
- changes,
94
- results,
95
- adrs: newAdrs,
96
- promoted,
97
- demoted,
98
- };
99
- }
100
- /**
101
- * Propose rule changes for top violations
102
- */
103
- proposeChanges(violations, bundle) {
104
- const changes = [];
105
- for (const violation of violations) {
106
- // Find the rule
107
- const rule = this.findRule(violation.ruleId, bundle);
108
- if (rule) {
109
- // Existing rule that's being violated too often
110
- changes.push(this.proposeRuleModification(rule, violation));
111
- }
112
- else {
113
- // No rule exists for this violation type - propose new rule
114
- changes.push(this.proposeNewRule(violation));
115
- }
116
- }
117
- return changes;
118
- }
119
- /**
120
- * Propose modification to an existing rule
121
- */
122
- proposeRuleModification(rule, violation) {
123
- // Analyze violation pattern to suggest improvement
124
- let proposedText = rule.text;
125
- let changeType = 'modify';
126
- if (violation.frequency > 5) {
127
- // Rule is violated frequently - make it more specific or add enforcement
128
- proposedText = `${rule.text}. This rule requires automated enforcement via gates.`;
129
- }
130
- else if (violation.cost > 50) {
131
- // Violations are expensive - elevate priority
132
- proposedText = `[HIGH PRIORITY] ${rule.text}. Violations of this rule are costly (avg ${violation.cost.toFixed(0)} rework lines).`;
133
- }
134
- // If rule is local and performing well, propose promotion
135
- if (rule.source === 'local') {
136
- const wins = this.promotionTracker.get(rule.id) ?? 0;
137
- if (wins >= this.config.promotionWins - 1) {
138
- changeType = 'promote';
139
- }
140
- }
141
- return {
142
- changeId: randomUUID(),
143
- targetRuleId: rule.id,
144
- changeType,
145
- originalText: rule.text,
146
- proposedText,
147
- rationale: `Violated ${violation.frequency} times with avg cost of ${violation.cost.toFixed(0)} rework lines (score: ${violation.score.toFixed(1)})`,
148
- triggeringViolation: violation,
149
- };
150
- }
151
- /**
152
- * Propose a new rule for unhandled violations
153
- */
154
- proposeNewRule(violation) {
155
- return {
156
- changeId: randomUUID(),
157
- targetRuleId: violation.ruleId,
158
- changeType: 'add',
159
- proposedText: `[${violation.ruleId}] Enforce compliance for pattern "${violation.ruleId}". Auto-generated from ${violation.frequency} violations with avg cost ${violation.cost.toFixed(0)} lines.`,
160
- rationale: `No existing rule covers violations classified as "${violation.ruleId}". ${violation.frequency} occurrences detected.`,
161
- triggeringViolation: violation,
162
- };
163
- }
164
- /**
165
- * Evaluate a proposed change against baseline metrics
166
- */
167
- evaluateChange(change, baseline, ledger) {
168
- // Get events that would be affected by this rule
169
- const events = ledger.getEvents();
170
- const affectedEvents = events.filter(e => e.violations.some(v => v.ruleId === change.targetRuleId) ||
171
- e.retrievedRuleIds.includes(change.targetRuleId));
172
- // Compute "candidate" metrics: simulate the effect of the change
173
- // For now, estimate based on the violation pattern
174
- const candidateMetrics = this.simulateChangeEffect(change, baseline, affectedEvents.length);
175
- // Decision logic:
176
- // 1. Risk must not increase (violation rate stays same or drops)
177
- // 2. Rework must decrease
178
- const riskIncrease = candidateMetrics.violationRate - baseline.violationRate;
179
- const reworkDecrease = baseline.reworkLines - candidateMetrics.reworkLines;
180
- const shouldPromote = riskIncrease <= this.config.maxRiskIncrease &&
181
- reworkDecrease > 0 &&
182
- (reworkDecrease / Math.max(baseline.reworkLines, 1)) >= this.config.improvementThreshold;
183
- const reason = shouldPromote
184
- ? `Rework decreased by ${reworkDecrease.toFixed(1)} lines (${((reworkDecrease / Math.max(baseline.reworkLines, 1)) * 100).toFixed(1)}%) without increasing risk`
185
- : riskIncrease > this.config.maxRiskIncrease
186
- ? `Risk increased by ${riskIncrease.toFixed(2)} (exceeds threshold ${this.config.maxRiskIncrease})`
187
- : `Insufficient rework improvement (${((reworkDecrease / Math.max(baseline.reworkLines, 1)) * 100).toFixed(1)}% < ${(this.config.improvementThreshold * 100).toFixed(0)}% required)`;
188
- return {
189
- change,
190
- baseline,
191
- candidate: candidateMetrics,
192
- shouldPromote,
193
- reason,
194
- };
195
- }
196
- /**
197
- * Heuristic estimation of how a rule change would affect metrics.
198
- *
199
- * This does NOT run a real A/B test against live traffic — it applies
200
- * fixed multipliers per change-type to the baseline numbers. The
201
- * percentages (e.g. 40% for modify, 60% for add) are conservative
202
- * estimates, not measured values. Results should be treated as
203
- * directional guidance, not ground truth.
204
- */
205
- simulateChangeEffect(change, baseline, affectedEventCount) {
206
- const affectedRatio = baseline.taskCount > 0
207
- ? affectedEventCount / baseline.taskCount
208
- : 0;
209
- // Conservative estimates based on change type
210
- let violationReduction = 0;
211
- let reworkReduction = 0;
212
- switch (change.changeType) {
213
- case 'modify':
214
- // Modifying a rule typically reduces its specific violations by 30-50%
215
- violationReduction = affectedRatio * 0.4;
216
- reworkReduction = change.triggeringViolation.cost * 0.3;
217
- break;
218
- case 'add':
219
- // Adding a new rule typically catches 50-70% of unhandled violations
220
- violationReduction = affectedRatio * 0.6;
221
- reworkReduction = change.triggeringViolation.cost * 0.5;
222
- break;
223
- case 'promote':
224
- // Promoting to root means it's always active, catching 80%+
225
- violationReduction = affectedRatio * 0.8;
226
- reworkReduction = change.triggeringViolation.cost * 0.6;
227
- break;
228
- case 'remove':
229
- // Removing a bad rule might increase violations temporarily
230
- violationReduction = -affectedRatio * 0.2;
231
- reworkReduction = -change.triggeringViolation.cost * 0.1;
232
- break;
233
- default:
234
- break;
235
- }
236
- return {
237
- violationRate: Math.max(0, baseline.violationRate * (1 - violationReduction)),
238
- selfCorrectionRate: Math.min(1, baseline.selfCorrectionRate + violationReduction * 0.1),
239
- reworkLines: Math.max(0, baseline.reworkLines - reworkReduction),
240
- clarifyingQuestions: baseline.clarifyingQuestions,
241
- taskCount: baseline.taskCount,
242
- };
243
- }
244
- /**
245
- * Record an ADR for a rule change decision
246
- */
247
- recordADR(result) {
248
- const adrNumber = this.adrs.length + 1;
249
- return {
250
- number: adrNumber,
251
- title: `${result.shouldPromote ? 'Promote' : 'Reject'}: ${result.change.changeType} rule ${result.change.targetRuleId}`,
252
- decision: result.shouldPromote
253
- ? `Apply ${result.change.changeType} to rule ${result.change.targetRuleId}`
254
- : `Reject proposed ${result.change.changeType} for rule ${result.change.targetRuleId}`,
255
- rationale: result.reason,
256
- change: result.change,
257
- testResult: result,
258
- date: Date.now(),
259
- };
260
- }
261
- /**
262
- * Find a rule in the policy bundle
263
- */
264
- findRule(ruleId, bundle) {
265
- const constitutionRule = bundle.constitution.rules.find(r => r.id === ruleId);
266
- if (constitutionRule)
267
- return constitutionRule;
268
- const shardRule = bundle.shards.find(s => s.rule.id === ruleId);
269
- return shardRule?.rule;
270
- }
271
- /**
272
- * Apply promoted changes to a policy bundle
273
- */
274
- applyPromotions(bundle, promoted, changes) {
275
- // Clone the bundle
276
- const newConstitution = { ...bundle.constitution, rules: [...bundle.constitution.rules] };
277
- const newShards = [...bundle.shards];
278
- for (const ruleId of promoted) {
279
- const change = changes.find(c => c.targetRuleId === ruleId);
280
- if (!change)
281
- continue;
282
- // Find the shard to promote
283
- const shardIdx = newShards.findIndex(s => s.rule.id === ruleId);
284
- if (shardIdx >= 0) {
285
- const shard = newShards[shardIdx];
286
- const promotedRule = {
287
- ...shard.rule,
288
- source: 'root',
289
- isConstitution: true,
290
- priority: shard.rule.priority + 100,
291
- text: change.proposedText || shard.rule.text,
292
- updatedAt: Date.now(),
293
- };
294
- // Add to constitution
295
- newConstitution.rules.push(promotedRule);
296
- // Remove from shards
297
- newShards.splice(shardIdx, 1);
298
- }
299
- }
300
- return {
301
- constitution: newConstitution,
302
- shards: newShards,
303
- manifest: bundle.manifest, // Manifest would need recompilation
304
- };
305
- }
306
- // ===== Getters =====
307
- get lastRun() {
308
- return this.lastOptimizationRun;
309
- }
310
- getADRs() {
311
- return [...this.adrs];
312
- }
313
- getProposedChanges() {
314
- return [...this.proposedChanges];
315
- }
316
- getTestResults() {
317
- return [...this.testResults];
318
- }
319
- getPromotionTracker() {
320
- return new Map(this.promotionTracker);
321
- }
322
- }
323
- /**
324
- * Create an optimizer instance
325
- */
326
- export function createOptimizer(config) {
327
- return new OptimizerLoop(config);
328
- }
329
- //# sourceMappingURL=optimizer.js.map
@@ -1,189 +0,0 @@
1
- /**
2
- * Ledger Persistence Layer
3
- *
4
- * Connects the in-memory RunLedger to durable file-based storage using
5
- * newline-delimited JSON (NDJSON). Provides append-only event logging,
6
- * compaction, and lock-based concurrent access prevention.
7
- *
8
- * Storage layout:
9
- * {storagePath}/events.ndjson - Newline-delimited JSON events
10
- * {storagePath}/index.json - Metadata index (counts, timestamps, task IDs)
11
- * {storagePath}/.lock - Lock file for concurrent access prevention
12
- *
13
- * @module @monomind/guidance/persistence
14
- */
15
- import { RunLedger } from './ledger.js';
16
- import type { RunEvent } from './types.js';
17
- /**
18
- * Configuration for the persistent ledger
19
- */
20
- export interface PersistenceConfig {
21
- /** Directory path for storage files (default: '.monomind/guidance') */
22
- storagePath: string;
23
- /** Maximum events to keep; oldest evicted on compact (default: 10000) */
24
- maxEvents: number;
25
- /** How often to compact/vacuum in milliseconds (default: 1 hour) */
26
- compactIntervalMs: number;
27
- /** Enable write-ahead logging style (flush after each write) (default: true) */
28
- enableWAL: boolean;
29
- }
30
- /**
31
- * Storage statistics
32
- */
33
- export interface StorageStats {
34
- /** Total number of stored events */
35
- eventCount: number;
36
- /** Storage size in bytes */
37
- storageSizeBytes: number;
38
- /** Timestamp of the oldest event (null if empty) */
39
- oldestEvent: number | null;
40
- /** Timestamp of the newest event (null if empty) */
41
- newestEvent: number | null;
42
- }
43
- /**
44
- * Low-level NDJSON-based event storage.
45
- *
46
- * Handles file I/O, append-only writes, range reads, compaction,
47
- * and lock-based concurrent access prevention.
48
- */
49
- export declare class EventStore {
50
- private readonly eventsPath;
51
- private readonly indexPath;
52
- private readonly lockPath;
53
- private readonly baseDir;
54
- private lockHolder;
55
- constructor(storagePath: string);
56
- /**
57
- * Append a single event to the NDJSON file and update the index.
58
- */
59
- append(event: RunEvent): Promise<void>;
60
- /**
61
- * Read and parse all events from storage.
62
- */
63
- readAll(): Promise<RunEvent[]>;
64
- /**
65
- * Read events within a time range [startTime, endTime].
66
- */
67
- readRange(startTime: number, endTime: number): Promise<RunEvent[]>;
68
- /**
69
- * Compact the event store to keep at most `maxEvents` events.
70
- * Oldest events are evicted first. Rewrites the NDJSON file atomically.
71
- *
72
- * @returns The number of evicted events.
73
- */
74
- compact(maxEvents: number): Promise<number>;
75
- /**
76
- * Atomically replace all events in storage with the given array.
77
- * Rewrites the NDJSON file and rebuilds the index.
78
- */
79
- writeAll(events: RunEvent[]): Promise<void>;
80
- /**
81
- * Get storage statistics.
82
- */
83
- getStats(): Promise<StorageStats>;
84
- /**
85
- * Acquire a file-based lock for concurrent access prevention.
86
- * Throws if the lock is already held by another process.
87
- */
88
- acquireLock(): Promise<void>;
89
- /**
90
- * Release the file-based lock.
91
- */
92
- releaseLock(): Promise<void>;
93
- /**
94
- * Remove all storage files (events, index, lock).
95
- */
96
- destroy(): Promise<void>;
97
- /**
98
- * Ensure the storage directory exists.
99
- */
100
- private ensureDirectory;
101
- /**
102
- * Parse an NDJSON string into RunEvent array, skipping blank/invalid lines.
103
- */
104
- private parseNdjson;
105
- /**
106
- * Read the index file, returning a default if it does not exist.
107
- */
108
- private readIndex;
109
- /**
110
- * Update the index with a new event.
111
- */
112
- private updateIndex;
113
- /**
114
- * Rebuild the index from a given set of events.
115
- */
116
- private rebuildIndex;
117
- }
118
- /**
119
- * A RunLedger subclass that persists events to NDJSON file storage.
120
- *
121
- * Extends the in-memory RunLedger with:
122
- * - Automatic persistence on logEvent()
123
- * - Load from storage on init via importEvents()
124
- * - Explicit save()/load() for bulk operations
125
- * - Compaction to enforce maxEvents limit
126
- * - Storage statistics
127
- * - Automatic periodic compaction via interval timer
128
- */
129
- export declare class PersistentLedger extends RunLedger {
130
- private readonly config;
131
- private readonly store;
132
- private compactTimer;
133
- private initialized;
134
- constructor(config?: Partial<PersistenceConfig>);
135
- /**
136
- * Initialize the persistent ledger: load existing events from storage
137
- * and start the compaction timer.
138
- */
139
- init(): Promise<void>;
140
- /**
141
- * Override logEvent to also persist the event to storage.
142
- */
143
- logEvent(event: RunEvent | Omit<RunEvent, 'eventId'>): RunEvent;
144
- /**
145
- * Override importEvents to also persist imported events to storage.
146
- */
147
- importEvents(events: RunEvent[]): void;
148
- /**
149
- * Flush all in-memory events to storage, replacing the storage contents.
150
- * This performs a full atomic rewrite of the NDJSON file.
151
- */
152
- save(): Promise<void>;
153
- /**
154
- * Restore events from storage into memory.
155
- * Clears the in-memory ledger first, then loads all stored events.
156
- */
157
- load(): Promise<void>;
158
- /**
159
- * Compact the storage to keep at most maxEvents events.
160
- * Also updates the in-memory ledger to match.
161
- *
162
- * @returns The number of evicted events.
163
- */
164
- compact(): Promise<number>;
165
- /**
166
- * Get storage statistics.
167
- */
168
- getStorageStats(): Promise<StorageStats>;
169
- /**
170
- * Clean up resources (stop compaction timer, release locks, etc.).
171
- */
172
- destroy(): Promise<void>;
173
- /**
174
- * Get the underlying EventStore (for advanced use / testing).
175
- */
176
- getEventStore(): EventStore;
177
- private startCompactTimer;
178
- private stopCompactTimer;
179
- }
180
- /**
181
- * Create a PersistentLedger instance. Call `init()` after creation to load
182
- * existing events from storage.
183
- */
184
- export declare function createPersistentLedger(config?: Partial<PersistenceConfig>): PersistentLedger;
185
- /**
186
- * Create an EventStore instance for direct low-level storage access.
187
- */
188
- export declare function createEventStore(path: string): EventStore;
189
- //# sourceMappingURL=persistence.d.ts.map