amalfa 0.0.0-reserved → 1.0.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 (139) hide show
  1. package/.biomeignore +19 -0
  2. package/:memory: +0 -0
  3. package/:memory:-shm +0 -0
  4. package/:memory:-wal +0 -0
  5. package/LICENSE +21 -0
  6. package/README.md +343 -13
  7. package/README.old.md +112 -0
  8. package/agents.config.json +11 -0
  9. package/amalfa.config.example.ts +100 -0
  10. package/biome.json +49 -0
  11. package/bun.lock +371 -0
  12. package/docs/AGENT_PROTOCOLS.md +28 -0
  13. package/docs/ARCHITECTURAL_OVERVIEW.md +123 -0
  14. package/docs/BENTO_BOXING_DEPRECATION.md +281 -0
  15. package/docs/Bun-SQLite.html +464 -0
  16. package/docs/COMMIT_GUIDELINES.md +367 -0
  17. package/docs/DEVELOPER_ONBOARDING.md +36 -0
  18. package/docs/Graph and Vector Database Best Practices.md +214 -0
  19. package/docs/PERFORMANCE_BASELINES.md +88 -0
  20. package/docs/REPOSITORY_CLEANUP_SUMMARY.md +261 -0
  21. package/docs/edge-generation-methods.md +57 -0
  22. package/docs/elevator-pitch.md +118 -0
  23. package/docs/graph-and-vector-database-playbook.html +480 -0
  24. package/docs/hardened-sqlite.md +85 -0
  25. package/docs/headless-knowledge-management.md +79 -0
  26. package/docs/john-kaye-flux-prompt.md +46 -0
  27. package/docs/keyboard-shortcuts.md +80 -0
  28. package/docs/opinion-proceed-pattern.md +29 -0
  29. package/docs/polyvis-nodes-edges-schema.md +77 -0
  30. package/docs/protocols/lab-protocol.md +30 -0
  31. package/docs/reaction-iquest-loop-coder.md +46 -0
  32. package/docs/services.md +60 -0
  33. package/docs/sqlite-wal-readonly-trap.md +228 -0
  34. package/docs/strategy/css-architecture.md +40 -0
  35. package/docs/test-document-cycle.md +83 -0
  36. package/docs/test_lifecycle_E2E.md +4 -0
  37. package/docs/the-bicameral-graph.md +83 -0
  38. package/docs/user-guide.md +70 -0
  39. package/docs/vision-helper.md +53 -0
  40. package/drizzle/0000_minor_iron_fist.sql +19 -0
  41. package/drizzle/meta/0000_snapshot.json +139 -0
  42. package/drizzle/meta/_journal.json +13 -0
  43. package/example_usage.ts +39 -0
  44. package/experiment.sh +35 -0
  45. package/hello +2 -0
  46. package/index.html +52 -0
  47. package/knowledge/excalibur.md +12 -0
  48. package/package.json +60 -15
  49. package/plans/experience-graph-integration.md +60 -0
  50. package/prompts/gemini-king-mode-prompt.md +46 -0
  51. package/public/docs/MCP_TOOLS.md +372 -0
  52. package/schemas/README.md +20 -0
  53. package/schemas/cda.schema.json +84 -0
  54. package/schemas/conceptual-lexicon.schema.json +75 -0
  55. package/scratchpads/dummy-debrief-boxed.md +39 -0
  56. package/scratchpads/dummy-debrief.md +27 -0
  57. package/scratchpads/scratchpad-design.md +50 -0
  58. package/scratchpads/scratchpad-scrolling.md +20 -0
  59. package/scratchpads/scratchpad-toc-disappearance.md +23 -0
  60. package/scratchpads/scratchpad-toc.md +28 -0
  61. package/scratchpads/test_gardener.md +7 -0
  62. package/src/EnlightenedTriad.ts +146 -0
  63. package/src/JIT_Triad.ts +137 -0
  64. package/src/cli.ts +318 -0
  65. package/src/config/constants.ts +7 -0
  66. package/src/config/defaults.ts +81 -0
  67. package/src/core/BentoNormalizer.ts +113 -0
  68. package/src/core/EdgeWeaver.ts +145 -0
  69. package/src/core/FractureLogic.ts +22 -0
  70. package/src/core/Harvester.ts +73 -0
  71. package/src/core/LLMClient.ts +93 -0
  72. package/src/core/LouvainGate.ts +67 -0
  73. package/src/core/MarkdownMasker.ts +49 -0
  74. package/src/core/README.md +11 -0
  75. package/src/core/SemanticMatcher.ts +89 -0
  76. package/src/core/SemanticWeaver.ts +96 -0
  77. package/src/core/TagEngine.ts +56 -0
  78. package/src/core/TimelineWeaver.ts +61 -0
  79. package/src/core/VectorEngine.ts +232 -0
  80. package/src/daemon/index.ts +221 -0
  81. package/src/data/experience/test_doc_1.md +2 -0
  82. package/src/data/experience/test_doc_2.md +2 -0
  83. package/src/db/schema.ts +46 -0
  84. package/src/demo-triad.ts +45 -0
  85. package/src/gardeners/AutoTagger.ts +116 -0
  86. package/src/gardeners/BaseGardener.ts +55 -0
  87. package/src/llm/EnlightenedProvider.ts +95 -0
  88. package/src/mcp/README.md +6 -0
  89. package/src/mcp/index.ts +341 -0
  90. package/src/pipeline/AmalfaIngestor.ts +262 -0
  91. package/src/pipeline/HarvesterPipeline.ts +101 -0
  92. package/src/pipeline/Ingestor.ts +555 -0
  93. package/src/pipeline/README.md +7 -0
  94. package/src/pipeline/SemanticHarvester.ts +222 -0
  95. package/src/resonance/DatabaseFactory.ts +100 -0
  96. package/src/resonance/README.md +148 -0
  97. package/src/resonance/cli/README.md +7 -0
  98. package/src/resonance/cli/ingest.ts +41 -0
  99. package/src/resonance/cli/migrate.ts +54 -0
  100. package/src/resonance/config.ts +40 -0
  101. package/src/resonance/daemon.ts +236 -0
  102. package/src/resonance/db.ts +422 -0
  103. package/src/resonance/pipeline/README.md +7 -0
  104. package/src/resonance/pipeline/extract.ts +89 -0
  105. package/src/resonance/pipeline/transform_docs.ts +60 -0
  106. package/src/resonance/schema.ts +138 -0
  107. package/src/resonance/services/embedder.ts +131 -0
  108. package/src/resonance/services/simpleTokenizer.ts +119 -0
  109. package/src/resonance/services/stats.ts +327 -0
  110. package/src/resonance/services/tokenizer.ts +159 -0
  111. package/src/resonance/transform/cda.ts +393 -0
  112. package/src/resonance/types/enriched-cda.ts +112 -0
  113. package/src/services/README.md +56 -0
  114. package/src/services/llama.ts +59 -0
  115. package/src/services/llamauv.ts +56 -0
  116. package/src/services/olmo3.ts +58 -0
  117. package/src/services/phi.ts +52 -0
  118. package/src/types/artifact.ts +12 -0
  119. package/src/utils/EnvironmentVerifier.ts +67 -0
  120. package/src/utils/Logger.ts +21 -0
  121. package/src/utils/ServiceLifecycle.ts +207 -0
  122. package/src/utils/ZombieDefense.ts +244 -0
  123. package/src/utils/validator.ts +264 -0
  124. package/substack/substack-playbook-1.md +95 -0
  125. package/substack/substack-playbook-2.md +78 -0
  126. package/tasks/ui-investigation.md +26 -0
  127. package/test-db +0 -0
  128. package/test-db-shm +0 -0
  129. package/test-db-wal +0 -0
  130. package/tests/canary/verify_pinch_check.ts +44 -0
  131. package/tests/fixtures/ingest_test.md +12 -0
  132. package/tests/fixtures/ingest_test_boxed.md +13 -0
  133. package/tests/fixtures/safety_test.md +45 -0
  134. package/tests/fixtures/safety_test_boxed.md +49 -0
  135. package/tests/fixtures/tagged_output.md +49 -0
  136. package/tests/fixtures/tagged_test.md +49 -0
  137. package/tests/mcp-server-settings.json +8 -0
  138. package/tsconfig.json +46 -0
  139. package/verify-embedder.ts +54 -0
