@vigylx/slm 0.0.0-stage → 0.3.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.
package/README.md CHANGED
@@ -1,3 +1,258 @@
1
- # Temporary Holding Version
1
+ # Vigyl
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Control your server from Telegram, in plain English.**
4
+
5
+ Send your bot "run the test suite" and it runs. Send "deploy to staging" and it
6
+ deploys. If a build fails, Vigyl reads the error, tries to fix it, and runs it
7
+ again — and asks you first before anything destructive.
8
+
9
+ ![Vigyl healing a failing test suite from Telegram](https://raw.githubusercontent.com/ankithm-113/vigyl/main/docs/demo.gif)
10
+
11
+ *A real run: the test fails, Vigyl patches `sum.js`, the re-run passes — six seconds, unedited.*
12
+
13
+ ```
14
+ you ▸ run the build
15
+ bot ▸ 🧠 Working out what to run...
16
+ ▸ ▶ Running (attempt 1/4): npm run build
17
+ ▸ ✗ Failed (exit 1) — build_error: src/app.ts(12,5): error TS2304
18
+ ▸ 🔧 Asking the model for a fix...
19
+ ▸ ✍ Patched src/app.ts: added the missing import
20
+ ▸ ▶ Running (attempt 2/4): npm run build
21
+ ▸ ✅ Done — succeeded on attempt 2 after self-healing.
22
+ ```
23
+
24
+ ---
25
+
26
+ ## Status
27
+
28
+ **v0.1.0 — early beta.** Built and tested, but young. Read
29
+ [What is not proven yet](#what-is-not-proven-yet) before pointing it at
30
+ anything you care about.
31
+
32
+ ---
33
+
34
+ ## Install
35
+
36
+ ```bash
37
+ npm install -g @vigylx/cli
38
+ ```
39
+
40
+ Or the one-liner:
41
+
42
+ ```bash
43
+ curl -fsSL https://raw.githubusercontent.com/ankithm-113/vigyl/main/scripts/install.sh | bash
44
+ ```
45
+
46
+ Windows (PowerShell):
47
+
48
+ ```powershell
49
+ irm https://raw.githubusercontent.com/ankithm-113/vigyl/main/scripts/install.ps1 | iex
50
+ ```
51
+
52
+ Requires **Node 20 or newer**. Works on Linux, macOS and Windows.
53
+
54
+ ## Set up (about five minutes)
55
+
56
+ **1. Make a Telegram bot.** Message [@BotFather](https://t.me/BotFather), send
57
+ `/newbot`, follow the prompts, copy the token it gives you.
58
+
59
+ **2. Get an OpenAI API key** from
60
+ [platform.openai.com/api-keys](https://platform.openai.com/api-keys). Vigyl uses
61
+ `gpt-4o-mini` by default; a typical command costs well under a cent.
62
+ (Anthropic is also supported — see [Choosing a model](#choosing-a-model).)
63
+
64
+ **3. Run the wizard** in the project you want to control:
65
+
66
+ ```bash
67
+ cd ~/my-project
68
+ vigyl init
69
+ ```
70
+
71
+ It validates both credentials against the live services before writing
72
+ anything, then waits for you to message your bot so it can learn which chat to
73
+ trust.
74
+
75
+ **4. Start it:**
76
+
77
+ ```bash
78
+ vigyl start
79
+ ```
80
+
81
+ Now message your bot.
82
+
83
+ ### No terminal? (CI, containers, agents)
84
+
85
+ ```bash
86
+ export OPENAI_API_KEY=sk-...
87
+ export TELEGRAM_BOT_TOKEN=123456:ABC...
88
+ vigyl init --non-interactive
89
+ ```
90
+
91
+ ## Commands
92
+
93
+ ### Terminal
94
+
95
+ | Command | What it does |
96
+ |---|---|
97
+ | `vigyl init` | Setup wizard with live credential checks |
98
+ | `vigyl doctor` | Check everything, including live credentials |
99
+ | `vigyl start` | Start the daemon in the background |
100
+ | `vigyl start -f` | Run in the foreground |
101
+ | `vigyl stop` | Stop the daemon |
102
+ | `vigyl status` | Is it running? |
103
+ | `vigyl logs -n 100` | Recent daemon log lines |
104
+ | `vigyl logs -f` | Follow the log until Ctrl+C |
105
+
106
+ `vigyl doctor` is the fastest way to find out why something is not working:
107
+
108
+ ```
109
+ Vigyl doctor
110
+
111
+ ✓ Node version Node 24.13.1
112
+ ✓ Shell Commands will run through bash
113
+ ✓ PTY support node-pty is loadable
114
+ ✓ Config file Loaded and valid
115
+ ✓ Workspace writable /home/you/my-project
116
+ ✓ Authorized chats 1 chat(s) authorized
117
+ ✓ OpenAI key Key valid; gpt-4o-mini is available.
118
+ ✓ Telegram token Connected to @your_bot.
119
+ ✓ Command parsing Parsed a test request into: tail -n 20 logs/app.log
120
+
121
+ Everything checks out. Vigyl is ready.
122
+ ```
123
+
124
+ ### Telegram
125
+
126
+ | Command | What it does |
127
+ |---|---|
128
+ | *(plain English)* | Run a command |
129
+ | `/status` | Daemon status |
130
+ | `/history` | Recent commands |
131
+ | `/repeat` | Run the last command again |
132
+ | `/logs` | Full output of your last command |
133
+ | `/logs <id>` | Full output of a specific command |
134
+ | `/monitor on\|off\|status` | Health alerts for this chat |
135
+ | `/help` | Command reference |
136
+
137
+ ## How it works
138
+
139
+ ```
140
+ Telegram ──▶ bot.ts ──▶ daemon.ts ──▶ supervisor.ts ──▶ llm.ts (OpenAI / Anthropic)
141
+ │ (what should run?)
142
+ ├──▶ hitl.ts approval gate
143
+ ├──▶ security.ts path sandbox + command policy
144
+ └──▶ self-heal.ts ──▶ executor.ts ──▶ your shell
145
+ │ │
146
+ │ └──▶ monitor.ts (classify failure)
147
+ └──▶ supervisor.ts (propose a patch)
148
+ ```
149
+
150
+ 1. Your message goes to the model (gpt-4o-mini by default), which turns it into
151
+ one shell command, returned as schema-validated structured output.
152
+ 2. The command is checked against the security policy and the approval rules.
153
+ 3. Anything destructive comes back to you with Approve / Deny buttons.
154
+ 4. Otherwise it runs in a real PTY, confined to your workspace.
155
+ 5. On failure, the output is classified and — when it is the kind of failure a
156
+ file edit can fix — the model is shown the failing file plus the local files
157
+ it imports (up to 3 hops) and proposes a patch. The patch may only target a
158
+ file it was shown in full, and is validated against the sandbox before it is
159
+ written. Then the command runs again, up to 3 retries.
160
+
161
+ ## Safety
162
+
163
+ Vigyl runs real commands on your server, so it is worth knowing exactly what
164
+ holds it in. The short version:
165
+
166
+ - **Path sandbox.** Every path is canonicalised (symlinks resolved) and checked
167
+ for containment inside your workspace. This is a real boundary.
168
+ - **Approval gate.** Destructive actions need a button press. The rules are
169
+ yours, and they run independently of the model's own judgement.
170
+ - **Patches are validated before they are written.** A proposed fix that points
171
+ outside the workspace is rejected and logged, and the original file is backed
172
+ up before any overwrite.
173
+ - **The command blocklist is a speed bump, not a boundary.** It catches
174
+ accidents. What actually contains a hostile command is the workspace
175
+ confinement, running as a non-root user, and the approval gate.
176
+
177
+ Full detail, including the threat model and what Vigyl does *not* protect
178
+ against: **[docs/SECURITY.md](docs/SECURITY.md)**.
179
+
180
+ ## Configuration
181
+
182
+ `vigyl init` writes `vigyl.config.json`. Everything has a sensible default;
183
+ full reference in **[docs/CONFIGURATION.md](docs/CONFIGURATION.md)**.
184
+
185
+ ```jsonc
186
+ {
187
+ "workspace_root": "/home/you/my-project",
188
+ "telegram": { "bot_token": "…", "allowed_chat_ids": [12345678] },
189
+ "provider": "openai",
190
+ "openai": { "api_key": "…", "model": "gpt-4o-mini" },
191
+ "hitl": {
192
+ "require_for": ["production", "env", "delete", "migrate", "push"],
193
+ "timeout_seconds": 300
194
+ },
195
+ "self_heal": { "enabled": true, "max_retries": 3, "context_lines": 80 },
196
+ "monitor": { "enabled": true, "interval_seconds": 300, "disk_percent": 85 }
197
+ }
198
+ ```
199
+
200
+ **This file holds two live credentials.** `vigyl init` writes it `0600` and adds
201
+ it to `.gitignore`.
202
+
203
+ ### Choosing a model
204
+
205
+ OpenAI is the default. To use Anthropic instead, set `ANTHROPIC_API_KEY` and
206
+ leave `OPENAI_API_KEY` unset (Vigyl picks whichever key it finds, preferring
207
+ OpenAI), or force it with `VIGYL_PROVIDER=anthropic`. `VIGYL_MODEL` overrides the
208
+ model for whichever provider is active. Details in
209
+ [docs/CONFIGURATION.md](docs/CONFIGURATION.md#choosing-a-provider).
210
+
211
+ ## What is not proven yet
212
+
213
+ Being straight with you, because this is v0.1.0 and it runs commands on your
214
+ server:
215
+
216
+ - **Live testing so far is one developer's sandbox.** The full Telegram →
217
+ model → command → self-heal loop has been run end to end against
218
+ `gpt-4o-mini`: it healed a TypeScript error, a failing test and a bug two
219
+ imports deep, refused to patch a missing dependency, and held a production
220
+ deploy for approval. That is a handful of scenarios, not real-world mileage.
221
+ - **Anthropic is supported but has never been run against a live key.** It
222
+ shares the provider interface and has unit tests; only OpenAI has been live.
223
+ - **Self-heal edits one file per attempt**, and only files under 60 KB that it
224
+ was shown in full. Bugs that need coordinated edits across files will stop
225
+ after a few attempts rather than be fixed.
226
+ - **pwsh and POSIX shell paths are written but lightly exercised.** Development
227
+ was on Windows with cmd.exe.
228
+
229
+ Known limitations: one workspace per daemon, Telegram only, and no persistent
230
+ conversation memory beyond the last few turns.
231
+
232
+ ## Troubleshooting
233
+
234
+ Start with `vigyl doctor`. Common problems and fixes:
235
+ **[docs/TROUBLESHOOTING.md](docs/TROUBLESHOOTING.md)**.
236
+
237
+ ## Development
238
+
239
+ ```bash
240
+ git clone https://github.com/ankithm-113/vigyl && cd vigyl
241
+ npm install
242
+ npm run build
243
+ npm test
244
+ ```
245
+
246
+ Monorepo: `packages/daemon` is the library, `packages/cli` owns the `vigyl`
247
+ binary. Current build status and design decisions live in
248
+ [PROGRESS.md](PROGRESS.md).
249
+
250
+ ## Licence
251
+
252
+ **AGPL-3.0-only** from v0.1.1 onwards. Copyright (c) 2026 Ankith M.
253
+
254
+ You may use, modify and self-host it freely. If you run a modified version as a
255
+ network service, the AGPL requires you to publish your changes.
256
+
257
+ v0.1.0 on npm was published under MIT, and that release stays MIT — a licence
258
+ cannot be revoked retroactively.
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Build failures with known labels, for benchmarking the local model.
3
+ *
4
+ * Two kinds of case, and the split is the point:
5
+ *
6
+ * `rules` cases are ones the daemon's regex rules already name. They are here
7
+ * to prove the fast path stays correct, not to exercise the model — the model
8
+ * never sees them in the real loop.
9
+ *
10
+ * `model` cases are ones the rules return 'unknown' for. **These are the only
11
+ * cases that matter.** A benchmark that measured accuracy over obvious errors
12
+ * would report a flattering number that says nothing, because in production
13
+ * those never reach the model at all.
14
+ *
15
+ * Every log here is real output shape: npm, tsc, pytest, docker, cargo, go,
16
+ * gradle and friends, including the noise before the error.
17
+ */
18
+ export interface BenchCase {
19
+ readonly name: string;
20
+ readonly expect: 'syntax_error' | 'dependency_missing' | 'config_error' | 'permission_error' | 'network_error' | 'build_error' | 'test_failure' | 'resource_exhausted' | 'runtime_error' | 'unknown';
21
+ readonly reach: 'rules' | 'model';
22
+ readonly log: string;
23
+ }
24
+ export declare const CORPUS: readonly BenchCase[];
25
+ export declare const MODEL_CASES: BenchCase[];
26
+ export declare const RULE_CASES: BenchCase[];
27
+ //# sourceMappingURL=corpus.d.ts.map
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.RULE_CASES = exports.MODEL_CASES = exports.CORPUS = void 0;
4
+ const NL = String.fromCharCode(10);
5
+ const lines = (...parts) => parts.join(NL);
6
+ exports.CORPUS = [
7
+ // ── Cases the rules already answer ───────────────────────────────────────
8
+ {
9
+ name: 'npm missing module',
10
+ expect: 'dependency_missing',
11
+ reach: 'rules',
12
+ log: lines('> app@1.0.0 build', '> node build.js', '', 'node:internal/modules/cjs/loader:1228', ' throw err;', ' ^', "Error: Cannot find module 'chalk'", 'Require stack:', '- /srv/app/build.js'),
13
+ },
14
+ {
15
+ name: 'tsc type error',
16
+ expect: 'build_error',
17
+ reach: 'rules',
18
+ log: lines('> tsc -b', '', "src/server.ts(42,18): error TS2345: Argument of type 'string' is not assignable to parameter of type 'number'.", 'Found 1 error.'),
19
+ },
20
+ {
21
+ name: 'permission denied writing a log',
22
+ expect: 'permission_error',
23
+ reach: 'rules',
24
+ log: lines('Starting worker...', "Error: EACCES: permission denied, open '/var/log/app/worker.log'", ' at Object.openSync (node:fs:603:3)'),
25
+ },
26
+ {
27
+ name: 'database connection refused',
28
+ expect: 'network_error',
29
+ reach: 'rules',
30
+ log: lines('Running migrations...', 'Error: connect ECONNREFUSED 127.0.0.1:5432', ' at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1595:16)'),
31
+ },
32
+ {
33
+ name: 'javascript syntax error',
34
+ expect: 'syntax_error',
35
+ reach: 'rules',
36
+ log: lines('/srv/app/src/routes.js:18', ' const handler = (req, res => {', ' ^', '', 'SyntaxError: Unexpected token =>'),
37
+ },
38
+ // ── Cases the rules cannot name: the real benchmark ──────────────────────
39
+ {
40
+ name: 'pytest assertion',
41
+ expect: 'test_failure',
42
+ reach: 'rules',
43
+ log: lines('============================= test session starts ==============================', 'platform linux -- Python 3.11.4, pytest-7.4.0', 'collected 23 items', '', 'tests/test_pricing.py .................F..... [100%]', '', '=================================== FAILURES ===================================', '____________________________ test_discount_applies _____________________________', '', ' def test_discount_applies():', ' cart = Cart(items=[Item(price=100)])', '> assert cart.total() == 90', 'E assert 100 == 90', 'E + where 100 = <Cart>.total()', '', 'tests/test_pricing.py:31: AssertionError'),
44
+ },
45
+ {
46
+ // The rules call this syntax_error, which is fair: it is a parse error in
47
+ // a Dockerfile. Labelled to match rather than argued with.
48
+ name: 'docker build, dockerfile parse error',
49
+ expect: 'syntax_error',
50
+ reach: 'rules',
51
+ log: lines('#1 [internal] load build definition from Dockerfile', '#1 transferring dockerfile: 512B done', '#1 DONE 0.0s', '', 'failed to solve: dockerfile parse error on line 14: COPY requires at least two arguments'),
52
+ },
53
+ {
54
+ name: 'go vet, unused variable',
55
+ expect: 'build_error',
56
+ reach: 'model',
57
+ log: lines('go: downloading github.com/lib/pq v1.10.9', './handlers/user.go:27:2: declared and not used: ctx', 'make: *** [Makefile:12: build] Error 2'),
58
+ },
59
+ {
60
+ // Day 4 settled this: the cause is configuration (wrong JDK), and the
61
+ // rules now have a wrong-runtime signal that says so.
62
+ name: 'gradle, wrong java version configured',
63
+ expect: 'config_error',
64
+ reach: 'rules',
65
+ log: lines('> Configure project :app', '', 'FAILURE: Build failed with an exception.', '', '* What went wrong:', 'A problem occurred evaluating project :app.', '> Failed to apply plugin class AppPlugin.', ' > Android Gradle plugin requires Java 17 to run. You are currently using Java 11.'),
66
+ },
67
+ {
68
+ name: 'cargo, borrow checker',
69
+ expect: 'build_error',
70
+ reach: 'model',
71
+ log: lines(' Compiling vigyl-core v0.1.0', 'error[E0502]: cannot borrow `buffer` as mutable because it is also borrowed as immutable', ' --> src/stream.rs:44:9', ' |', '42 | let first = &buffer[0];', ' | ------ immutable borrow occurs here', '44 | buffer.push(9);', ' | ^^^^^^^^^^^^^ mutable borrow occurs here', '', 'error: could not compile `vigyl-core` due to previous error'),
72
+ },
73
+ {
74
+ name: 'jest snapshot mismatch',
75
+ expect: 'test_failure',
76
+ reach: 'rules',
77
+ log: lines(' FAIL src/components/Badge.test.tsx', ' ● Badge › renders the count', '', ' expect(received).toMatchSnapshot()', '', ' Snapshot name: `Badge renders the count 1`', '', ' - Snapshot - 1', ' + Received + 1', '', ' - <span class="badge">3</span>', ' + <span class="badge">4</span>', '', 'Snapshots: 1 failed, 11 passed, 12 total'),
78
+ },
79
+ {
80
+ name: 'env var missing, phrased as a plain exit',
81
+ expect: 'config_error',
82
+ reach: 'model',
83
+ log: lines('booting api...', 'FATAL: STRIPE_SECRET must be set before the server can start', 'process exited with code 1'),
84
+ },
85
+ {
86
+ name: 'python import of a module that is installed but broken',
87
+ expect: 'dependency_missing',
88
+ reach: 'model',
89
+ log: lines('Traceback (most recent call last):', ' File "/srv/app/main.py", line 3, in <module>', ' import numpy', ' File "/usr/lib/python3/numpy/__init__.py", line 144, in <module>', ' from . import core', 'ImportError: libopenblas.so.0: cannot open shared object file'),
90
+ },
91
+ {
92
+ name: 'webpack, loader not configured for a file type',
93
+ expect: 'config_error',
94
+ reach: 'model',
95
+ log: lines('assets by status 1.2 MiB [cached] 1 asset', '', 'ERROR in ./src/styles/main.scss 1:0', 'Module parse failed: Unexpected character "@" (1:0)', 'You may need an appropriate loader to handle this file type.', '> @use "sass:math";'),
96
+ },
97
+ {
98
+ name: 'flaky integration test that timed out',
99
+ expect: 'test_failure',
100
+ reach: 'model',
101
+ log: lines(' api integration', ' ✓ creates a user (241ms)', ' 1) streams events', '', ' 1 passing (2s)', ' 1 failing', '', ' 1) api integration streams events:', ' Error: Timeout of 5000ms exceeded. For async tests, ensure done() is called.'),
102
+ },
103
+ {
104
+ name: 'terraform, argument that does not exist',
105
+ expect: 'config_error',
106
+ reach: 'model',
107
+ log: lines('Initializing provider plugins...', '', 'Error: Unsupported argument', '', ' on main.tf line 22, in resource "aws_s3_bucket" "assets":', ' 22: acl_policy = "private"', '', 'An argument named "acl_policy" is not expected here.'),
108
+ },
109
+ {
110
+ name: 'postgres database does not exist',
111
+ expect: 'config_error',
112
+ reach: 'model',
113
+ log: lines('Running alembic upgrade head...', 'sqlalchemy.exc.OperationalError: (psycopg2.OperationalError)', 'FATAL: database "app_production" does not exist', '', '(Background on this error at: https://sqlalche.me/e/20/e3q8)'),
114
+ },
115
+ {
116
+ name: 'rust test panic',
117
+ expect: 'test_failure',
118
+ reach: 'model',
119
+ log: lines('running 14 tests', 'test parser::tests::reads_header ... ok', "thread 'tax::tests::applies_rate' panicked at src/tax.rs:88:9:", 'left == right', ' left: 110', ' right: 100', 'note: run with `RUST_BACKTRACE=1` to display a backtrace'),
120
+ },
121
+ {
122
+ name: 'java heap exhausted',
123
+ expect: 'resource_exhausted',
124
+ reach: 'model',
125
+ log: lines('Compiling 412 source files...', 'java.lang.OutOfMemoryError: Java heap space', '\tat java.base/java.util.Arrays.copyOf(Arrays.java:3745)', '\tat com.sun.tools.javac.main.Main.compile(Main.java:folder)'),
126
+ },
127
+ {
128
+ name: 'disk full during a build',
129
+ expect: 'resource_exhausted',
130
+ reach: 'model',
131
+ log: lines('Copying artefacts...', 'tar: write error: No space left on device', 'make: *** [Makefile:30: package] Error 2'),
132
+ },
133
+ ];
134
+ exports.MODEL_CASES = exports.CORPUS.filter((c) => c.reach === 'model');
135
+ exports.RULE_CASES = exports.CORPUS.filter((c) => c.reach === 'rules');
136
+ //# sourceMappingURL=corpus.js.map
@@ -0,0 +1,22 @@
1
+ interface CaseResult {
2
+ readonly name: string;
3
+ readonly expected: string;
4
+ readonly got: string;
5
+ readonly correct: boolean;
6
+ readonly confidence: number;
7
+ readonly source: string;
8
+ readonly latencyMs: number;
9
+ readonly summary: string;
10
+ }
11
+ export interface ModelReport {
12
+ readonly model: string;
13
+ readonly sizeBytes: number;
14
+ readonly loadMs: number;
15
+ readonly results: readonly CaseResult[];
16
+ readonly accuracy: number;
17
+ readonly medianLatencyMs: number;
18
+ readonly p90LatencyMs: number;
19
+ readonly meanLatencyMs: number;
20
+ }
21
+ export {};
22
+ //# sourceMappingURL=run.d.ts.map
@@ -0,0 +1,136 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ /**
4
+ * Live benchmark: how good is a local model at naming a build failure the
5
+ * regex rules could not, and how long does it take on this CPU?
6
+ *
7
+ * Run with a downloaded model:
8
+ * node packages/slm/dist/bench/run.js llama3.2-1b-q4 phi3-mini-4k-q4
9
+ *
10
+ * Not a test. Needs real models and real time, so it lives outside the suite.
11
+ */
12
+ const node_perf_hooks_1 = require("node:perf_hooks");
13
+ const classifier_1 = require("../classifier");
14
+ const downloader_1 = require("../downloader");
15
+ const corpus_1 = require("./corpus");
16
+ const NL = String.fromCharCode(10);
17
+ function percentile(values, fraction) {
18
+ if (values.length === 0)
19
+ return 0;
20
+ const sorted = [...values].sort((a, b) => a - b);
21
+ const index = Math.min(sorted.length - 1, Math.floor(fraction * sorted.length));
22
+ return sorted[index] ?? 0;
23
+ }
24
+ async function benchmarkModel(key, cases) {
25
+ const spec = (0, downloader_1.resolveModel)(key);
26
+ const path = await (0, downloader_1.getModelPath)(key);
27
+ if (!path)
28
+ throw new Error(`${key} is not downloaded. Run: vigyl slm download --model ${key}`);
29
+ process.stdout.write(`${NL}Loading ${spec.label}...${NL}`);
30
+ const classifier = new classifier_1.SLMClassifier({ modelPath: path, timeoutMs: 120_000 });
31
+ const loadStart = node_perf_hooks_1.performance.now();
32
+ await classifier.init();
33
+ const loadMs = Math.round(node_perf_hooks_1.performance.now() - loadStart);
34
+ process.stdout.write(` loaded in ${(loadMs / 1000).toFixed(1)}s, context ${classifier.loadedContextSize}${NL}${NL}`);
35
+ const results = [];
36
+ for (const testCase of cases) {
37
+ const started = node_perf_hooks_1.performance.now();
38
+ const result = await classifier.classify(testCase.log);
39
+ const latencyMs = Math.round(node_perf_hooks_1.performance.now() - started);
40
+ const correct = result.errorType === testCase.expect;
41
+ results.push({
42
+ name: testCase.name,
43
+ expected: testCase.expect,
44
+ got: result.errorType,
45
+ correct,
46
+ confidence: result.confidence,
47
+ source: result.source,
48
+ latencyMs,
49
+ summary: result.summary,
50
+ });
51
+ const mark = correct ? 'ok ' : 'MISS';
52
+ const detail = correct ? result.errorType : `${result.errorType} (wanted ${testCase.expect})`;
53
+ process.stdout.write(` ${mark} ${String(latencyMs).padStart(6)}ms ${testCase.name.padEnd(46)} ${detail}${NL}`);
54
+ }
55
+ await classifier.dispose();
56
+ const latencies = results.map((r) => r.latencyMs);
57
+ const correct = results.filter((r) => r.correct).length;
58
+ return {
59
+ model: key,
60
+ sizeBytes: spec.bytes,
61
+ loadMs,
62
+ results,
63
+ accuracy: results.length === 0 ? 0 : correct / results.length,
64
+ medianLatencyMs: percentile(latencies, 0.5),
65
+ p90LatencyMs: percentile(latencies, 0.9),
66
+ meanLatencyMs: Math.round(latencies.reduce((a, b) => a + b, 0) / Math.max(1, latencies.length)),
67
+ };
68
+ }
69
+ /** The fast path, measured on the cases it is supposed to answer. */
70
+ function benchmarkRules() {
71
+ let correct = 0;
72
+ const times = [];
73
+ for (const testCase of corpus_1.RULE_CASES) {
74
+ const started = node_perf_hooks_1.performance.now();
75
+ const result = (0, classifier_1.fastClassify)(testCase.log);
76
+ times.push((node_perf_hooks_1.performance.now() - started) * 1000);
77
+ if (result?.errorType === testCase.expect)
78
+ correct += 1;
79
+ }
80
+ return {
81
+ accuracy: correct / corpus_1.RULE_CASES.length,
82
+ meanMicros: Math.round(times.reduce((a, b) => a + b, 0) / times.length),
83
+ };
84
+ }
85
+ async function main() {
86
+ const requested = process.argv.slice(2);
87
+ const models = requested.length > 0 ? requested : ['llama3.2-1b-q4', 'phi3-mini-4k-q4'];
88
+ process.stdout.write(`Corpus: ${corpus_1.CORPUS.length} cases ` +
89
+ `(${corpus_1.RULE_CASES.length} answered by rules, ${corpus_1.MODEL_CASES.length} needing the model)${NL}`);
90
+ const rules = benchmarkRules();
91
+ process.stdout.write(`${NL}Fast path: ${(rules.accuracy * 100).toFixed(0)}% on its ${corpus_1.RULE_CASES.length} cases, ` +
92
+ `mean ${rules.meanMicros}µs, no model${NL}`);
93
+ const reports = [];
94
+ for (const model of models) {
95
+ try {
96
+ reports.push(await benchmarkModel(model, corpus_1.MODEL_CASES));
97
+ }
98
+ catch (error) {
99
+ process.stdout.write(`${NL}Skipping ${model}: ${error.message}${NL}`);
100
+ }
101
+ }
102
+ process.stdout.write(`${NL}${'='.repeat(78)}${NL}Summary — ${corpus_1.MODEL_CASES.length} cases the rules could not name${NL}${NL}`);
103
+ process.stdout.write(` ${'model'.padEnd(20)} ${'size'.padEnd(8)} ${'load'.padEnd(8)} ` +
104
+ `${'accuracy'.padEnd(10)} ${'median'.padEnd(10)} ${'p90'.padEnd(10)} mean${NL}`);
105
+ for (const report of reports) {
106
+ process.stdout.write(` ${report.model.padEnd(20)} ` +
107
+ `${(report.sizeBytes / 1e9).toFixed(1).padEnd(7)}G ` +
108
+ `${(report.loadMs / 1000).toFixed(1).padEnd(7)}s ` +
109
+ `${((report.accuracy * 100).toFixed(0) + '%').padEnd(10)} ` +
110
+ `${(report.medianLatencyMs + 'ms').padEnd(10)} ` +
111
+ `${(report.p90LatencyMs + 'ms').padEnd(10)} ` +
112
+ `${report.meanLatencyMs}ms${NL}`);
113
+ }
114
+ process.stdout.write(`${NL}Misses:${NL}`);
115
+ for (const report of reports) {
116
+ for (const result of report.results.filter((r) => !r.correct)) {
117
+ process.stdout.write(` ${report.model}: ${result.name}${NL}` +
118
+ ` wanted ${result.expected}, got ${result.got} ` +
119
+ `(confidence ${result.confidence.toFixed(2)}, via ${result.source})${NL}` +
120
+ ` "${result.summary}"${NL}`);
121
+ }
122
+ }
123
+ process.stdout.write(`${NL}${JSON.stringify({ rules, reports: reports.map((r) => ({
124
+ model: r.model,
125
+ loadMs: r.loadMs,
126
+ accuracy: r.accuracy,
127
+ medianLatencyMs: r.medianLatencyMs,
128
+ p90LatencyMs: r.p90LatencyMs,
129
+ meanLatencyMs: r.meanLatencyMs,
130
+ })) })}${NL}`);
131
+ }
132
+ main().catch((error) => {
133
+ process.stderr.write(String(error) + NL);
134
+ process.exit(1);
135
+ });
136
+ //# sourceMappingURL=run.js.map