magi-ai 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (300) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +377 -0
  3. package/README.md +377 -0
  4. package/dist/bin/magi-benchmark.d.ts +14 -0
  5. package/dist/bin/magi-benchmark.js +93 -0
  6. package/dist/bin/magi-mcp.d.ts +8 -0
  7. package/dist/bin/magi-mcp.js +28 -0
  8. package/dist/bin/magi.d.ts +2 -0
  9. package/dist/bin/magi.js +634 -0
  10. package/dist/src/adapters/base.d.ts +34 -0
  11. package/dist/src/adapters/base.js +149 -0
  12. package/dist/src/adapters/claude.d.ts +29 -0
  13. package/dist/src/adapters/claude.js +65 -0
  14. package/dist/src/adapters/codex.d.ts +21 -0
  15. package/dist/src/adapters/codex.js +41 -0
  16. package/dist/src/adapters/gemini.d.ts +18 -0
  17. package/dist/src/adapters/gemini.js +31 -0
  18. package/dist/src/adapters/registry.d.ts +19 -0
  19. package/dist/src/adapters/registry.js +59 -0
  20. package/dist/src/audit/hash-chain.d.ts +21 -0
  21. package/dist/src/audit/hash-chain.js +70 -0
  22. package/dist/src/audit/types.d.ts +25 -0
  23. package/dist/src/audit/types.js +1 -0
  24. package/dist/src/audit/writer.d.ts +18 -0
  25. package/dist/src/audit/writer.js +100 -0
  26. package/dist/src/benchmark/golden-tasks.d.ts +9 -0
  27. package/dist/src/benchmark/golden-tasks.js +476 -0
  28. package/dist/src/benchmark/reporter.d.ts +5 -0
  29. package/dist/src/benchmark/reporter.js +107 -0
  30. package/dist/src/benchmark/runner.d.ts +30 -0
  31. package/dist/src/benchmark/runner.js +224 -0
  32. package/dist/src/benchmark/scorer.d.ts +12 -0
  33. package/dist/src/benchmark/scorer.js +124 -0
  34. package/dist/src/benchmark/types.d.ts +54 -0
  35. package/dist/src/benchmark/types.js +1 -0
  36. package/dist/src/cache/deliberation-cache.d.ts +49 -0
  37. package/dist/src/cache/deliberation-cache.js +127 -0
  38. package/dist/src/cli/commands/config-cmd.d.ts +11 -0
  39. package/dist/src/cli/commands/config-cmd.js +190 -0
  40. package/dist/src/cli/commands/demo.d.ts +12 -0
  41. package/dist/src/cli/commands/demo.js +66 -0
  42. package/dist/src/cli/commands/setup.d.ts +7 -0
  43. package/dist/src/cli/commands/setup.js +182 -0
  44. package/dist/src/cli/i18n.d.ts +89 -0
  45. package/dist/src/cli/i18n.js +176 -0
  46. package/dist/src/cli/interactive-select.d.ts +27 -0
  47. package/dist/src/cli/interactive-select.js +130 -0
  48. package/dist/src/cli/tui-setup.d.ts +24 -0
  49. package/dist/src/cli/tui-setup.js +42 -0
  50. package/dist/src/config/cli-detector.d.ts +37 -0
  51. package/dist/src/config/cli-detector.js +99 -0
  52. package/dist/src/config/user-config.d.ts +81 -0
  53. package/dist/src/config/user-config.js +134 -0
  54. package/dist/src/context/auto-collector.d.ts +43 -0
  55. package/dist/src/context/auto-collector.js +337 -0
  56. package/dist/src/context/manager.d.ts +35 -0
  57. package/dist/src/context/manager.js +162 -0
  58. package/dist/src/context/serializer.d.ts +20 -0
  59. package/dist/src/context/serializer.js +52 -0
  60. package/dist/src/demo/recorded-deliberation.d.ts +13 -0
  61. package/dist/src/demo/recorded-deliberation.js +277 -0
  62. package/dist/src/engine/angel-detector.d.ts +83 -0
  63. package/dist/src/engine/angel-detector.js +334 -0
  64. package/dist/src/engine/at-field.d.ts +40 -0
  65. package/dist/src/engine/at-field.js +195 -0
  66. package/dist/src/engine/berserk-orchestrator.d.ts +66 -0
  67. package/dist/src/engine/berserk-orchestrator.js +378 -0
  68. package/dist/src/engine/change-metrics.d.ts +56 -0
  69. package/dist/src/engine/change-metrics.js +214 -0
  70. package/dist/src/engine/consensus.d.ts +20 -0
  71. package/dist/src/engine/consensus.js +146 -0
  72. package/dist/src/engine/dead-sea-scrolls.d.ts +132 -0
  73. package/dist/src/engine/dead-sea-scrolls.js +610 -0
  74. package/dist/src/engine/drift-detector.d.ts +39 -0
  75. package/dist/src/engine/drift-detector.js +225 -0
  76. package/dist/src/engine/dummy-plug.d.ts +44 -0
  77. package/dist/src/engine/dummy-plug.js +190 -0
  78. package/dist/src/engine/engram-manager.d.ts +55 -0
  79. package/dist/src/engine/engram-manager.js +306 -0
  80. package/dist/src/engine/events.d.ts +130 -0
  81. package/dist/src/engine/events.js +44 -0
  82. package/dist/src/engine/gospel.d.ts +30 -0
  83. package/dist/src/engine/gospel.js +129 -0
  84. package/dist/src/engine/hallucination-detector.d.ts +33 -0
  85. package/dist/src/engine/hallucination-detector.js +215 -0
  86. package/dist/src/engine/human-resolver.d.ts +19 -0
  87. package/dist/src/engine/human-resolver.js +89 -0
  88. package/dist/src/engine/instrumentality.d.ts +64 -0
  89. package/dist/src/engine/instrumentality.js +297 -0
  90. package/dist/src/engine/iruel-battle.d.ts +79 -0
  91. package/dist/src/engine/iruel-battle.js +319 -0
  92. package/dist/src/engine/kernel/deliberation-kernel.d.ts +12 -0
  93. package/dist/src/engine/kernel/deliberation-kernel.js +303 -0
  94. package/dist/src/engine/kernel/index.d.ts +8 -0
  95. package/dist/src/engine/kernel/index.js +7 -0
  96. package/dist/src/engine/kernel/phase-runner.d.ts +10 -0
  97. package/dist/src/engine/kernel/phase-runner.js +155 -0
  98. package/dist/src/engine/kernel/post-processor.d.ts +17 -0
  99. package/dist/src/engine/kernel/post-processor.js +131 -0
  100. package/dist/src/engine/kernel/types.d.ts +107 -0
  101. package/dist/src/engine/kernel/types.js +1 -0
  102. package/dist/src/engine/kernel/unit-executor.d.ts +6 -0
  103. package/dist/src/engine/kernel/unit-executor.js +132 -0
  104. package/dist/src/engine/lcl-manager.d.ts +44 -0
  105. package/dist/src/engine/lcl-manager.js +143 -0
  106. package/dist/src/engine/middleware/cache.d.ts +7 -0
  107. package/dist/src/engine/middleware/cache.js +29 -0
  108. package/dist/src/engine/middleware/chain.d.ts +18 -0
  109. package/dist/src/engine/middleware/chain.js +45 -0
  110. package/dist/src/engine/middleware/firewall.d.ts +8 -0
  111. package/dist/src/engine/middleware/firewall.js +24 -0
  112. package/dist/src/engine/middleware/index.d.ts +4 -0
  113. package/dist/src/engine/middleware/index.js +3 -0
  114. package/dist/src/engine/middleware/types.d.ts +43 -0
  115. package/dist/src/engine/middleware/types.js +1 -0
  116. package/dist/src/engine/nebuchadnezzar-key.d.ts +61 -0
  117. package/dist/src/engine/nebuchadnezzar-key.js +203 -0
  118. package/dist/src/engine/neon-genesis.d.ts +52 -0
  119. package/dist/src/engine/neon-genesis.js +203 -0
  120. package/dist/src/engine/objective-judge.d.ts +53 -0
  121. package/dist/src/engine/objective-judge.js +214 -0
  122. package/dist/src/engine/offline-mode.d.ts +18 -0
  123. package/dist/src/engine/offline-mode.js +46 -0
  124. package/dist/src/engine/orchestrator.d.ts +79 -0
  125. package/dist/src/engine/orchestrator.js +58 -0
  126. package/dist/src/engine/secret-cipher.d.ts +26 -0
  127. package/dist/src/engine/secret-cipher.js +114 -0
  128. package/dist/src/engine/seele-council.d.ts +90 -0
  129. package/dist/src/engine/seele-council.js +482 -0
  130. package/dist/src/engine/self-destruct.d.ts +61 -0
  131. package/dist/src/engine/self-destruct.js +231 -0
  132. package/dist/src/engine/self-evolution.d.ts +64 -0
  133. package/dist/src/engine/self-evolution.js +368 -0
  134. package/dist/src/engine/sync-rate.d.ts +45 -0
  135. package/dist/src/engine/sync-rate.js +151 -0
  136. package/dist/src/engine/type666-firewall.d.ts +76 -0
  137. package/dist/src/engine/type666-firewall.js +343 -0
  138. package/dist/src/engine/umbilical-cable.d.ts +41 -0
  139. package/dist/src/engine/umbilical-cable.js +192 -0
  140. package/dist/src/index.d.ts +106 -0
  141. package/dist/src/index.js +426 -0
  142. package/dist/src/mcp/server.d.ts +38 -0
  143. package/dist/src/mcp/server.js +196 -0
  144. package/dist/src/metrics/token-tracker.d.ts +38 -0
  145. package/dist/src/metrics/token-tracker.js +112 -0
  146. package/dist/src/parsers/json-extractor.d.ts +9 -0
  147. package/dist/src/parsers/json-extractor.js +239 -0
  148. package/dist/src/parsers/opinion-schema.d.ts +81 -0
  149. package/dist/src/parsers/opinion-schema.js +147 -0
  150. package/dist/src/parsers/unstructured-parser.d.ts +20 -0
  151. package/dist/src/parsers/unstructured-parser.js +122 -0
  152. package/dist/src/pipelines/architecture.d.ts +10 -0
  153. package/dist/src/pipelines/architecture.js +9 -0
  154. package/dist/src/pipelines/bug-analysis.d.ts +9 -0
  155. package/dist/src/pipelines/bug-analysis.js +8 -0
  156. package/dist/src/pipelines/code-review.d.ts +10 -0
  157. package/dist/src/pipelines/code-review.js +30 -0
  158. package/dist/src/pipelines/custom.d.ts +14 -0
  159. package/dist/src/pipelines/custom.js +29 -0
  160. package/dist/src/pipelines/registry.d.ts +9 -0
  161. package/dist/src/pipelines/registry.js +20 -0
  162. package/dist/src/prompts/personas.d.ts +6 -0
  163. package/dist/src/prompts/personas.js +44 -0
  164. package/dist/src/prompts/schemas.d.ts +4 -0
  165. package/dist/src/prompts/schemas.js +24 -0
  166. package/dist/src/prompts/templates.d.ts +6 -0
  167. package/dist/src/prompts/templates.js +91 -0
  168. package/dist/src/repl/accessibility.d.ts +23 -0
  169. package/dist/src/repl/accessibility.js +46 -0
  170. package/dist/src/repl/banner.d.ts +4 -0
  171. package/dist/src/repl/banner.js +28 -0
  172. package/dist/src/repl/boot-animation.d.ts +13 -0
  173. package/dist/src/repl/boot-animation.js +143 -0
  174. package/dist/src/repl/completer.d.ts +21 -0
  175. package/dist/src/repl/completer.js +168 -0
  176. package/dist/src/repl/context.d.ts +24 -0
  177. package/dist/src/repl/context.js +42 -0
  178. package/dist/src/repl/display-utils.d.ts +13 -0
  179. package/dist/src/repl/display-utils.js +65 -0
  180. package/dist/src/repl/event-listener.d.ts +18 -0
  181. package/dist/src/repl/event-listener.js +112 -0
  182. package/dist/src/repl/export-formatter.d.ts +8 -0
  183. package/dist/src/repl/export-formatter.js +73 -0
  184. package/dist/src/repl/ghost-text.d.ts +31 -0
  185. package/dist/src/repl/ghost-text.js +119 -0
  186. package/dist/src/repl/handoff-animation.d.ts +15 -0
  187. package/dist/src/repl/handoff-animation.js +65 -0
  188. package/dist/src/repl/history.d.ts +16 -0
  189. package/dist/src/repl/history.js +130 -0
  190. package/dist/src/repl/job-registry.d.ts +26 -0
  191. package/dist/src/repl/job-registry.js +80 -0
  192. package/dist/src/repl/magi-repl.d.ts +72 -0
  193. package/dist/src/repl/magi-repl.js +1008 -0
  194. package/dist/src/repl/multiline-input.d.ts +45 -0
  195. package/dist/src/repl/multiline-input.js +78 -0
  196. package/dist/src/repl/prompt-builder.d.ts +19 -0
  197. package/dist/src/repl/prompt-builder.js +36 -0
  198. package/dist/src/repl/repl-state.d.ts +5 -0
  199. package/dist/src/repl/repl-state.js +19 -0
  200. package/dist/src/repl/result-display.d.ts +8 -0
  201. package/dist/src/repl/result-display.js +195 -0
  202. package/dist/src/repl/session-stats.d.ts +26 -0
  203. package/dist/src/repl/session-stats.js +119 -0
  204. package/dist/src/repl/slash-commands.d.ts +60 -0
  205. package/dist/src/repl/slash-commands.js +725 -0
  206. package/dist/src/repl/terminal-sanitize.d.ts +14 -0
  207. package/dist/src/repl/terminal-sanitize.js +19 -0
  208. package/dist/src/reporters/console.d.ts +7 -0
  209. package/dist/src/reporters/console.js +78 -0
  210. package/dist/src/reporters/json.d.ts +2 -0
  211. package/dist/src/reporters/json.js +3 -0
  212. package/dist/src/reporters/markdown.d.ts +2 -0
  213. package/dist/src/reporters/markdown.js +65 -0
  214. package/dist/src/reporters/streaming.d.ts +20 -0
  215. package/dist/src/reporters/streaming.js +178 -0
  216. package/dist/src/tui/activity-log.d.ts +23 -0
  217. package/dist/src/tui/activity-log.js +67 -0
  218. package/dist/src/tui/animations.d.ts +39 -0
  219. package/dist/src/tui/animations.js +167 -0
  220. package/dist/src/tui/ansi.d.ts +28 -0
  221. package/dist/src/tui/ansi.js +51 -0
  222. package/dist/src/tui/boot-sequence.d.ts +11 -0
  223. package/dist/src/tui/boot-sequence.js +98 -0
  224. package/dist/src/tui/colors.d.ts +101 -0
  225. package/dist/src/tui/colors.js +71 -0
  226. package/dist/src/tui/header.d.ts +24 -0
  227. package/dist/src/tui/header.js +122 -0
  228. package/dist/src/tui/index.d.ts +3 -0
  229. package/dist/src/tui/index.js +3 -0
  230. package/dist/src/tui/keypress.d.ts +25 -0
  231. package/dist/src/tui/keypress.js +95 -0
  232. package/dist/src/tui/layout.d.ts +74 -0
  233. package/dist/src/tui/layout.js +171 -0
  234. package/dist/src/tui/magi-tui.d.ts +101 -0
  235. package/dist/src/tui/magi-tui.js +754 -0
  236. package/dist/src/tui/panel.d.ts +45 -0
  237. package/dist/src/tui/panel.js +292 -0
  238. package/dist/src/tui/screen-buffer.d.ts +54 -0
  239. package/dist/src/tui/screen-buffer.js +262 -0
  240. package/dist/src/tui/status-bar.d.ts +25 -0
  241. package/dist/src/tui/status-bar.js +124 -0
  242. package/dist/src/tui/terminal-detect.d.ts +26 -0
  243. package/dist/src/tui/terminal-detect.js +44 -0
  244. package/dist/src/tui/tui-helpers.d.ts +12 -0
  245. package/dist/src/tui/tui-helpers.js +37 -0
  246. package/dist/src/types/adapter.d.ts +75 -0
  247. package/dist/src/types/adapter.js +36 -0
  248. package/dist/src/types/config.d.ts +108 -0
  249. package/dist/src/types/config.js +85 -0
  250. package/dist/src/types/consensus.d.ts +55 -0
  251. package/dist/src/types/consensus.js +17 -0
  252. package/dist/src/types/core.d.ts +178 -0
  253. package/dist/src/types/core.js +85 -0
  254. package/dist/src/types/magi-api.d.ts +62 -0
  255. package/dist/src/types/magi-api.js +7 -0
  256. package/dist/src/types/phase-h.d.ts +142 -0
  257. package/dist/src/types/phase-h.js +7 -0
  258. package/dist/src/types/phase-i.d.ts +186 -0
  259. package/dist/src/types/phase-i.js +6 -0
  260. package/dist/src/types/phase-k.d.ts +259 -0
  261. package/dist/src/types/phase-k.js +6 -0
  262. package/dist/src/types/phase-l.d.ts +199 -0
  263. package/dist/src/types/phase-l.js +6 -0
  264. package/dist/src/types/pipeline.d.ts +37 -0
  265. package/dist/src/types/pipeline.js +2 -0
  266. package/dist/src/utils/abstain-factory.d.ts +2 -0
  267. package/dist/src/utils/abstain-factory.js +18 -0
  268. package/dist/src/utils/errors.d.ts +34 -0
  269. package/dist/src/utils/errors.js +59 -0
  270. package/dist/src/utils/file-validator.d.ts +50 -0
  271. package/dist/src/utils/file-validator.js +124 -0
  272. package/dist/src/utils/fire-and-forget.d.ts +5 -0
  273. package/dist/src/utils/fire-and-forget.js +10 -0
  274. package/dist/src/utils/flag-validator.d.ts +21 -0
  275. package/dist/src/utils/flag-validator.js +79 -0
  276. package/dist/src/utils/freeze.d.ts +8 -0
  277. package/dist/src/utils/freeze.js +16 -0
  278. package/dist/src/utils/language-detector.d.ts +16 -0
  279. package/dist/src/utils/language-detector.js +159 -0
  280. package/dist/src/utils/latency-tracker.d.ts +45 -0
  281. package/dist/src/utils/latency-tracker.js +100 -0
  282. package/dist/src/utils/logger.d.ts +33 -0
  283. package/dist/src/utils/logger.js +112 -0
  284. package/dist/src/utils/process.d.ts +40 -0
  285. package/dist/src/utils/process.js +253 -0
  286. package/dist/src/utils/retry.d.ts +12 -0
  287. package/dist/src/utils/retry.js +30 -0
  288. package/dist/src/utils/safe-fs.d.ts +38 -0
  289. package/dist/src/utils/safe-fs.js +56 -0
  290. package/dist/src/utils/safe-json-parse.d.ts +15 -0
  291. package/dist/src/utils/safe-json-parse.js +49 -0
  292. package/dist/src/utils/sanitize.d.ts +14 -0
  293. package/dist/src/utils/sanitize.js +186 -0
  294. package/dist/src/utils/semaphore.d.ts +22 -0
  295. package/dist/src/utils/semaphore.js +57 -0
  296. package/dist/src/utils/shutdown.d.ts +6 -0
  297. package/dist/src/utils/shutdown.js +51 -0
  298. package/dist/src/utils/tty.d.ts +5 -0
  299. package/dist/src/utils/tty.js +7 -0
  300. package/package.json +82 -0
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Shared types for kernel modules.
3
+ *
4
+ * Defines the dependency contracts between kernel sub-modules
5
+ * (UnitExecutor, PhaseRunner, PostProcessor, DeliberationKernel).
6
+ */
7
+ import type { MagiTask, MagiOpinion, DeliberationRound, DeliberationPhase, MagiDeliberation } from '../../types/core.js';
8
+ import type { PipelineConfig, IPipeline } from '../../types/pipeline.js';
9
+ import type { ICliAdapter } from '../../types/adapter.js';
10
+ import type { AdapterRegistry } from '../../adapters/registry.js';
11
+ import type { PipelineRegistry } from '../../pipelines/registry.js';
12
+ import type { ConsensusEngine } from '../consensus.js';
13
+ import type { ConsensusResult } from '../../types/consensus.js';
14
+ import type { ContextManager } from '../../context/manager.js';
15
+ import type { MagiEventBus } from '../events.js';
16
+ import type { TokenTracker } from '../../metrics/token-tracker.js';
17
+ import type { ObjectiveJudge, ObjectiveResult } from '../objective-judge.js';
18
+ import type { LatencyTracker } from '../../utils/latency-tracker.js';
19
+ import type { SyncRateTracker } from '../sync-rate.js';
20
+ import type { ATField } from '../at-field.js';
21
+ import type { GospelChronicle } from '../gospel.js';
22
+ import type { UmbilicalCable } from '../umbilical-cable.js';
23
+ import type { DummyPlugSystem } from '../dummy-plug.js';
24
+ import type { OfflineMode } from '../offline-mode.js';
25
+ import type { EngramManager } from '../engram-manager.js';
26
+ import type { LCLManager } from '../lcl-manager.js';
27
+ import type { InstrumentalityEngine } from '../instrumentality.js';
28
+ import type { DriftDetector } from '../drift-detector.js';
29
+ import type { Type666Firewall } from '../type666-firewall.js';
30
+ import type { NebuchadnezzarKey } from '../nebuchadnezzar-key.js';
31
+ import type { IruelBattleSystem } from '../iruel-battle.js';
32
+ import type { DeliberationCache } from '../../cache/deliberation-cache.js';
33
+ /** Optional modules injected into the kernel. */
34
+ export interface OptionalModules {
35
+ tokenTracker?: TokenTracker;
36
+ objectiveJudge?: ObjectiveJudge;
37
+ syncRateTracker?: SyncRateTracker;
38
+ atField?: ATField;
39
+ gospel?: GospelChronicle;
40
+ umbilicalCable?: UmbilicalCable;
41
+ dummyPlug?: DummyPlugSystem;
42
+ offlineMode?: OfflineMode;
43
+ engramManager?: EngramManager;
44
+ lclManager?: LCLManager;
45
+ instrumentality?: InstrumentalityEngine;
46
+ driftDetector?: DriftDetector;
47
+ type666Firewall?: Type666Firewall;
48
+ nebuchadnezzarKey?: NebuchadnezzarKey;
49
+ iruelBattle?: IruelBattleSystem;
50
+ cache?: DeliberationCache;
51
+ }
52
+ /** Core dependencies shared across all kernel sub-modules. */
53
+ export interface KernelDependencies {
54
+ adapters: AdapterRegistry;
55
+ pipelines: PipelineRegistry;
56
+ contextManager: ContextManager;
57
+ latencyTracker: LatencyTracker;
58
+ eventBus?: MagiEventBus;
59
+ modules: OptionalModules;
60
+ /** Allow CLIs to read project files during deliberation */
61
+ fileAccessEnabled?: boolean;
62
+ }
63
+ /** BERSERK strategy metadata for unit execution. */
64
+ export interface BerserkStrategyParam {
65
+ name: string;
66
+ promptPrefix: string;
67
+ }
68
+ /** Parameters for a single unit execution. */
69
+ export interface UnitExecutionParams {
70
+ deliberationId: string;
71
+ adapter: ICliAdapter;
72
+ task: MagiTask;
73
+ pipeline: IPipeline;
74
+ phase: DeliberationPhase;
75
+ previousRounds: DeliberationRound[];
76
+ config: PipelineConfig;
77
+ objectiveSummary?: string;
78
+ signal?: AbortSignal;
79
+ /** When set, prepends BERSERK strategy prefix to the system prompt. */
80
+ berserkStrategy?: BerserkStrategyParam;
81
+ /** Allow CLIs to read project files */
82
+ fileAccessEnabled?: boolean;
83
+ }
84
+ /** Parameters for running a phase. */
85
+ export interface PhaseRunParams {
86
+ deliberationId: string;
87
+ task: MagiTask;
88
+ pipeline: IPipeline;
89
+ phase: DeliberationPhase;
90
+ previousRounds: DeliberationRound[];
91
+ config: PipelineConfig;
92
+ objectiveSummary?: string;
93
+ /** Allow CLIs to read project files */
94
+ fileAccessEnabled?: boolean;
95
+ }
96
+ /** Result context built during a deliberation. */
97
+ export interface DeliberationContext {
98
+ id: string;
99
+ task: MagiTask;
100
+ config: PipelineConfig;
101
+ rounds: DeliberationRound[];
102
+ pendingIO: Promise<void>[];
103
+ startedAt: Date;
104
+ objectiveResult?: ObjectiveResult;
105
+ consensus?: ConsensusResult;
106
+ }
107
+ export type { MagiTask, MagiOpinion, DeliberationRound, DeliberationPhase, MagiDeliberation, PipelineConfig, IPipeline, ICliAdapter, ConsensusResult, ConsensusEngine, ObjectiveResult, MagiEventBus, ContextManager, LatencyTracker, TokenTracker, AdapterRegistry, PipelineRegistry, };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import type { KernelDependencies, UnitExecutionParams, MagiOpinion } from './types.js';
2
+ export declare class UnitExecutor {
3
+ private readonly deps;
4
+ constructor(deps: KernelDependencies);
5
+ execute(params: UnitExecutionParams): Promise<MagiOpinion>;
6
+ }
@@ -0,0 +1,132 @@
1
+ import { OPINION_JSON_SCHEMA } from '../../types/pipeline.js';
2
+ import { buildPersonaPrompt } from '../../prompts/personas.js';
3
+ import { buildUserPrompt } from '../../prompts/templates.js';
4
+ import { logger } from '../../utils/logger.js';
5
+ import { createAbstainOpinion } from '../../utils/abstain-factory.js';
6
+ import { SafeOpinionSchema } from '../../parsers/opinion-schema.js';
7
+ import { estimateTokens } from '../../metrics/token-tracker.js';
8
+ export class UnitExecutor {
9
+ deps;
10
+ constructor(deps) {
11
+ this.deps = deps;
12
+ }
13
+ async execute(params) {
14
+ const { deliberationId, adapter, task, pipeline, phase, previousRounds, config, objectiveSummary, signal, berserkStrategy, } = params;
15
+ const { eventBus, latencyTracker } = this.deps;
16
+ const { tokenTracker } = this.deps.modules;
17
+ eventBus?.emit('unit:start', {
18
+ deliberationId,
19
+ unit: adapter.unit,
20
+ phase,
21
+ emittedAt: new Date(),
22
+ });
23
+ // Build persona prompt (each AI brings its own expertise naturally)
24
+ const basePrompt = buildPersonaPrompt(adapter.unit, phase);
25
+ const systemPrompt = berserkStrategy
26
+ ? `[BERSERK MODE: ${berserkStrategy.name}]\n${berserkStrategy.promptPrefix}\n\n${basePrompt}`
27
+ : basePrompt;
28
+ // For cross-examination, pass other units' opinions from the last round
29
+ const lastRound = previousRounds[previousRounds.length - 1];
30
+ const otherOpinions = lastRound?.opinions.filter((o) => o.unit !== adapter.unit);
31
+ const userPrompt = buildUserPrompt(task, adapter.unit, phase, previousRounds, otherOpinions, objectiveSummary);
32
+ // File access requires more time for CLIs to explore the codebase
33
+ const baseTimeout = latencyTracker.getTimeout(adapter.unit, config.adapterTimeoutMs);
34
+ const timeoutMs = params.fileAccessEnabled ? Math.min(baseTimeout * 2, 600_000) : baseTimeout;
35
+ const execStart = Date.now();
36
+ let response;
37
+ try {
38
+ response = await adapter.execute({
39
+ prompt: userPrompt,
40
+ systemPrompt: adapter.supportsSystemPrompt() ? systemPrompt : undefined,
41
+ jsonSchema: adapter.supportsStructuredOutput() ? OPINION_JSON_SCHEMA : undefined,
42
+ timeoutMs,
43
+ signal,
44
+ fileAccessEnabled: params.fileAccessEnabled,
45
+ cwd: params.fileAccessEnabled ? process.cwd() : undefined,
46
+ onStdoutChunk: (chunk) => {
47
+ eventBus?.emit('unit:chunk', {
48
+ deliberationId,
49
+ unit: adapter.unit,
50
+ chunk,
51
+ stream: 'stdout',
52
+ emittedAt: new Date(),
53
+ });
54
+ },
55
+ onStderrChunk: (chunk) => {
56
+ eventBus?.emit('unit:chunk', {
57
+ deliberationId,
58
+ unit: adapter.unit,
59
+ chunk,
60
+ stream: 'stderr',
61
+ emittedAt: new Date(),
62
+ });
63
+ },
64
+ });
65
+ latencyTracker.record(adapter.unit, Date.now() - execStart, true);
66
+ }
67
+ catch (err) {
68
+ latencyTracker.record(adapter.unit, Date.now() - execStart, false);
69
+ throw err;
70
+ }
71
+ // Track token usage (fire-and-forget)
72
+ if (tokenTracker) {
73
+ tokenTracker.addRecord({
74
+ deliberationId,
75
+ unit: adapter.unit,
76
+ phase,
77
+ estimatedInputTokens: estimateTokens(userPrompt),
78
+ estimatedOutputTokens: estimateTokens(response.raw),
79
+ timestamp: new Date(),
80
+ });
81
+ }
82
+ // Parse opinion from response
83
+ const partialOpinion = pipeline.parseOpinion(response.raw, response.structured, adapter.unit, phase);
84
+ // Validate opinion at trust boundary using SafeOpinionSchema
85
+ const safeResult = SafeOpinionSchema.safeParse({
86
+ vote: partialOpinion.vote,
87
+ confidence: partialOpinion.confidence,
88
+ reasoning: partialOpinion.reasoning,
89
+ keyPoints: partialOpinion.keyPoints,
90
+ suggestions: partialOpinion.suggestions,
91
+ });
92
+ if (safeResult.success) {
93
+ logger.audit('adapter.success', deliberationId, {
94
+ unit: adapter.unit,
95
+ phase,
96
+ vote: safeResult.data.vote,
97
+ });
98
+ eventBus?.emit('unit:complete', {
99
+ deliberationId,
100
+ unit: adapter.unit,
101
+ phase,
102
+ vote: safeResult.data.vote,
103
+ confidence: safeResult.data.confidence,
104
+ durationMs: Date.now() - execStart,
105
+ reasoningSummary: safeResult.data.reasoning.slice(0, 300),
106
+ emittedAt: new Date(),
107
+ });
108
+ return {
109
+ unit: partialOpinion.unit,
110
+ vote: safeResult.data.vote,
111
+ confidence: safeResult.data.confidence,
112
+ reasoning: safeResult.data.reasoning,
113
+ keyPoints: safeResult.data.keyPoints,
114
+ suggestions: safeResult.data.suggestions,
115
+ rawOutput: response.raw,
116
+ meta: response.meta,
117
+ };
118
+ }
119
+ // Validation failed -- demote to ABSTAIN
120
+ logger.warn(`${adapter.displayName} opinion failed safe validation, demoting to ABSTAIN`, {
121
+ unit: adapter.unit,
122
+ phase,
123
+ error: String(safeResult.error),
124
+ });
125
+ logger.audit('validation.failure', deliberationId, {
126
+ unit: adapter.unit,
127
+ phase,
128
+ error: String(safeResult.error),
129
+ });
130
+ return createAbstainOpinion(adapter.unit, `Opinion from ${adapter.displayName} failed safe validation: ${String(safeResult.error)}`, ['Opinion validation failed at trust boundary'], { rawOutput: response.raw, meta: response.meta });
131
+ }
132
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * LCLManager — Shared Consciousness Pool (共有意識プール)
3
+ *
4
+ * Controls how much context is shared between MAGI units at each
5
+ * deliberation phase. Uses LCL density (0.0-1.0) to determine the
6
+ * degree of information sharing, and integrates HallucinationDetector
7
+ * to purify contaminated opinions.
8
+ *
9
+ * Part of B-02 LCL.
10
+ */
11
+ import type { MagiOpinion, DeliberationPhase } from '../types/core.js';
12
+ import type { LCLPhaseConfig, LCLDensity, LCLContaminationResult } from '../types/phase-i.js';
13
+ import type { MagiEventBus } from './events.js';
14
+ export declare class LCLManager {
15
+ private readonly densities;
16
+ private readonly eventBus;
17
+ private readonly detector;
18
+ constructor(config?: Partial<LCLPhaseConfig>, eventBus?: MagiEventBus);
19
+ /**
20
+ * Generate shared context string from opinions based on current phase density.
21
+ *
22
+ * density 0.0 → empty string (no sharing, full independence)
23
+ * density 1.0 → full reasoning + all keyPoints
24
+ * 0 < density < 1 → proportional trimming
25
+ */
26
+ getSharedContext(phase: DeliberationPhase, opinions: MagiOpinion[]): string;
27
+ /**
28
+ * Analyze an opinion for hallucinations and purify if contaminated.
29
+ * Emits events via eventBus when hallucinations are found and purified.
30
+ */
31
+ purify(opinion: MagiOpinion, deliberationId?: string): LCLContaminationResult;
32
+ /**
33
+ * Dynamically adjust the density for a specific phase.
34
+ */
35
+ setDensity(phase: DeliberationPhase, density: LCLDensity): void;
36
+ /**
37
+ * Get the current density for a specific phase.
38
+ */
39
+ getDensity(phase: DeliberationPhase): LCLDensity;
40
+ /**
41
+ * Get all phase densities as a snapshot.
42
+ */
43
+ getDensities(): Readonly<LCLPhaseConfig>;
44
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * LCLManager — Shared Consciousness Pool (共有意識プール)
3
+ *
4
+ * Controls how much context is shared between MAGI units at each
5
+ * deliberation phase. Uses LCL density (0.0-1.0) to determine the
6
+ * degree of information sharing, and integrates HallucinationDetector
7
+ * to purify contaminated opinions.
8
+ *
9
+ * Part of B-02 LCL.
10
+ */
11
+ import { HallucinationDetector } from './hallucination-detector.js';
12
+ // ── Constants ────────────────────────────────────────────────────
13
+ /** Default LCL density per deliberation phase */
14
+ const DEFAULT_DENSITIES = {
15
+ 'initial-opinion': 0.0,
16
+ 'cross-examination': 0.7,
17
+ 'final-vote': 0.4,
18
+ };
19
+ // ── LCLManager ───────────────────────────────────────────────────
20
+ export class LCLManager {
21
+ densities;
22
+ eventBus;
23
+ detector;
24
+ constructor(config, eventBus) {
25
+ this.densities = {
26
+ ...DEFAULT_DENSITIES,
27
+ ...config,
28
+ };
29
+ this.eventBus = eventBus;
30
+ this.detector = new HallucinationDetector();
31
+ }
32
+ // ── Shared context generation ──────────────────────────────────
33
+ /**
34
+ * Generate shared context string from opinions based on current phase density.
35
+ *
36
+ * density 0.0 → empty string (no sharing, full independence)
37
+ * density 1.0 → full reasoning + all keyPoints
38
+ * 0 < density < 1 → proportional trimming
39
+ */
40
+ getSharedContext(phase, opinions) {
41
+ const density = this.densities[phase];
42
+ if (density <= 0 || opinions.length === 0) {
43
+ return '';
44
+ }
45
+ const sections = [];
46
+ for (const opinion of opinions) {
47
+ const parts = [];
48
+ // Include unit header
49
+ parts.push(`[${opinion.unit}] vote=${opinion.vote} confidence=${opinion.confidence}`);
50
+ // Include proportional keyPoints
51
+ if (opinion.keyPoints.length > 0) {
52
+ const count = Math.max(1, Math.round(opinion.keyPoints.length * density));
53
+ const selectedPoints = opinion.keyPoints.slice(0, count);
54
+ parts.push(`Key points: ${selectedPoints.join('; ')}`);
55
+ }
56
+ // Include truncated reasoning based on density
57
+ if (density >= 1.0) {
58
+ parts.push(`Reasoning: ${opinion.reasoning}`);
59
+ }
60
+ else if (density >= 0.3) {
61
+ const maxLen = Math.round(opinion.reasoning.length * density);
62
+ const truncated = opinion.reasoning.slice(0, maxLen);
63
+ if (truncated.length > 0) {
64
+ parts.push(`Reasoning: ${truncated}...`);
65
+ }
66
+ }
67
+ // density < 0.3 → no reasoning shared (too noisy at low density)
68
+ sections.push(parts.join('\n'));
69
+ }
70
+ return sections.join('\n\n');
71
+ }
72
+ // ── Hallucination purification ─────────────────────────────────
73
+ /**
74
+ * Analyze an opinion for hallucinations and purify if contaminated.
75
+ * Emits events via eventBus when hallucinations are found and purified.
76
+ */
77
+ purify(opinion, deliberationId) {
78
+ const reports = this.detector.detect(opinion);
79
+ if (reports.length === 0) {
80
+ return {
81
+ unit: opinion.unit,
82
+ reports: [],
83
+ purified: false,
84
+ originalConfidence: opinion.confidence,
85
+ adjustedConfidence: opinion.confidence,
86
+ };
87
+ }
88
+ // Emit contamination detection event
89
+ if (this.eventBus && deliberationId) {
90
+ this.eventBus.emit('lcl:contamination-detected', {
91
+ deliberationId,
92
+ unit: opinion.unit,
93
+ hallucinationCount: reports.length,
94
+ types: [...new Set(reports.map(r => r.type))],
95
+ emittedAt: new Date(),
96
+ });
97
+ }
98
+ // Purify the opinion
99
+ const purifiedOpinion = this.detector.purify(opinion, reports);
100
+ const wasPurified = purifiedOpinion.confidence !== opinion.confidence ||
101
+ purifiedOpinion.reasoning !== opinion.reasoning;
102
+ // Emit purification event
103
+ if (wasPurified && this.eventBus && deliberationId) {
104
+ this.eventBus.emit('lcl:purified', {
105
+ deliberationId,
106
+ unit: opinion.unit,
107
+ removedCount: reports.filter(r => r.confidence >= 0.7).length,
108
+ originalConfidence: opinion.confidence,
109
+ adjustedConfidence: purifiedOpinion.confidence,
110
+ emittedAt: new Date(),
111
+ });
112
+ }
113
+ return {
114
+ unit: opinion.unit,
115
+ reports,
116
+ purified: wasPurified,
117
+ originalConfidence: opinion.confidence,
118
+ adjustedConfidence: purifiedOpinion.confidence,
119
+ };
120
+ }
121
+ // ── Density management ─────────────────────────────────────────
122
+ /**
123
+ * Dynamically adjust the density for a specific phase.
124
+ */
125
+ setDensity(phase, density) {
126
+ if (density < 0 || density > 1) {
127
+ throw new RangeError(`LCL density must be between 0.0 and 1.0, got ${density}`);
128
+ }
129
+ this.densities[phase] = density;
130
+ }
131
+ /**
132
+ * Get the current density for a specific phase.
133
+ */
134
+ getDensity(phase) {
135
+ return this.densities[phase];
136
+ }
137
+ /**
138
+ * Get all phase densities as a snapshot.
139
+ */
140
+ getDensities() {
141
+ return { ...this.densities };
142
+ }
143
+ }
@@ -0,0 +1,7 @@
1
+ import type { MiddlewareFn } from './types.js';
2
+ import type { DeliberationCache } from '../../cache/deliberation-cache.js';
3
+ /**
4
+ * Cache middleware -- checks cache before deliberation, stores result after.
5
+ * Only handles the GET (read) side. The cache SET remains in the orchestrator.
6
+ */
7
+ export declare function createCacheMiddleware(cache: DeliberationCache): MiddlewareFn;
@@ -0,0 +1,29 @@
1
+ import { logger } from '../../utils/logger.js';
2
+ /**
3
+ * Cache middleware -- checks cache before deliberation, stores result after.
4
+ * Only handles the GET (read) side. The cache SET remains in the orchestrator.
5
+ */
6
+ export function createCacheMiddleware(cache) {
7
+ return async (ctx, next) => {
8
+ // Check cache
9
+ const cached = cache.get(ctx.task);
10
+ if (cached) {
11
+ logger.info('Cache hit for deliberation', { type: ctx.task.type, title: ctx.task.title });
12
+ logger.audit('deliberation.cache_hit', cached.id, { type: ctx.task.type, title: ctx.task.title });
13
+ ctx.eventBus?.emit('deliberation:complete', {
14
+ deliberationId: cached.id,
15
+ decision: cached.consensus.decision,
16
+ totalDurationMs: cached.totalDurationMs,
17
+ rounds: cached.rounds.length,
18
+ fromCache: true,
19
+ emittedAt: new Date(),
20
+ });
21
+ ctx.cachedResult = cached;
22
+ ctx.skipDeliberation = true;
23
+ // Don't call next() -- short-circuit
24
+ return;
25
+ }
26
+ // Pass through to deliberation
27
+ await next();
28
+ };
29
+ }
@@ -0,0 +1,18 @@
1
+ import type { MiddlewareContext, MiddlewareFn, MiddlewareErrorInfo } from './types.js';
2
+ /**
3
+ * Koa-style middleware chain with error boundary.
4
+ * Each middleware receives context + next().
5
+ * Calling next() passes control to the next middleware in the stack.
6
+ * If a middleware throws, the error is captured and the chain continues.
7
+ */
8
+ export declare class MiddlewareChain {
9
+ private readonly middlewares;
10
+ /** Errors captured during the last execute() call */
11
+ readonly errors: MiddlewareErrorInfo[];
12
+ /** Register a middleware function */
13
+ use(mw: MiddlewareFn): this;
14
+ /** Execute the middleware chain */
15
+ execute(ctx: MiddlewareContext): Promise<void>;
16
+ /** Number of registered middlewares */
17
+ get length(): number;
18
+ }
@@ -0,0 +1,45 @@
1
+ import { logger } from '../../utils/logger.js';
2
+ /**
3
+ * Koa-style middleware chain with error boundary.
4
+ * Each middleware receives context + next().
5
+ * Calling next() passes control to the next middleware in the stack.
6
+ * If a middleware throws, the error is captured and the chain continues.
7
+ */
8
+ export class MiddlewareChain {
9
+ middlewares = [];
10
+ /** Errors captured during the last execute() call */
11
+ errors = [];
12
+ /** Register a middleware function */
13
+ use(mw) {
14
+ this.middlewares.push(mw);
15
+ return this;
16
+ }
17
+ /** Execute the middleware chain */
18
+ async execute(ctx) {
19
+ this.errors.length = 0;
20
+ let index = 0;
21
+ const next = async () => {
22
+ if (index < this.middlewares.length) {
23
+ const currentIndex = index;
24
+ const mw = this.middlewares[index++];
25
+ try {
26
+ await mw(ctx, next);
27
+ }
28
+ catch (err) {
29
+ const error = err instanceof Error ? err : new Error(String(err));
30
+ this.errors.push({ middlewareIndex: currentIndex, error });
31
+ // If middleware set blocked before throwing, respect the block
32
+ if (ctx.blocked)
33
+ return;
34
+ logger.warn(`Middleware[${currentIndex}] error (continuing chain): ${error.message}`);
35
+ await next();
36
+ }
37
+ }
38
+ };
39
+ await next();
40
+ }
41
+ /** Number of registered middlewares */
42
+ get length() {
43
+ return this.middlewares.length;
44
+ }
45
+ }
@@ -0,0 +1,8 @@
1
+ import type { MiddlewareFn } from './types.js';
2
+ import type { Type666Firewall } from '../type666-firewall.js';
3
+ /**
4
+ * Firewall middleware -- scans task input before deliberation.
5
+ * Only handles the pre-scan. The post-deliberation learnFromDeliberation
6
+ * call remains in the orchestrator.
7
+ */
8
+ export declare function createFirewallMiddleware(firewall: Type666Firewall): MiddlewareFn;
@@ -0,0 +1,24 @@
1
+ import { logger } from '../../utils/logger.js';
2
+ /**
3
+ * Firewall middleware -- scans task input before deliberation.
4
+ * Only handles the pre-scan. The post-deliberation learnFromDeliberation
5
+ * call remains in the orchestrator.
6
+ */
7
+ export function createFirewallMiddleware(firewall) {
8
+ return async (ctx, next) => {
9
+ const scanResult = firewall.scan(ctx.task.description);
10
+ if (!scanResult.passed) {
11
+ logger.warn('Type-666 Firewall blocked deliberation input', {
12
+ threats: scanResult.threats.length, totalScore: scanResult.totalScore,
13
+ });
14
+ logger.audit('firewall.blocked', ctx.deliberationId, {
15
+ threats: scanResult.threats.length, totalScore: scanResult.totalScore,
16
+ });
17
+ ctx.blocked = true;
18
+ ctx.blockedReason = `Type-666 Firewall blocked: ${scanResult.threats.length} threats detected (score: ${scanResult.totalScore.toFixed(2)})`;
19
+ return; // Don't call next() -- short-circuit (same pattern as cache)
20
+ }
21
+ logger.audit('firewall.scan', ctx.deliberationId, { passed: true, totalScore: scanResult.totalScore });
22
+ await next();
23
+ };
24
+ }
@@ -0,0 +1,4 @@
1
+ export { MiddlewareChain } from './chain.js';
2
+ export type { MiddlewareContext, MiddlewareFn, MiddlewareErrorInfo } from './types.js';
3
+ export { createCacheMiddleware } from './cache.js';
4
+ export { createFirewallMiddleware } from './firewall.js';
@@ -0,0 +1,3 @@
1
+ export { MiddlewareChain } from './chain.js';
2
+ export { createCacheMiddleware } from './cache.js';
3
+ export { createFirewallMiddleware } from './firewall.js';
@@ -0,0 +1,43 @@
1
+ import type { MagiTask, MagiDeliberation } from '../../types/core.js';
2
+ import type { PipelineConfig } from '../../types/pipeline.js';
3
+ import type { MagiEventBus } from '../events.js';
4
+ /**
5
+ * Context object passed through the middleware chain.
6
+ * Middleware can read and modify the context to affect deliberation behavior.
7
+ */
8
+ export interface MiddlewareContext {
9
+ /** Unique deliberation ID */
10
+ deliberationId: string;
11
+ /** The task being deliberated */
12
+ task: MagiTask;
13
+ /** Pipeline configuration (mutable by middleware) */
14
+ config: PipelineConfig;
15
+ /** Optional event bus */
16
+ eventBus?: MagiEventBus;
17
+ /** Shared metadata bag for cross-middleware communication */
18
+ metadata: Map<string, unknown>;
19
+ /** Set by CacheMiddleware if a cached result is found */
20
+ cachedResult?: MagiDeliberation;
21
+ /** Set to true to skip remaining middleware and return cachedResult */
22
+ skipDeliberation?: boolean;
23
+ /** Set by firewall middleware when input is blocked */
24
+ blocked?: boolean;
25
+ /** Reason for blocking (set alongside blocked) */
26
+ blockedReason?: string;
27
+ }
28
+ /**
29
+ * Middleware function -- Koa-style with next() for chaining.
30
+ * Call next() to pass control to the next middleware.
31
+ * Not calling next() short-circuits the chain.
32
+ */
33
+ export type MiddlewareFn = (ctx: MiddlewareContext, next: () => Promise<void>) => Promise<void>;
34
+ /**
35
+ * Error information captured when a middleware throws.
36
+ * The chain continues execution despite the error.
37
+ */
38
+ export interface MiddlewareErrorInfo {
39
+ /** Index of the middleware that threw */
40
+ middlewareIndex: number;
41
+ /** The captured error */
42
+ error: Error;
43
+ }
@@ -0,0 +1 @@
1
+ export {};