@@ -0,0 +1,75 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "title": "Conceptual Lexicon (CL) Schema",
4
+ "description": "Defines the structure for a Conceptual Lexicon file, which is an array of term and heuristic entries.",
5
+ "type": "array",
6
+ "items": {
7
+ "$ref": "#/definitions/lexiconEntry"
8
+ },
9
+ "definitions": {
10
+ "lexiconEntry": {
11
+ "type": "object",
12
+ "title": "Lexicon Entry",
13
+ "description": "A single entry (term or heuristic) in the Conceptual Lexicon.",
14
+ "properties": {
15
+ "id": {
16
+ "description": "The unique identifier for the entry (e.g., 'term-001', 'OH-040').",
17
+ "type": "string",
18
+ "pattern": "^[a-zA-Z0-9_-]+$"
19
+ },
20
+ "title": {
21
+ "description": "The human-readable title of the term or heuristic.",
22
+ "type": "string"
23
+ },
24
+ "description": {
25
+ "description": "The full definition of the entry. Can be a simple string or a structured object for complex definitions.",
26
+ "type": ["string", "object"]
27
+ },
28
+ "type": {
29
+ "description": "The type of the entry, e.g., 'term', 'operational-heuristic'.",
30
+ "type": "string"
31
+ },
32
+ "category": {
33
+ "description": "The category of the entry, e.g., 'Core Concept', 'Operational Heuristic'.",
34
+ "type": "string"
35
+ },
36
+ "tags": {
37
+ "description": "An optional array of tags for establishing relationships (e.g., '[Implements: COG-5]').",
38
+ "type": "array",
39
+ "items": {
40
+ "type": "string"
41
+ }
42
+ },
43
+ "source": {
44
+ "description": "The origin of the entry, typically 'cl'.",
45
+ "type": "string"
46
+ },
47
+ "external_refs": {
48
+ "description": "A list of external grounding resources (URLs, Citations, Code).",
49
+ "type": "array",
50
+ "items": {
51
+ "type": "object",
52
+ "properties": {
53
+ "label": {
54
+ "description": "Human-readable link text (e.g., 'Wikipedia', 'Source Code').",
55
+ "type": "string"
56
+ },
57
+ "url": {
58
+ "description": "The fully qualified URI.",
59
+ "type": "string",
60
+ "format": "uri"
61
+ },
62
+ "type": {
63
+ "description": "The nature of the reference.",
64
+ "type": "string",
65
+ "enum": ["source", "citation", "implementation", "example"]
66
+ }
67
+ },
68
+ "required": ["label", "url", "type"]
69
+ }
70
+ }
71
+ },
72
+ "required": ["id", "title", "description", "type"]
73
+ }
74
+ }
75
+ }
@@ -0,0 +1,39 @@
1
+ # Debrief: Project Alpha (Dummy)
2
+
3
+ **Date:** 2025-12-12
4
+ **Status:** Success
5
+
6
+
7
+ <!-- bento-id: bento-f4290ac6 -->
8
+ <!-- type: section -->
9
+ ## 1. Overview
10
+ We successfully deployed the Alpha version. It was great.
11
+
12
+
13
+ <!-- bento-id: bento-4dd57b85 -->
14
+ <!-- type: section -->
15
+ ## 2. Technical Details
16
+ We used a lot of code.
17
+
18
+ ### The Algorithm
19
+ Here is the core loop:
20
+
21
+ ```typescript
22
+ function coreLoop() {
23
+ console.log("Don't split me!");
24
+ // This is a comment inside code
25
+ }
26
+ ```
27
+
28
+
29
+ <!-- bento-id: bento-8cc779e9 -->
30
+ <!-- type: section -->
31
+ ## 3. Lessons Learned
32
+ - Don't eat yellow snow.
33
+ - **Testing:** Is important.
34
+
35
+
36
+ <!-- bento-id: bento-e4cea28f -->
37
+ <!-- type: section -->
38
+ ## 4. Future Work
39
+ We need to do more stuff.
@@ -0,0 +1,27 @@
1
+ # Debrief: Project Alpha (Dummy)
2
+
3
+ **Date:** 2025-12-12
4
+ **Status:** Success
5
+
6
+ ## 1. Overview
7
+ We successfully deployed the Alpha version. It was great.
8
+
9
+ ## 2. Technical Details
10
+ We used a lot of code.
11
+
12
+ ### The Algorithm
13
+ Here is the core loop:
14
+
15
+ ```typescript
16
+ function coreLoop() {
17
+ console.log("Don't split me!");
18
+ // This is a comment inside code
19
+ }
20
+ ```
21
+
22
+ ## 3. Lessons Learned
23
+ - Don't eat yellow snow.
24
+ - **Testing:** Is important.
25
+
26
+ ## 4. Future Work
27
+ We need to do more stuff.
@@ -0,0 +1,50 @@
1
+ # Design Scratchpad: AntiGravity Emulation
2
+
3
+ **Goal**: Adopt the visual language of Google's AntiGravity agent.
4
+
5
+ ## 1. Core Philosophy
6
+ - **High Contrast Dark Mode**: Deep backgrounds (`#202124` or darker), crisp white text (`#ffffff`), and subtle borders.
7
+ - **Typography**: Clean, geometric sans-serif (Google Sans / Inter).
8
+ - **Fluidity**: Responsive sizing for typography and spacing.
9
+ - **"The Card"**: Distinct surfaces with subtle borders and rounded corners.
10
+
11
+ ## 2. Color Palette (Dark Mode)
12
+
13
+ | Semantic Name | Value | Description |
14
+ | :--- | :--- | :--- |
15
+ | `--primary` | `#202124` | Main Background (Deep Gray) |
16
+ | `--secondary` | `#ffffff` | Primary Text (Crisp White) |
17
+ | `--accent` | `#303134` | Secondary Background / Sidebar |
18
+ | `--surface-1` | `#202124` | App Background |
19
+ | `--surface-2` | `#303134` | Card / Panel Background |
20
+ | `--surface-hover` | `#3c4043` | Hover State |
21
+ | `--border-base` | `#5f6368` | Subtle Borders |
22
+ | `--link` | `#8ab4f8` | Google Blue (Links) |
23
+ | `--link-visited` | `#c58af9` | Google Violet (Visited) |
24
+
25
+ ## 3. Typography
26
+
27
+ - **Font Family**: `Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif`
28
+ - **Scale**:
29
+ - `xs`: `0.75rem`
30
+ - `sm`: `0.875rem`
31
+ - `base`: `1rem`
32
+ - `lg`: `1.125rem`
33
+ - `xl`: `1.25rem`
34
+ - `2xl`: `1.5rem`
35
+
36
+ ## 4. Spacing (Fluid)
37
+
38
+ Using Open Props `size-fluid-*` where appropriate, but anchoring on a 4px grid.
39
+
40
+ - `--spacing-1`: `4px`
41
+ - `--spacing-2`: `8px`
42
+ - `--spacing-3`: `12px`
43
+ - `--spacing-4`: `16px` (Standard Gap)
44
+ - `--spacing-5`: `20px`
45
+ - `--spacing-6`: `24px`
46
+
47
+ ## 5. Implementation Strategy
48
+ 1. **Update `theme.css`**: Replace existing color variables with the new palette.
49
+ 2. **Refine Typography**: Ensure `Inter` is loaded or falls back gracefully.
50
+ 3. **Component Audit**: Check Sidebars, Cards, and TOC for contrast issues.
@@ -0,0 +1,20 @@
1
+ # Scratchpad: Sidebar Scrolling Experiments
2
+
3
+ ## Problem Space
4
+ The sidebars in `v3.html` are not scrolling.
5
+ Structure: `aside` (Grid Cell) -> `div` (Container) -> `nav` (List).
6
+ Current State: Both `aside` and `nav` might have overflow properties, or `nav` is not constrained.
7
+
8
+ ## Hypothesis 1: Nested Scroll Conflict
9
+ If `aside` allows scrolling, the inner `div` grows to fit the content.
10
+ If `div` grows, `nav` grows.
11
+ Result: `nav` never overflows its container, so its scrollbar never triggers. The `aside` scrollbar *should* trigger, but might be hidden or behaving oddly due to `app-shell` grid constraints.
12
+
13
+ ## Experiment 1: Lock Parent, Scroll Child
14
+ **Goal**: Make `nav` the *only* scrollable element.
15
+ 1. `aside`: `overflow: hidden` (Don't scroll).
16
+ 2. `div.docs-directory`: `h-full flex flex-col overflow: hidden` (Constrain height, don't scroll).
17
+ 3. `nav`: `flex-1 overflow-y-auto min-h-0` (Fill space, scroll if needed, allow shrinking).
18
+
19
+ ## Log
20
+ - [ ] Experiment 1
@@ -0,0 +1,23 @@
1
+ # Scratchpad: TOC Disappearance Investigation
2
+
3
+ ## Problem
4
+ The Table of Contents (TOC) for `hi-fi-css.md` (and potentially others) has become invisible or empty after changing the font size from `text-sm` to `text-base`.
5
+
6
+ ## Context
7
+ - **Previous Change**: Increased vertical padding (`py-1` -> `py-1.5`) and font size (`text-sm` -> `text-base`).
8
+ - **User Report**: "now there is nothing visible in the outline".
9
+ - **Previous Issue**: `Alpine Warning: x-for ":key" is undefined` (Fixed by ensuring unique IDs).
10
+
11
+ ## Hypotheses
12
+ 1. **CSS Overflow/Visibility**: The larger text might be pushing content out of a constrained container, or `truncate` is hiding everything if the width is too small.
13
+ 2. **Alpine.js Crash**: The previous fix for IDs might have introduced a syntax error or logic error that crashes the Alpine component, preventing rendering.
14
+ 3. **Data Binding**: The `toc` array might be empty despite the ID fix.
15
+
16
+ ## Experiment Plan (Variable Reduction)
17
+ 1. **Revert Font Size**: Temporarily revert `text-base` to `text-sm` to see if visibility returns. (Isolates CSS vs Logic).
18
+ 2. **Console Logging**: Add aggressive logging in `doc-viewer.js` to confirm `toc` array population and Alpine lifecycle hooks.
19
+ 3. **Inspect DOM**: Use browser tool (if stable) or `view_file` to check if the `<a>` tags exist in the DOM but are hidden.
20
+
21
+ ## Action Log
22
+ - [ ] Create Scratchpad.
23
+ - [ ] Propose Plan.
@@ -0,0 +1,28 @@
1
+ # Scratchpad: TOC Generation Debugging
2
+
3
+ ## Problem
4
+ The Table of Contents (TOC) for `public/docs/hi-fi-css.md` only shows the document title. Other headings are missing.
5
+
6
+ ## Target File
7
+ `public/docs/hi-fi-css.md`
8
+
9
+ ## Hypotheses
10
+ 1. **Header Levels**: The file might use `h1` or `h4+` which are not captured by `querySelectorAll('h2, h3')`.
11
+ 2. **Parsing Timing**: `generateToC` might run before the DOM is fully updated (though `$nextTick` should prevent this).
12
+ 3. **Marked Config**: The custom renderer might be malformed.
13
+
14
+ ## Investigation Log
15
+ - [x] Inspect `hi-fi-css.md` content.
16
+ - **Finding**: File uses `h1`, `h2`, `h3`, and **many `h4`** headers.
17
+ - [x] Inspect `doc-viewer.js`.
18
+ - **Finding**: `generateToC` only queries `h2, h3`.
19
+ - [x] Inspect rendered DOM in Browser.
20
+ - **Confirmed**: `h4` elements exist but are ignored.
21
+ - [x] Fix: Add `h4` to `querySelectorAll`.
22
+ - **Action**: Updated `doc-viewer.js` to query `h2, h3, h4`.
23
+ - [ ] **Re-Investigation**: User reports TOC still empty.
24
+ - **Hypothesis 1**: `marked` renderer issue with bold tags `**` in headers?
25
+ - **Hypothesis 2**: `generateToC` timing (DOM not ready)?
26
+ - **Action**: Inspect `#main-content` HTML and Alpine `$data.toc`.
27
+ - **Result**: Programmatic test confirmed `h4`s are present (6 count) and `toc` array is populated (39 items).
28
+ - **Conclusion**: The fix works. User might be seeing cached state.
@@ -0,0 +1,7 @@
1
+ # Test Gardener Seed
2
+
3
+ This is a test file to verify the Auto-Tagger agent.
4
+ It discusses **Artificial Intelligence** and **Knowledge Graphs**.
5
+ It also mentions **Neural Networks** and **Semantic Search**.
6
+
7
+ Hopefully the gardener finds this and adds tags.
@@ -0,0 +1,146 @@
1
+ // --- CONFIGURATION ---
2
+ const PORTS = {
3
+ SCOUT: 8082, // Phi-3.5 (Fast Entity Extraction)
4
+ ARCHITECT: 8083, // Llama-3 (Strict Logic/JSON)
5
+ AUDITOR: 8084, // Olmo-3 (Deep Thinking)
6
+ };
7
+
8
+ interface AuditResult {
9
+ passed: boolean;
10
+ verdict: string;
11
+ thought_trace: string;
12
+ }
13
+
14
+ export class EnlightenedTriad {
15
+ /**
16
+ * THE SCOUT (Phi-3.5)
17
+ * "The Bouncer"
18
+ * Task: Fast, cheap filtering.
19
+ */
20
+ async scout(context: string, extractionTask: string): Promise<string> {
21
+ return this.callAgent(PORTS.SCOUT, [
22
+ {
23
+ role: "system",
24
+ content:
25
+ "You are a precise data extractor. Return only the requested data. No filler.",
26
+ },
27
+ {
28
+ role: "user",
29
+ content: `Context: ${context}\n\nTask: ${extractionTask}`,
30
+ },
31
+ ]);
32
+ }
33
+
34
+ /**
35
+ * THE ARCHITECT (Llama-3 + Accountant Vector)
36
+ * "The Builder"
37
+ * Task: Structure raw text into strict JSON.
38
+ */
39
+ async architect(unstructuredData: string): Promise<unknown> {
40
+ const response = await this.callAgent(PORTS.ARCHITECT, [
41
+ { role: "system", content: "Output JSON only." },
42
+ {
43
+ role: "user",
44
+ content: `Convert to Causal Graph JSON: ${unstructuredData}`,
45
+ },
46
+ ]);
47
+
48
+ try {
49
+ // Strip markdown code blocks if present
50
+ const cleanJson = response
51
+ .replace(/```json/g, "")
52
+ .replace(/```/g, "")
53
+ .trim();
54
+ return JSON.parse(cleanJson);
55
+ } catch (_e) {
56
+ console.error("❌ Architect JSON Error. Raw output:", response);
57
+ return null;
58
+ }
59
+ }
60
+
61
+ /**
62
+ * THE AUDITOR (Olmo-3-Think)
63
+ * "The QA Department"
64
+ * Task: Think for 2 minutes, then vote Yes/No.
65
+ */
66
+ async audit(claim: string): Promise<AuditResult> {
67
+ // High temp for creative debugging/thinking
68
+ const rawOutput = await this.callAgent(
69
+ PORTS.AUDITOR,
70
+ [
71
+ {
72
+ role: "user",
73
+ content: `Analyze the validity of this logical claim. \n\nClaim: "${claim}"\n\nShow your thinking process wrapped in <think> tags like this: <think> ... </think>, then end with 'VERDICT: PASS' or 'VERDICT: FAIL'.`,
74
+ },
75
+ ],
76
+ { temperature: 0.6, max_tokens: 2048 },
77
+ );
78
+
79
+ // --- THE PARSER ---
80
+ // Olmo uses <think> tags. We split the "Raj" monologue from the Answer.
81
+ let thoughtTrace = "";
82
+ let finalAnswer = "";
83
+
84
+ const thinkMatch = rawOutput.match(/<think>([\s\S]*?)<\/think>/);
85
+
86
+ if (thinkMatch?.[1]) {
87
+ // case 1: structured output
88
+ thoughtTrace = thinkMatch[1].trim();
89
+ finalAnswer = rawOutput.replace(thinkMatch[0], "").trim();
90
+ } else if (rawOutput.includes("VERDICT:")) {
91
+ // case 2: implicit separation (fallback)
92
+ const parts = rawOutput.split("VERDICT:");
93
+ thoughtTrace = parts[0]?.trim() ?? "";
94
+ // Reconstruct the verdict part
95
+ finalAnswer = `VERDICT:${parts.slice(1).join("VERDICT:")}`.trim();
96
+ } else {
97
+ // case 3: total failure to structure
98
+ thoughtTrace = rawOutput;
99
+ finalAnswer = "VERDICT: FAIL (Parse Error)";
100
+ }
101
+
102
+ const passed = finalAnswer.includes("VERDICT: PASS");
103
+
104
+ return {
105
+ passed,
106
+ verdict: finalAnswer, // The short answer for UI
107
+ thought_trace: thoughtTrace, // The monologue for DB/Audit
108
+ };
109
+ }
110
+
111
+ // --- UTILS (Bun Native Fetch) ---
112
+ private async callAgent(
113
+ port: number,
114
+ messages: { role: string; content: string }[],
115
+ options: { temperature?: number; max_tokens?: number } = {},
116
+ ): Promise<string> {
117
+ try {
118
+ const response = await fetch(
119
+ `http://127.0.0.1:${port}/v1/chat/completions`,
120
+ {
121
+ method: "POST",
122
+ headers: { "Content-Type": "application/json" },
123
+ body: JSON.stringify({
124
+ messages,
125
+ temperature: options.temperature || 0.1,
126
+ n_predict: options.max_tokens || 512,
127
+ }),
128
+ },
129
+ );
130
+
131
+ if (!response.ok) {
132
+ throw new Error(
133
+ `HTTP Error ${response.status}: ${response.statusText}`,
134
+ );
135
+ }
136
+
137
+ const data = (await response.json()) as {
138
+ choices: { message: { content: string } }[];
139
+ };
140
+ return data.choices?.[0]?.message?.content || "";
141
+ } catch (_error) {
142
+ console.error(`❌ Agent at Port ${port} is offline/unreachable.`);
143
+ return "AGENT_OFFLINE";
144
+ }
145
+ }
146
+ }
@@ -0,0 +1,137 @@
1
+ import { type Subprocess, spawn } from "bun";
2
+ import { EnlightenedTriad } from "./EnlightenedTriad"; // Re-using your existing interface
3
+
4
+ // --- CONFIGURATION ---
5
+ const BASE_DIR = `${import.meta.dir}/../experiments/enlightenment`; // Adjust relative to src/
6
+ const BIN_PATH = `${BASE_DIR}/llama.cpp/build/bin/llama-server`;
7
+ const VECTORS_DIR = `${BASE_DIR}/vectors`;
8
+
9
+ const AGENTS = {
10
+ SCOUT: {
11
+ port: 8082,
12
+ model: `${VECTORS_DIR}/Phi-3.5-mini-instruct-Q4_K_M.gguf`,
13
+ ctx: 4096,
14
+ vector: null,
15
+ },
16
+ ARCHITECT: {
17
+ port: 8083,
18
+ model: `${VECTORS_DIR}/Meta-Llama-3-8B-Instruct-Q4_K_M.gguf`,
19
+ ctx: 8192,
20
+ vector: `${VECTORS_DIR}/enlightenment_vector_v2.gguf`,
21
+ scale: "-0.3",
22
+ },
23
+ AUDITOR: {
24
+ port: 8084,
25
+ model: `${VECTORS_DIR}/Olmo-3-7B-Think-Q4_K_M.gguf`,
26
+ ctx: 8192,
27
+ vector: null,
28
+ },
29
+ };
30
+
31
+ let currentProcess: Subprocess | null = null;
32
+
33
+ // --- LIFECYCLE MANAGER ---
34
+ async function bootAgent(role: keyof typeof AGENTS) {
35
+ if (currentProcess) {
36
+ console.log("♻️ Freeing VRAM (Stopping previous agent)...");
37
+ currentProcess.kill();
38
+ await new Promise((r) => setTimeout(r, 1000)); // Cool down
39
+ }
40
+
41
+ const config = AGENTS[role];
42
+ console.log(`🚀 Booting ${role} on Port ${config.port}...`);
43
+
44
+ const args = [
45
+ BIN_PATH,
46
+ "-m",
47
+ config.model,
48
+ "--port",
49
+ config.port.toString(),
50
+ "--ctx-size",
51
+ config.ctx.toString(),
52
+ "--n-gpu-layers",
53
+ "99", // Metal
54
+ "--log-disable", // Keep console clean
55
+ ];
56
+
57
+ if (config.vector) {
58
+ args.push("--control-vector-scaled", `${config.vector}:${config.scale}`);
59
+ }
60
+
61
+ // Spawn via Bun
62
+ currentProcess = spawn(args, {
63
+ stdout: "ignore", // Silence server logs
64
+ stderr: "ignore",
65
+ });
66
+
67
+ // Wait for Health Check
68
+ process.stdout.write(" Waiting for neural activity...");
69
+ for (let i = 0; i < 30; i++) {
70
+ try {
71
+ const res = await fetch(`http://127.0.0.1:${config.port}/health`);
72
+ if (res.ok) {
73
+ console.log(" Online! 🟢");
74
+ return;
75
+ }
76
+ } catch (_e) {}
77
+ await new Promise((r) => setTimeout(r, 500));
78
+ process.stdout.write(".");
79
+ }
80
+ throw new Error(`${role} failed to start.`);
81
+ }
82
+
83
+ async function shutdown() {
84
+ if (currentProcess) {
85
+ console.log("\n🛑 Shutting down final agent...");
86
+ currentProcess.kill();
87
+ }
88
+ }
89
+
90
+ // --- THE DEMO FLOW ---
91
+ async function runOptimizedPipeline() {
92
+ const triad = new EnlightenedTriad();
93
+
94
+ try {
95
+ console.log("⚡️ SYSTEM ONLINE: Engaging OPTIMIZED Intelligence...\n");
96
+ const rawLog =
97
+ "2025-12-19 14:02:11 [CRITICAL] Connection refused at 192.168.1.5 (DB_SHARD_04). Latency 4005ms.";
98
+
99
+ // --- STEP 1: SCOUT ---
100
+ await bootAgent("SCOUT");
101
+ console.log("\n--- 🕵️ SCOUT TASK ---");
102
+ const scoutResult = await triad.scout(
103
+ rawLog,
104
+ "Extract IP and Error Message. No notes.",
105
+ );
106
+ console.log(`>> Output: ${scoutResult}`);
107
+
108
+ // --- STEP 2: ARCHITECT ---
109
+ await bootAgent("ARCHITECT");
110
+ console.log("\n--- 📐 ARCHITECT TASK ---");
111
+ const architectResult = await triad.architect(scoutResult);
112
+ console.log(`>> Output:`, JSON.stringify(architectResult, null, 2));
113
+
114
+ // --- STEP 3: AUDITOR ---
115
+ await bootAgent("AUDITOR");
116
+ console.log("\n--- 🧠 AUDITOR TASK ---");
117
+ const claim = `The error 'Connection refused' caused the high latency.`;
118
+ const auditResult = await triad.audit(claim);
119
+
120
+ console.log(
121
+ `\n📝 THOUGHT TRACE:\n${auditResult.thought_trace.substring(0, 300)}...`,
122
+ );
123
+ console.log(`\n⚖️ VERDICT: ${auditResult.passed ? "✅ PASS" : "❌ FAIL"}`);
124
+ } catch (error) {
125
+ console.error("\n💥 Pipeline Error:", error);
126
+ } finally {
127
+ await shutdown();
128
+ }
129
+ }
130
+
131
+ // Handle Ctrl+C
132
+ process.on("SIGINT", async () => {
133
+ await shutdown();
134
+ process.exit(0);
135
+ });
136
+
137
+ runOptimizedPipeline();