tribunal-kit 4.4.3 → 4.4.5

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.
package/README.md CHANGED
@@ -1,242 +1,113 @@
1
- <div align="center">
2
- <picture>
3
- <img src="./docs/tribunalkit_no_bg.png" alt="TribunalKit — Code Without Hallucinations" width="480">
4
- </picture>
5
-
6
- <br><br>
7
-
8
- [![NPM](https://img.shields.io/npm/v/tribunal-kit?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/tribunal-kit)
9
- [![License](https://img.shields.io/badge/License-MIT-8b5cf6?style=for-the-badge)](LICENSE)
10
- [![Version](https://img.shields.io/badge/Version-4.3.1_Supreme_Court-black?style=for-the-badge)](CHANGELOG.md)
11
- </div>
12
-
13
-
14
- <br><br>
15
-
16
- > 🚨 **AI GENERATES CODE. TRIBUNAL ENSURES IT WORKS.**
17
- > A plug-in `.agent/` intelligence payload that upgrades your IDE with **41 specialist agents**, **31 slash commands**, **91 hardened skills**, and a **16-reviewer Tribunal pipeline** — zero hallucinations, zero configuration.
18
-
19
- ---
20
-
21
- <br>
22
-
23
- ## ▓▒░ INITIATION SEQUENCE
24
-
25
- Drop Tribunal into any project. Global or local.
26
-
27
- ```bash
28
- # Pull the intelligence payload into your project
29
- npx tribunal-kit init
30
- ```
31
- *(Installs the `.agent/` architecture directly. No bloat. Pure capability.)*
32
-
33
- <details>
34
- <summary><b>📺 Quick Demo — What happens when you run it</b></summary>
35
- <br>
36
-
37
- ```
38
- $ npx tribunal-kit init
39
-
40
- ████████╗██████╗ ██╗██████╗ ██╗ ██╗███╗ ██╗ █████╗ ██╗
41
- ╚══██╔══╝██╔══██╗██║██╔══██╗██║ ██║████╗ ██║██╔══██╗██║
42
- ██║ ██████╔╝██║██████╔╝██║ ██║██╔██╗ ██║███████║██║
43
- ██║ ██╔══██╗██║██╔══██╗██║ ██║██║╚██╗██║██╔══██║██║
44
- ██║ ██║ ██║██║██████╔╝╚██████╔╝██║ ╚████║██║ ██║███████╗
45
- ╚═╝ ╚═╝ ╚═╝╚═╝╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝
46
-
47
- ╔══════════════════════════════════════════════════════════════╗
48
- ║ Anti-Hallucination Agent System ║
49
- ╚══════════════════════════════════════════════════════════════╝
50
-
51
- Installed .agent/
52
-
53
- ╔══════════════════════════════════════════════════════════════╗
54
- ║ 🤖 Agents 41 installed ║
55
- ║ ⚡ Workflows 32 installed ║
56
- ║ 🧠 Skills 91 installed ║
57
- ║ 🔧 Scripts 27 installed ║
58
- ╚══════════════════════════════════════════════════════════════╝
59
-
60
- 700+ files installed. 16 parallel Tribunal reviewers armed.
61
-
62
- $ npx tribunal-kit status
63
-
64
- Installed at .agent/
65
- 🤖 agents 40 files
66
- ⚡ workflows 31 files
67
- 🧠 skills 90 files
68
- 🔧 scripts 27 files
69
- ```
70
-
71
- > 💡 **Lighter install?** Use `npx tribunal-kit init --minimal` for just 13 core agents + 15 essential skills.
72
-
73
- </details>
74
-
75
- > ✅ **IDE Auto-Detection:** `init` automatically generates bridge files for every major AI coding IDE:
76
- >
77
- > | IDE | Bridge File Generated |
78
- > | :--- | :--- |
79
- > | **Cursor** | `.cursorrules` |
80
- > | **Windsurf** | `.windsurfrules` |
81
- > | **Gemini / Antigravity** | `.gemini/settings.json` + `.gemini/GEMINI.md` |
82
- > | **GitHub Copilot** | `.github/copilot-instructions.md` |
83
- > | **Claude** | `.claude/CLAUDE.md` |
84
- >
85
- > Bridge files are never overwritten on re-init — your customizations are safe.
86
-
87
- **Prerequisites:** Node.js 18
88
-
89
- > 💡 **Shorthand alias:** You can use `tk` instead of `tribunal-kit` for all commands (e.g., `tk init`, `tk status`).
90
-
91
- <br>
92
-
93
- ## ▓▒░ THE PIPELINE // HOW IT WORKS
94
-
95
- **Code generation is solved. Code correctness is the frontier.** We enforce a strict **Evidence-Based Closeout**.
96
-
97
- ```diff
98
- - AI Generates -> Commits to Disk -> You Find Bugs Later
99
- + AI Generates -> Parallel Tribunal Review -> Human Gate -> Commits to Disk
100
- ```
101
-
102
- ### 🎯 Auto-Routing Intelligence
103
- No manual tagging required. The system self-organizes.
104
-
105
- <p>
106
- <kbd>User</kbd> "Add JWT authentication" <br>
107
- <kbd>System</kbd> <code>🤖 Applying @security-auditor + @backend-specialist...</code> <br><br>
108
-
109
- <kbd>User</kbd> "Fix the dark mode button" <br>
110
- <kbd>System</kbd> <code>🤖 Applying @ui-ux-pro-max + @frontend-specialist...</code> <br><br>
111
-
112
- <kbd>User</kbd> "/swarm build a API" <br>
113
- <kbd>System</kbd> <code>🤖 supervisor-agent → Dispatching 3 Workers...</code>
114
- </p>
115
-
116
- <br>
117
-
118
- ## ▓▒░ THE SUPREME COURT (v4.0)
119
-
120
- *(New in v4)* The Tribunal Kit now features persistent memory so the AI **never makes the same mistake twice** and automatically learns your team's coding style.
121
-
122
- **1. The Case Law Engine (Never repeat mistakes)**
123
- If an agent makes a mistake, you can record it as a legal precedent. Before writing any future code, the `precedence-reviewer` checks this database locally to forcefully block the AI from repeating that mistake.
124
- - `npx tribunal-kit case add` *(Record an AI hallucination)*
125
- - `npx tribunal-kit case search "query"` *(Search your precedents)*
126
-
127
- **2. Skill Evolution Forge (Auto-learns your style)**
128
- You no longer need to write manual rules. The system reads your Git commits, strips out the noise to save tokens, and automatically extracts your project's unique architectural patterns to teach the AI.
129
- - `npx tribunal-kit learn` *(Run a learning digest on staged files)*
130
- - `npx tribunal-kit hook` *(Automate learning every time you `git push`)*
131
-
132
- <br>
133
-
134
- ## ▓▒░ CAPABILITY MATRIX
135
-
136
- | System Asset | Count | Operational Scope |
137
- | :--- | :---: | :--- |
138
- | 🤖 **Agents** | `40` | Specialist personas — 16 reviewers + 24 domain specialists |
139
- | 🧠 **Skills** | `90` | Domain modules (Edge Computing, Red Team Tactics, GSAP, Framer Motion, TypeScript Advanced) |
140
- | ⚡ **Workflows** | `31` | Slash command procedures including `/swarm`, `/tribunal-full`, `/ui-ux-pro-max` |
141
- | 🛠️ **Scripts** | `25` | CI/CD, linting, payload dispatching, security scanning, case law, skill evolution |
142
-
143
-
144
- <br>
145
-
146
- ## ▓▒░ COMMAND TERMINAL
147
-
148
- Expand the accordions to view the operational commands at your disposal.
149
-
150
- <details open>
151
- <summary><b>🔥 CORE EXECUTION</b></summary>
152
- <br>
153
-
154
- | Command | Action |
155
- | :--- | :--- |
156
- | <code>/generate</code> | Trigger full Tribunal: Generate → Audit → Approve. |
157
- | <code>/create</code> | Scaffold major features or apps, routed by App Builder. |
158
- | <code>/enhance</code> | Safely extend existing structures without regression. |
159
- | <code>/deploy</code> | Force the 3-gate production release sequence. |
160
-
161
- </details>
162
-
163
- <details>
164
- <summary><b>⚖️ THE TRIBUNAL GAUNTLET (REVIEWERS)</b></summary>
165
- <br>
166
- Unleash parallel reviewers on existing code.
167
-
168
- | Command | Action |
169
- | :--- | :--- |
170
- | <code>/review</code> | Audit code for silent degradation and logic holes. |
171
- | <code>/tribunal-full</code> | Unleash **ALL 16** reviewers simultaneously. Maximum scrutiny. |
172
- | <code>/tribunal-backend</code> | Summons <code>[ Logic + Security + Dependency + Types ]</code> |
173
- | <code>/tribunal-frontend</code> | Summons <code>[ Logic + Security + Frontend + Types ]</code> |
174
- | <code>/tribunal-database</code> | Summons <code>[ Logic + Security + SQL ]</code> |
175
- | <code>/tribunal-mobile</code> | Summons <code>[ Logic + Security + Mobile ]</code> |
176
-
177
- </details>
178
-
179
- <details>
180
- <summary><b>🧠 SWARM & ORCHESTRATION</b></summary>
181
- <br>
182
-
183
- | Command | Action |
184
- | :--- | :--- |
185
- | <code>/swarm</code> | Supervisor breaks goal → sends to isolated workers → synthesizes. |
186
- | <code>/orchestrate</code> | Manual multi-agent sync for complex integrations. |
187
- | <code>/plan</code> | Architectural mapping before a single line is written. |
188
- | <code>/ui-ux-pro-max</code>| Triggers peak aesthetic frontend design. |
189
-
190
- </details>
191
-
192
- <details>
193
- <summary><b>⚖️ SUPREME COURT / MEMORY</b></summary>
194
- <br>
195
-
196
- | Command | Action |
197
- | :--- | :--- |
198
- | <code>npx tribunal-kit case add</code> | Record an AI hallucination to ban it forever. |
199
- | <code>npx tribunal-kit case search</code> | Search your local database of banned code. |
200
- | <code>npx tribunal-kit learn</code> | Auto-extract project idioms from your git diffs. |
201
- | <code>npx tribunal-kit hook</code> | Install a git hook to auto-learn the moment you push. |
202
-
203
- </details>
204
-
205
- <details>
206
- <summary><b>🔧 TROUBLESHOOTING & OPS</b></summary>
207
- <br>
208
-
209
- | Command | Action |
210
- | :--- | :--- |
211
- | <code>/debug</code> | Systematic root-cause investigation. |
212
- | <code>/preview</code> | Local development server control. |
213
- | <code>/status</code> | View Tribunal session status. |
214
-
215
- </details>
216
-
217
- <br>
218
-
219
- ## ▓▒░ POST-INSTALL TELEMETRY
220
-
221
- After initialization, utility scripts unlock local ops:
222
-
223
- ```bash
224
- # 01. Pre-commit audit
225
- node .agent/scripts/checklist.js .
226
-
227
- # 02. Pre-deploy full suite verification
228
- node .agent/scripts/verify_all.js
229
-
230
- # 03. Start local development environment
231
- node .agent/scripts/auto_preview.js start
232
- ```
233
-
234
- <br>
235
-
236
- <div align="center">
237
- <br>
238
- <img src="https://img.shields.io/badge/Status-Active_&_Secured-00e5ff?style=for-the-badge" alt="Status" />
239
- <br><br>
240
- <i>"Never guess database column names. Error handling on every async function. Evidence-based closeouts. Welcome to the Tribunal."</i><br>
241
- <sub><b>MIT Licensed</b> • Hand-forged for high-performance agentic engineering.</sub>
242
- </div>
1
+ <div align="center">
2
+ <picture>
3
+ <img src="./docs/tribunalkit_no_bg.png" alt="TribunalKit — Code Without Hallucinations" width="480">
4
+ </picture>
5
+
6
+ <br>
7
+
8
+ <h1>TRIBUNAL KIT</h1>
9
+ <p><b>Anti-Hallucination Agent Architecture • Long-Running Autonomy • Pipeline Scrutiny</b></p>
10
+
11
+ [![NPM](https://img.shields.io/npm/v/tribunal-kit?style=for-the-badge&logo=npm&logoColor=white)](https://www.npmjs.com/package/tribunal-kit)
12
+ [![License](https://img.shields.io/badge/License-MIT-8b5cf6?style=for-the-badge)](LICENSE)
13
+ [![Version](https://img.shields.io/badge/Version-4.4.4_Marathon-black?style=for-the-badge)](CHANGELOG.md)
14
+ </div>
15
+
16
+ ---
17
+
18
+ > [!IMPORTANT]
19
+ > **AI GENERATES CODE. TRIBUNAL ENSURES IT WORKS.**
20
+ > A zero-bloat `.agent/` intelligence payload that upgrades your IDE with **41 specialist agents**, **31 workflows**, and a **16-reviewer Tribunal pipeline**. Zero hallucinations. Absolute execution certainty.
21
+
22
+ ## ▓▒░ QUICK START
23
+
24
+ Drop Tribunal into any existing project to instantly weaponize your IDE.
25
+
26
+ ```bash
27
+ # Pull the intelligence payload into your project directory
28
+ npx tribunal-kit init
29
+ ```
30
+
31
+ > [!NOTE]
32
+ > `init` automatically generates bridge rules for **Cursor**, **Windsurf**, **Gemini**, **Copilot**, and **Claude**. No configuration required.
33
+
34
+ <br>
35
+
36
+ ## ▓▒░ THE MARATHON HARNESS (v4.4.4)
37
+
38
+ The v4.4 update introduces the **Marathon Harness**—an engine designed to keep autonomous agents on track during long-running, multi-session projects without looping or losing context.
39
+
40
+ ### ⛓️ Directed Acyclic Graph (DAG) Support
41
+ Cascade failures are obsolete. Features can now be declared with dependencies (`--deps=1,2`). If a database schema task fails, the API route task is automatically flagged as **Deadlocked** and bypassed until the root issue is resolved.
42
+
43
+ ### 🧠 Failure Context & Attempt Tracking
44
+ Agents no longer blindly retry failed approaches. When a feature fails, the reason and attempt count are permanently logged into the state matrix. The next agent to attempt the feature receives the exact failure history to course-correct immediately.
45
+
46
+ ### 🔮 Memory Distillation
47
+ Context windows dilute over time. The new `distill` command allows agents to forge crucial architectural decisions into a permanent `distilled_context.md` memory matrix, bridging the amnesia gap between long work sessions.
48
+
49
+ <br>
50
+
51
+ ## ▓▒░ THE PIPELINE // EVIDENCE-BASED CLOSEOUT
52
+
53
+ Code generation is solved. **Code correctness is the frontier.**
54
+
55
+ ```mermaid
56
+ graph TD
57
+ A[User Request] -->|Intent Parsed| B(Context Broker)
58
+ B --> C{Inner-Loop Validator}
59
+
60
+ C -->|Syntax & Secrets Check| D[Parallel Tribunal Review]
61
+ C -.->|Failed| E[Maker Auto-Correction]
62
+ E -.-> C
63
+
64
+ D -->|16 Domain Reviewers| F[Human Gate]
65
+ F -->|Approved| G((Committed to Disk))
66
+
67
+ classDef default fill:#1a1a1a,stroke:#333,stroke-width:2px,color:#fff;
68
+ classDef critical fill:#ff1637,stroke:#fff,stroke-width:2px,color:#fff;
69
+ classDef success fill:#00e5ff,stroke:#fff,stroke-width:2px,color:#1a1a1a;
70
+
71
+ class D critical;
72
+ class G success;
73
+ ```
74
+
75
+ <br>
76
+
77
+ ## ▓▒░ THE SUPREME COURT (CASE LAW ENGINE)
78
+
79
+ The Tribunal Kit features persistent memory. The AI **never makes the same mistake twice** and auto-learns your engineering culture.
80
+
81
+ > [!WARNING]
82
+ > **1. The Case Law Engine**
83
+ > Record mistakes as legal precedent. The `precedence-reviewer` checks this database locally to forcefully block the AI from repeating banned patterns.
84
+ > - `npx tribunal-kit case add` *(Record an AI hallucination)*
85
+
86
+ > [!TIP]
87
+ > **2. Skill Evolution Forge**
88
+ > Stop writing manual rules. The system reads your Git diffs, strips token bloat, and auto-extracts your project's architectural idioms.
89
+ > - `npx tribunal-kit learn` *(Digest staged files)*
90
+
91
+ <br>
92
+
93
+ ## ▓▒░ COMMAND ARSENAL
94
+
95
+ | Slash Command | Operational Scope |
96
+ | :--- | :--- |
97
+ | `/generate` | Full Tribunal sequence: Generate → Audit → Human Gate. |
98
+ | `/create` | Scaffold major applications via App Builder routing. |
99
+ | `/enhance` | Safely extend existing codebases with zero regression. |
100
+ | `/swarm` | Fan-out orchestrator. Dispatch isolated workers, synthesize output. |
101
+ | `/tribunal-full` | Unleash **ALL 16** domain reviewers simultaneously for maximum scrutiny. |
102
+ | `/debug` | Systematic 4-phase root-cause investigation. No guessing. |
103
+ | `/ui-ux-pro-max` | Advanced visual aesthetic engine. No generic AI slop. |
104
+
105
+ <br>
106
+
107
+ <div align="center">
108
+ <br>
109
+ <img src="https://img.shields.io/badge/Status-Active_&_Secured-00e5ff?style=for-the-badge" alt="Status" />
110
+ <br><br>
111
+ <i>"Never guess database column names. Error handling on every async function. Evidence-based closeouts. Welcome to the Tribunal."</i><br>
112
+ <sub><b>MIT Licensed</b> Engineered for maximum autonomy and precision.</sub>
113
+ </div>
@@ -1117,5 +1117,5 @@ runWithUpdateCheck(command, flags);
1117
1117
 
1118
1118
  // -- Exports (for testing) -- do not remove
1119
1119
  if (require.main !== module) {
1120
- module.exports = { parseArgs, compareSemver, copyDir, countDir, isSelfInstall, CORE_AGENTS, CORE_SKILLS, generateIDEBridges };
1121
- }
1120
+ module.exports = { parseArgs, compareSemver, copyDir, countDir, isSelfInstall, CORE_AGENTS, CORE_SKILLS, generateIDEBridges, cmdMarathon };
1121
+ }
package/bin/wrapper.js ADDED
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Tribunal-Kit Core Wrapper
4
+ *
5
+ * This script routes commands to the ultra-fast Rust binary if available and supported.
6
+ * For legacy commands (or if the binary isn't available/compiled yet), it gracefully
7
+ * falls back to the original JavaScript implementation.
8
+ */
9
+
10
+ const fs = require('fs');
11
+ const path = require('path');
12
+ const { spawnSync } = require('child_process');
13
+ const os = require('os');
14
+
15
+ // Commands that have been fully ported to Rust so far
16
+ const RUST_COMMANDS = new Set(['init', 'validate', 'status']);
17
+
18
+ // Determine the path to the compiled Rust binary
19
+ // In a full production release, this checks optionalDependencies in node_modules
20
+ // For development, it checks the local target/release folder
21
+ function getBinaryPath() {
22
+ const isWindows = os.platform() === 'win32';
23
+ const ext = isWindows ? '.exe' : '';
24
+
25
+ // First, check bin/ directory (postinstall downloaded binary)
26
+ const binPath = path.resolve(__dirname, `tribunal-core${ext}`);
27
+ if (fs.existsSync(binPath)) {
28
+ return binPath;
29
+ }
30
+
31
+ // Second, try to find the binary compiled from crates/core/Cargo.toml
32
+ const devPath = path.resolve(__dirname, '..', 'target', 'release', `tribunal-core${ext}`);
33
+ if (fs.existsSync(devPath)) {
34
+ return devPath;
35
+ }
36
+
37
+ // Third, try target/debug (if they ran `cargo build` instead of `--release`)
38
+ const debugPath = path.resolve(__dirname, '..', 'target', 'debug', `tribunal-core${ext}`);
39
+ if (fs.existsSync(debugPath)) {
40
+ return debugPath;
41
+ }
42
+
43
+ // Production resolution (from optionalDependencies) would go here
44
+ return null;
45
+ }
46
+
47
+ function runRustBinary(binPath, args) {
48
+ const result = spawnSync(binPath, args, {
49
+ stdio: 'inherit',
50
+ env: process.env
51
+ });
52
+
53
+ if (result.error) {
54
+ console.error(`\x1b[91m✖ Failed to execute Rust engine:\x1b[0m ${result.error.message}`);
55
+ process.exit(1);
56
+ }
57
+
58
+ process.exit(result.status || 0);
59
+ }
60
+
61
+ function runLegacyFallback() {
62
+ // Graceful fallback to the original JS implementation
63
+ // We do this by modifying process.argv so it appears normal to the legacy script
64
+ require('./tribunal-kit.js');
65
+ }
66
+
67
+ function main() {
68
+ // Skip 'node' and 'wrapper.js'
69
+ const args = process.argv.slice(2);
70
+
71
+ // Extract the command (the first non-flag argument)
72
+ const command = args.find(a => !a.startsWith('-'));
73
+
74
+ if (command && RUST_COMMANDS.has(command)) {
75
+ const binPath = getBinaryPath();
76
+
77
+ if (binPath) {
78
+ // For the init command, Rust needs to know where the .agent template folder is.
79
+ if (command === 'init') {
80
+ const sourceDir = path.resolve(__dirname, '..', '.agent');
81
+ args.push('--source-dir', sourceDir);
82
+ }
83
+
84
+ // Route to Rust engine
85
+ // console.log('\x1b[90m⚡ Executing via Rust Core Engine\x1b[0m');
86
+ runRustBinary(binPath, args);
87
+ return;
88
+ } else {
89
+ // Warn if Rust command was requested but binary is missing
90
+ console.warn('\x1b[93m⚠ Rust binary not found in target/. Falling back to JS engine.\x1b[0m');
91
+ }
92
+ }
93
+
94
+ // Fall back to JS logic for un-ported commands (e.g. `learn`, `case`, `marathon`)
95
+ runLegacyFallback();
96
+ }
97
+
98
+ main();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tribunal-kit",
3
- "version": "4.4.3",
3
+ "version": "4.4.5",
4
4
  "description": "Anti-Hallucination AI Agent Kit — 40 specialist agents, 32 slash commands, 16 parallel Tribunal reviewers, Performance Swarm engine, Supreme Court case law pipeline, and long-running agent harness.",
5
5
  "keywords": [
6
6
  "ai",
@@ -42,8 +42,8 @@
42
42
  },
43
43
  "license": "MIT",
44
44
  "bin": {
45
- "tribunal-kit": "bin/tribunal-kit.js",
46
- "tk": "bin/tribunal-kit.js"
45
+ "tribunal-kit": "bin/wrapper.js",
46
+ "tk": "bin/wrapper.js"
47
47
  },
48
48
  "files": [
49
49
  "bin/",
@@ -65,6 +65,7 @@
65
65
  "changelog:preview": "node scripts/changelog.js --preview",
66
66
  "sync": "node scripts/sync-version.js",
67
67
  "validate-payload": "node scripts/validate-payload.js",
68
+ "postinstall": "node scripts/postinstall.js",
68
69
  "build": "echo 'No build step required for this project'"
69
70
  },
70
71
  "devDependencies": {
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * postinstall.js — Binary Download Script
4
+ *
5
+ * After `npm install`, this script downloads the pre-compiled Rust binary
6
+ * for the user's platform from the latest GitHub Release.
7
+ *
8
+ * If the download fails (offline, unsupported platform, etc.), it's a soft failure.
9
+ * The wrapper.js will detect the missing binary and fall back to the JS engine.
10
+ */
11
+
12
+ const fs = require('fs');
13
+ const path = require('path');
14
+ const https = require('https');
15
+ const os = require('os');
16
+ const crypto = require('crypto');
17
+
18
+ const PKG = require(path.resolve(__dirname, '..', 'package.json'));
19
+ const VERSION = PKG.version;
20
+
21
+ const BINARY_DIR = path.resolve(__dirname, '..', 'bin');
22
+ const REPO = 'Harmitx7/tribunal-kit';
23
+
24
+ function getPlatformBinary() {
25
+ const platform = os.platform();
26
+ const arch = os.arch();
27
+
28
+ const map = {
29
+ 'win32-x64': 'tribunal-core-win-x64.exe',
30
+ 'win32-arm64': 'tribunal-core-win-arm64.exe',
31
+ 'darwin-x64': 'tribunal-core-darwin-x64',
32
+ 'darwin-arm64': 'tribunal-core-darwin-arm64',
33
+ 'linux-x64': 'tribunal-core-linux-x64',
34
+ 'linux-arm64': 'tribunal-core-linux-arm64',
35
+ };
36
+
37
+ const key = `${platform}-${arch}`;
38
+ return map[key] || null;
39
+ }
40
+
41
+ function getLocalBinaryPath() {
42
+ const isWindows = os.platform() === 'win32';
43
+ return path.join(BINARY_DIR, `tribunal-core${isWindows ? '.exe' : ''}`);
44
+ }
45
+
46
+ function download(url) {
47
+ return new Promise((resolve, reject) => {
48
+ const request = https.get(url, { headers: { 'User-Agent': `tribunal-kit/${VERSION}` } }, (res) => {
49
+ // Handle redirects (GitHub sends 302 to the actual download URL)
50
+ if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
51
+ download(res.headers.location).then(resolve).catch(reject);
52
+ return;
53
+ }
54
+
55
+ if (res.statusCode !== 200) {
56
+ reject(new Error(`HTTP ${res.statusCode}`));
57
+ return;
58
+ }
59
+
60
+ const chunks = [];
61
+ res.on('data', (chunk) => chunks.push(chunk));
62
+ res.on('end', () => resolve(Buffer.concat(chunks)));
63
+ res.on('error', reject);
64
+ });
65
+
66
+ request.on('error', reject);
67
+ request.setTimeout(30000, () => { request.destroy(); reject(new Error('Timeout')); });
68
+ });
69
+ }
70
+
71
+ async function main() {
72
+ const binaryName = getPlatformBinary();
73
+
74
+ if (!binaryName) {
75
+ console.log(`[tribunal-kit] No pre-built binary for ${os.platform()}-${os.arch()}. Using JS fallback.`);
76
+ return;
77
+ }
78
+
79
+ const localPath = getLocalBinaryPath();
80
+
81
+ // Skip if binary already exists (e.g. dev environment with cargo build)
82
+ if (fs.existsSync(localPath)) {
83
+ return;
84
+ }
85
+
86
+ const url = `https://github.com/${REPO}/releases/download/v${VERSION}/${binaryName}`;
87
+ const checksumsUrl = `https://github.com/${REPO}/releases/download/v${VERSION}/checksums.txt`;
88
+
89
+ console.log(`[tribunal-kit] Downloading native binary for ${os.platform()}-${os.arch()}...`);
90
+
91
+ try {
92
+ // 1. Download checksums file
93
+ const checksumsData = await download(checksumsUrl);
94
+ const checksumsText = checksumsData.toString('utf-8');
95
+
96
+ // 2. Extract expected hash
97
+ const hashMatch = checksumsText.split('\n').find(line => line.includes(binaryName));
98
+ if (!hashMatch) {
99
+ throw new Error(`Checksum for ${binaryName} not found in checksums.txt`);
100
+ }
101
+ const expectedHash = hashMatch.split(' ')[0].trim();
102
+
103
+ // 3. Download binary
104
+ const data = await download(url);
105
+
106
+ // 4. Verify checksum
107
+ const actualHash = crypto.createHash('sha256').update(data).digest('hex');
108
+ if (actualHash !== expectedHash) {
109
+ throw new Error(`Checksum mismatch! Expected ${expectedHash}, got ${actualHash}. Potential tamper detected.`);
110
+ }
111
+
112
+ // 5. Write to disk
113
+ fs.writeFileSync(localPath, data);
114
+
115
+ // Make executable on Unix
116
+ if (os.platform() !== 'win32') {
117
+ fs.chmodSync(localPath, 0o755);
118
+ }
119
+
120
+ console.log(`[tribunal-kit] Native binary installed and verified successfully.`);
121
+ } catch (e) {
122
+ // Soft failure — wrapper.js will use the JS engine
123
+ console.log(`[tribunal-kit] Binary download skipped (${e.message}). Using JS fallback.`);
124
+ }
125
+ }
126
+
127
+ main();