@sdkurjnk/blackshell 0.1.0 → 0.3.3

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
@@ -15,66 +15,65 @@ threat model, and theory.
15
15
 
16
16
  ## Status
17
17
 
18
- Early **proof of concept (v0.1.0)**. This is an LLVM-free *working skeleton*:
19
- the whole pipeline runs end to end on a toy IR with **dummy passes** (an
20
- accept-all gate and identity L1–L3 noising), so the layer contracts are locked
21
- and real passes can drop in without touching call sites.
18
+ **Working skeleton.** The pipeline runs end to end — real `clang`/`llc` compile a
19
+ source unit to an object file — but the three IP stages (eligibility **gate**,
20
+ **noising** L1–L3, equivalence **harness**) are **dummies** (accept-all gate,
21
+ identity noising), so the layer contracts are locked and real passes drop in
22
+ without touching call sites. Dummy output is correct-but-unprotecting — **do not
23
+ treat it as sealed.**
22
24
 
23
- What is **not** implemented yet (roadmap): the real eligibility gate (§5), real
24
- noising L1–L3 incl. carry-sensitive MBA, and raising the pipeline to LLVM for
25
- native, multi-target output. Dummy passes are correct-but-unprotecting — do not
26
- treat current output as sealed.
25
+ Roadmap: real eligibility gate (§5), real noising L1–L3 incl. carry-sensitive MBA.
27
26
 
28
27
  ## Requirements
29
28
 
30
- - **Node.js ≥ 20** — the CLI front door.
31
- - **Python 3** — the PoC engine runs behind the CLI. (`blackshell --version`
32
- works without it; every other command needs Python on `PATH`.)
29
+ - **Node.js ≥ 20** — the CLI (TS Launcher).
30
+ - **clang + llc on `PATH`** — the C++ engine shells out to them (source → LLVM IR → object), at runtime.
31
+ - **g++ (C++17)** — only to build the engine from a clone. The published npm package ships a
32
+ prebuilt engine for `linux-x64`, `linux-arm64`, `darwin-x64`, `darwin-arm64`, `win32-x64`.
33
33
 
34
- > The internal engine is Python only for the PoC; production moves it behind a
35
- > C-ABI native boundary. See [`docs/interfaces/`](docs/interfaces/).
36
-
37
- ## Install
34
+ ## Build & run (from a clone)
38
35
 
39
36
  ```sh
40
- npm install -g @sdkurjnk/blackshell
37
+ npm install
38
+ npm run build # g++ engine + tsc launcher
39
+ node dist/cli.js --version
40
+ npm test # full test suite
41
41
  ```
42
42
 
43
- Or run from a clone without installing: `node bin/blackshell.js <command>`.
43
+ `npm link` (or a global install) exposes the `blackshell` command; otherwise use
44
+ `node dist/cli.js <command>`.
44
45
 
45
46
  ## Usage
46
47
 
47
- Units are toy IR files (JSON, see [`docs/interfaces/03-ir-model.md`](docs/interfaces/03-ir-model.md)).
48
- Sealing follows a git-style staging model — stage units, then seal the set.
48
+ Units are **source files**. git-style staging — stage units, then seal the set.
49
49
 
50
50
  ```sh
51
- blackshell check <ir-file> # preview: is this region eligible? (gate only)
52
- blackshell add <ir-file> --level L1,L3 # stage a unit for sealing
53
- blackshell list # show staged units and levels
54
- blackshell drop <ir-file> # unstage
55
- blackshell enshell --verify # seal all staged units -> artifacts
56
- blackshell run <ir-file> --input a=40 # (dev) run a unit in the toy interpreter
51
+ blackshell check <source> # preview: is this region eligible? (gate only)
52
+ blackshell add <source> --level L1,L3 # stage a unit (default level: L3)
53
+ blackshell list # show staged units and levels
54
+ blackshell drop <source> # unstage
55
+ blackshell enshell # seal all staged units -> object files
57
56
  ```
58
57
 
59
58
  Example:
60
59
 
61
60
  ```sh
62
- blackshell add src/engine/examples/add2.ir.json --level L1,L3
63
- blackshell enshell --verify --emit-ir out
61
+ blackshell add src/engine/examples/add2.c --level L1,L3
62
+ blackshell enshell
64
63
  ```
65
64
 
66
65
  ## How it works
67
66
 
68
67
  ```
69
- [external] JS CLI ──argv──▶ [internal] engine
70
- bin/ + src/cli/ src/engine/ (Python, PoC)
71
- packaging · version gate → noising (L1–L3) → emit
72
- equivalence harness verifies every pass
68
+ [Launcher] TS / npm argv [Engine] C++ binary
69
+ src/launcher/cli.ts ───────────────▶ src/engine/
70
+ CLI · staging · render token · exit clang → gate → noising → harness → llc → .o
73
71
  ```
74
72
 
75
- The external/internal split and every layer contract (CLI seam, driver, IR
76
- model, pass contract, verification harness) are documented in
77
- [`docs/interfaces/`](docs/interfaces/). Contributing follows GitFlow —
73
+ The Launcher owns the CLI (parsing, staging, rendering); the engine runs the seal
74
+ pipeline per unit and returns a structured token. Layer contracts and the full
75
+ architecture are in [`docs/interfaces/`](docs/interfaces/) and
76
+ [`docs/Architecture.md`](docs/Architecture.md). Contributing follows GitFlow —
78
77
  see [`docs/contributing-gitflow.md`](docs/contributing-gitflow.md).
79
78
 
80
79
  ## License
package/dist/cli.js ADDED
@@ -0,0 +1,236 @@
1
+ #!/usr/bin/env node
2
+ // BlackShell Launcher (TS). Owns the CLI: parsing, the command set, the staging
3
+ // index and message rendering (docs/Architecture.md §5 hybrid). The C++ engine
4
+ // exposes per-unit primitives (check, enshell); the Launcher composes them — e.g.
5
+ // `enshell` seals every staged unit by calling the engine's enshell per unit.
6
+ import { spawnSync } from "node:child_process";
7
+ import { readFileSync, writeFileSync, existsSync, mkdirSync } from "node:fs";
8
+ import { fileURLToPath } from "node:url";
9
+ import { createRequire } from "node:module";
10
+ import { dirname, join } from "node:path";
11
+ const here = (p) => fileURLToPath(new URL(p, import.meta.url));
12
+ const pkg = JSON.parse(readFileSync(here("../package.json"), "utf8"));
13
+ const USAGE = `blackshell <command> [options]
14
+
15
+ check <source> Gate verdict only (dummy: accept-all)
16
+ add <source> [--level L] Stage a unit for sealing (L = e.g. L1,L2; default L3)
17
+ drop <source> Unstage a unit
18
+ list Show staged units and their levels
19
+ enshell Seal every staged unit -> object files
20
+ help | -h Show this help
21
+ -v | --version Show the version`;
22
+ // --- staging index (.blackshell/stage.json in the working dir, git-index-like) ---
23
+ const STAGE_FILE = ".blackshell/stage.json";
24
+ export function readStage() {
25
+ if (!existsSync(STAGE_FILE)) {
26
+ return [];
27
+ }
28
+ return JSON.parse(readFileSync(STAGE_FILE, "utf8"));
29
+ }
30
+ export function writeStage(units) {
31
+ mkdirSync(".blackshell", { recursive: true });
32
+ writeFileSync(STAGE_FILE, JSON.stringify(units, null, 2) + "\n");
33
+ }
34
+ export function showLevels(levels) {
35
+ if (levels.length === 0) {
36
+ return "L0 (identity)";
37
+ }
38
+ return levels.join(",");
39
+ }
40
+ // Resolve the engine binary. The published package pulls the matching engine as an
41
+ // optional dependency @sdkurjnk/blackshell-<platform>-<arch> (os/cpu-gated, so npm
42
+ // installs only the host's); resolve its binary. A local dev build in build/ is the
43
+ // fallback when no platform package is installed.
44
+ function enginePath() {
45
+ const exe = process.platform === "win32" ? "blackshell-engine.exe" : "blackshell-engine";
46
+ const pkg = `@sdkurjnk/blackshell-${process.platform}-${process.arch}`;
47
+ try {
48
+ const require = createRequire(import.meta.url);
49
+ return join(dirname(require.resolve(`${pkg}/package.json`)), exe);
50
+ }
51
+ catch {
52
+ return here(`../build/${exe}`);
53
+ }
54
+ }
55
+ // --- engine (C++) per-unit primitive call; returns the structured token line ---
56
+ function engine(args) {
57
+ const bin = enginePath();
58
+ const res = spawnSync(bin, args, { encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
59
+ if (res.error) {
60
+ console.error("error: engine not found (build it: npm run build:engine)");
61
+ return { token: "", status: 127 };
62
+ }
63
+ const token = (res.stdout ?? "").trim().split("\n").pop() ?? "";
64
+ return { token, status: res.status ?? 1 };
65
+ }
66
+ // engine token -> rendered message. The engine never renders.
67
+ export function render(token) {
68
+ const [key, ...a] = token.split(" ");
69
+ switch (key) {
70
+ case "gate.ok": {
71
+ return { line: `pass: ${a[0]} is eligible`, err: false };
72
+ }
73
+ case "gate.reject": {
74
+ return { line: `reject: ${a[0]} — ineligible`, err: true };
75
+ }
76
+ case "sealed": {
77
+ return { line: `sealed: ${a[0]} -> ${a[1]}`, err: false };
78
+ }
79
+ case "frontend.failed": {
80
+ return { line: `error: clang (frontend) failed on ${a[0]}`, err: true };
81
+ }
82
+ case "backend.failed": {
83
+ return { line: `error: llc (backend) failed on ${a[0]}`, err: true };
84
+ }
85
+ case "verify.broken": {
86
+ return { line: `error: noising broke equivalence on ${a[0]}`, err: true };
87
+ }
88
+ case "arg.one_positional": {
89
+ return { line: `error: expected exactly one <source> argument`, err: true };
90
+ }
91
+ case "cmd.unknown": {
92
+ return { line: `error: unknown command: ${a[0]}`, err: true };
93
+ }
94
+ default: {
95
+ return { line: token, err: true };
96
+ }
97
+ }
98
+ }
99
+ function emit(token) {
100
+ if (!token) {
101
+ return;
102
+ }
103
+ const { line, err } = render(token);
104
+ if (err) {
105
+ console.error(line);
106
+ }
107
+ else {
108
+ console.log(line);
109
+ }
110
+ }
111
+ // --- arg helpers ---
112
+ export function popOption(rest, name) {
113
+ const i = rest.indexOf(name);
114
+ if (i === -1) {
115
+ return { value: undefined, rest };
116
+ }
117
+ return { value: rest[i + 1], rest: rest.slice(0, i).concat(rest.slice(i + 2)) };
118
+ }
119
+ export function onePositional(rest) {
120
+ const positionals = rest.filter((a) => !a.startsWith("--"));
121
+ if (positionals.length !== 1) {
122
+ return undefined;
123
+ }
124
+ return positionals[0];
125
+ }
126
+ // --- commands ---
127
+ function cmdCheck(rest) {
128
+ const src = onePositional(rest);
129
+ if (src === undefined) {
130
+ console.error("error: expected exactly one <source> argument");
131
+ return 1;
132
+ }
133
+ const { token, status } = engine(["check", src]);
134
+ emit(token);
135
+ return status;
136
+ }
137
+ function cmdAdd(rest) {
138
+ const opt = popOption(rest, "--level");
139
+ const src = onePositional(opt.rest);
140
+ if (src === undefined) {
141
+ console.error("error: expected exactly one <source> argument");
142
+ return 1;
143
+ }
144
+ if (!existsSync(src)) {
145
+ console.error(`error: file not found: ${src}`);
146
+ return 1;
147
+ }
148
+ const levels = opt.value ? opt.value.split(",").map((s) => s.trim()).filter(Boolean) : ["L3"];
149
+ const units = readStage().filter((u) => u.path !== src);
150
+ units.push({ path: src, levels });
151
+ writeStage(units);
152
+ console.log(`staged: ${src} [${showLevels(levels)}]`);
153
+ return 0;
154
+ }
155
+ function cmdDrop(rest) {
156
+ const src = onePositional(rest);
157
+ if (src === undefined) {
158
+ console.error("error: expected exactly one <source> argument");
159
+ return 1;
160
+ }
161
+ const units = readStage();
162
+ const kept = units.filter((u) => u.path !== src);
163
+ if (kept.length === units.length) {
164
+ console.error(`error: not staged: ${src}`);
165
+ return 1;
166
+ }
167
+ writeStage(kept);
168
+ console.log(`dropped: ${src}`);
169
+ return 0;
170
+ }
171
+ function cmdList() {
172
+ const units = readStage();
173
+ if (units.length === 0) {
174
+ console.log("nothing staged");
175
+ return 0;
176
+ }
177
+ for (const u of units) {
178
+ console.log(` ${u.path} [${showLevels(u.levels)}]`);
179
+ }
180
+ return 0;
181
+ }
182
+ function cmdEnshell() {
183
+ const units = readStage();
184
+ if (units.length === 0) {
185
+ console.log("nothing staged");
186
+ return 0;
187
+ }
188
+ let code = 0;
189
+ for (const u of units) {
190
+ const { token, status } = engine(["enshell", u.path]);
191
+ emit(token);
192
+ if (status !== 0) {
193
+ code = status;
194
+ }
195
+ }
196
+ writeStage([]); // 1-shot: staging is consumed by enshell
197
+ console.log(`enshell complete: ${units.length} unit(s); staging cleared`);
198
+ return code;
199
+ }
200
+ function main(argv) {
201
+ const [cmd, ...rest] = argv;
202
+ if (cmd === "-v" || cmd === "--version" || cmd === "version") {
203
+ console.log(pkg.version);
204
+ return 0;
205
+ }
206
+ if (cmd === undefined || cmd === "help" || cmd === "-h" || cmd === "--help") {
207
+ console.log(USAGE);
208
+ return 0;
209
+ }
210
+ switch (cmd) {
211
+ case "check": {
212
+ return cmdCheck(rest);
213
+ }
214
+ case "add": {
215
+ return cmdAdd(rest);
216
+ }
217
+ case "drop": {
218
+ return cmdDrop(rest);
219
+ }
220
+ case "list": {
221
+ return cmdList();
222
+ }
223
+ case "enshell": {
224
+ return cmdEnshell();
225
+ }
226
+ default: {
227
+ console.error(`error: unknown command: ${cmd}`);
228
+ console.error(USAGE);
229
+ return 1;
230
+ }
231
+ }
232
+ }
233
+ // Run only when invoked directly (not when imported by tests).
234
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
235
+ process.exit(main(process.argv.slice(2)));
236
+ }
package/package.json CHANGED
@@ -1,20 +1,21 @@
1
1
  {
2
2
  "name": "@sdkurjnk/blackshell",
3
- "version": "0.1.0",
3
+ "version": "0.3.3",
4
4
  "description": "Build-stage protection tool that seals critical code regions at the compiler IR level, communicating with the outside only by value.",
5
5
  "type": "module",
6
6
  "bin": {
7
- "blackshell": "bin/blackshell.js"
7
+ "blackshell": "dist/cli.js"
8
8
  },
9
9
  "files": [
10
- "bin/",
11
- "src/cli/",
12
- "src/engine/blackshell_engine/",
13
- "src/engine/examples/"
10
+ "dist/"
14
11
  ],
15
12
  "scripts": {
16
- "test": "node --test",
17
- "test:engine": "python -m unittest discover -s src/engine/tests -t src/engine -p \"test_*.py\""
13
+ "build:engine": "node scripts/build-engine.mjs",
14
+ "build:engine-test": "node scripts/build-engine.mjs --test",
15
+ "build:ts": "tsc",
16
+ "build": "npm run build:engine && npm run build:ts",
17
+ "pretest": "npm run build:engine-test && npm run build:ts",
18
+ "test": "node --test"
18
19
  },
19
20
  "engines": {
20
21
  "node": ">=20"
@@ -38,5 +39,16 @@
38
39
  "publishConfig": {
39
40
  "access": "public",
40
41
  "provenance": true
42
+ },
43
+ "devDependencies": {
44
+ "@types/node": "^26.6.6",
45
+ "typescript": "^7.0.2"
46
+ },
47
+ "optionalDependencies": {
48
+ "@sdkurjnk/blackshell-darwin-arm64": "0.3.3",
49
+ "@sdkurjnk/blackshell-darwin-x64": "0.3.3",
50
+ "@sdkurjnk/blackshell-linux-arm64": "0.3.3",
51
+ "@sdkurjnk/blackshell-linux-x64": "0.3.3",
52
+ "@sdkurjnk/blackshell-win32-x64": "0.3.3"
41
53
  }
42
54
  }
package/bin/blackshell.js DELETED
@@ -1,49 +0,0 @@
1
- #!/usr/bin/env node
2
- import { spawnSync } from 'node:child_process';
3
- import { fileURLToPath } from 'node:url';
4
- import { delimiter } from 'node:path';
5
- import { triage } from '../src/cli/index.js';
6
-
7
- const argv = process.argv.slice(2);
8
- const t = triage(argv);
9
-
10
- // Meta queries (version, bare usage) are answered here without the engine.
11
- if (t.meta !== undefined) {
12
- process.stdout.write(t.meta + '\n');
13
- process.exit(0);
14
- }
15
-
16
- // Everything else forwards to the internal engine. In the PoC the seam is a
17
- // subprocess (Python); in production it becomes a C-ABI native binary. The
18
- // protocol — argv in, stdio inherited, exit code propagated — stays identical
19
- // (docs/interfaces/01-cli-seam.md).
20
- // The engine package is made importable via PYTHONPATH; cwd stays the user's
21
- // working directory so IR paths and the .blackshell/ index resolve there.
22
- const engineDir = fileURLToPath(new URL('../src/engine', import.meta.url));
23
- const pythonPath = process.env.PYTHONPATH
24
- ? engineDir + delimiter + process.env.PYTHONPATH
25
- : engineDir;
26
- const candidates = ['python', 'python3', 'py'];
27
-
28
- let res;
29
- for (const py of candidates) {
30
- res = spawnSync(py, ['-m', 'blackshell_engine', ...argv], {
31
- stdio: 'inherit',
32
- env: { ...process.env, PYTHONPATH: pythonPath },
33
- });
34
- // Try the next interpreter name only when this one isn't on PATH.
35
- if (!(res.error && res.error.code === 'ENOENT')) break;
36
- }
37
-
38
- if (res.error) {
39
- if (res.error.code === 'ENOENT') {
40
- process.stderr.write(
41
- 'blackshell: Python engine not found. The PoC engine needs Python 3 on PATH.\n',
42
- );
43
- process.exit(127);
44
- }
45
- process.stderr.write(`blackshell: failed to launch engine: ${res.error.message}\n`);
46
- process.exit(127);
47
- }
48
-
49
- process.exit(res.status ?? 1);
package/src/cli/index.js DELETED
@@ -1,37 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
-
3
- const pkg = JSON.parse(
4
- readFileSync(new URL('../../package.json', import.meta.url), 'utf8'),
5
- );
6
-
7
- export const VERSION = pkg.version;
8
-
9
- // Minimal top-level usage. Intentionally does NOT list commands — the engine
10
- // owns the command set (single source of truth), so JS can't drift from it.
11
- export const USAGE = `blackshell <command> [options]
12
-
13
- Build-stage protection tool. Seals critical code regions at the compiler IR
14
- level so they talk to the outside only by value.
15
-
16
- Run \`blackshell help\` for commands, \`blackshell -v\` for the version.`;
17
-
18
- // Pure triage — the external(JS)/internal(engine) seam (docs/interfaces/01).
19
- // JS answers only what packaging *owns* (version = the npm package value) plus
20
- // a bare top-level usage, so both work even if the engine is missing. Every
21
- // real command is forwarded to the engine verbatim; JS does not parse them.
22
- //
23
- // Returns { meta: string } to answer in JS, or { forward: true } to hand argv
24
- // to the engine.
25
- export function triage(argv) {
26
- const [cmd, ...rest] = argv;
27
- if (cmd === '-v' || cmd === '--version' || cmd === 'version') {
28
- return { meta: VERSION };
29
- }
30
- if (cmd === undefined) {
31
- return { meta: USAGE };
32
- }
33
- if ((cmd === '-h' || cmd === '--help') && rest.length === 0) {
34
- return { meta: USAGE };
35
- }
36
- return { forward: true };
37
- }
@@ -1,6 +0,0 @@
1
- """Black-Shell PoC engine (internal execution layer).
2
-
3
- LLVM-free toy pipeline: toy IR + interpreter + dummy passes, wired end to end
4
- so the layer contracts (docs/interfaces/) can be locked in code before the real
5
- gate / noising / LLVM backend land. See docs/interfaces/README.md.
6
- """
@@ -1,5 +0,0 @@
1
- import sys
2
-
3
- from .driver import main
4
-
5
- raise SystemExit(main(sys.argv[1:]))
@@ -1,231 +0,0 @@
1
- """Engine driver — parse argv, dispatch commands, assemble the pipeline
2
- (docs/interfaces/02-driver.md). Single source of truth for the command set.
3
-
4
- Pipeline order is fixed: load -> gate (reject => exit 2) -> noising L1->L2->L3
5
- (only the unit's selected levels) -> emit. Every stage honours the same IR
6
- contract, so dummy passes swap for real ones without changes here.
7
-
8
- Error handling: pipeline code raises messages.EngineError; the driver is the
9
- ONLY place that renders a message or touches stdout/stderr, via `_emit`, which
10
- looks the text/stream/exit up in the single-source catalog (messages.py).
11
- """
12
-
13
- import json
14
- import os
15
- import sys
16
-
17
- from . import harness, ir, messages, stage
18
- from .messages import EXIT_OK, EngineError
19
- from .passes import GATE, LEVEL_ORDER, NOISING
20
-
21
- USAGE = """blackshell <command> [options]
22
-
23
- Product commands:
24
- check <ir-file> Gate-only verdict (§5 cond.1); preview before add
25
- add <ir-file> [--level L] Stage a unit for sealing (L = e.g. L1,L2,L3)
26
- drop <ir-file> Unstage a unit
27
- list Show staged units and their levels
28
- enshell [--no-gate] [--emit-ir DIR] [--verify]
29
- Seal all staged units -> artifacts
30
-
31
- Dev commands:
32
- run <ir-file> [--input k=v ...] Run a unit in the toy interpreter
33
- help Show this help
34
- """
35
-
36
-
37
- def main(argv):
38
- if not argv:
39
- print(USAGE)
40
- return EXIT_OK
41
-
42
- cmd, rest = argv[0], argv[1:]
43
- try:
44
- handler = {
45
- "help": lambda r: (print(USAGE), EXIT_OK)[1],
46
- "check": _check,
47
- "add": _add,
48
- "drop": _drop,
49
- "list": _list,
50
- "enshell": _enshell,
51
- "run": _run,
52
- }.get(cmd)
53
- if handler is None:
54
- code = _emit("cmd.unknown", cmd=cmd)
55
- print(USAGE, file=sys.stderr)
56
- return code
57
- return handler(rest)
58
- except EngineError as e:
59
- # The one place pipeline-raised messages are rendered.
60
- return _emit(e.key, **e.params)
61
-
62
-
63
- # --- commands ---------------------------------------------------------------
64
-
65
-
66
- def _check(rest):
67
- path = _one_positional(rest)
68
- verdict = _run_gate(ir.load_ir(path))
69
- if verdict["ok"]:
70
- return _emit("check.pass", path=path, gate=GATE[0])
71
- return _emit("gate.reject", path=path, reason=verdict.get("reason", "ineligible"))
72
-
73
-
74
- def _add(rest):
75
- levels, rest = _pop_opt(rest, "--level")
76
- path = _one_positional(rest)
77
- ir.load_ir(path) # validate before staging
78
- selected = _parse_levels(levels)
79
- stage.add(path, selected)
80
- return _emit("stage.added", path=path, levels=_show_levels(selected))
81
-
82
-
83
- def _drop(rest):
84
- path = _one_positional(rest)
85
- if stage.drop(path):
86
- return _emit("stage.dropped", path=path)
87
- return _emit("stage.not_staged", path=path)
88
-
89
-
90
- def _list(rest):
91
- units = stage.staged()
92
- if not units:
93
- return _emit("stage.nothing")
94
- for u in units:
95
- _emit("stage.list_item", path=u["path"], levels=_show_levels(u["levels"]))
96
- return EXIT_OK
97
-
98
-
99
- def _enshell(rest):
100
- no_gate, rest = _pop_flag(rest, "--no-gate")
101
- do_verify, rest = _pop_flag(rest, "--verify")
102
- emit_dir, rest = _pop_opt(rest, "--emit-ir")
103
- emit_dir = emit_dir or "."
104
-
105
- units = stage.staged()
106
- if not units:
107
- return _emit("stage.nothing")
108
-
109
- count = 0
110
- for u in units:
111
- path, levels = u["path"], u["levels"]
112
- module = ir.load_ir(path)
113
- baseline = ir.load_ir(path) # independent L0 copy for the harness
114
-
115
- if not no_gate:
116
- verdict = _run_gate(module)
117
- if not verdict["ok"]:
118
- return _emit(
119
- "gate.reject", path=path, reason=verdict.get("reason", "ineligible")
120
- )
121
-
122
- for level in LEVEL_ORDER:
123
- if level not in levels:
124
- continue
125
- name, transform = NOISING[level]
126
- module = transform(module)
127
- if do_verify:
128
- report = harness.verify(
129
- baseline, module, harness.sample_inputs(baseline)
130
- )
131
- if not report["equivalent"]:
132
- return _emit(
133
- "verify.broken",
134
- pass_name=name,
135
- path=path,
136
- mismatch=report["mismatches"][0],
137
- )
138
-
139
- out = _write_artifact(module, emit_dir)
140
- _emit("enshell.sealed", path=path, out=out)
141
- count += 1
142
-
143
- stage.clear() # 1-shot artifact model: staging is consumed by enshell
144
- return _emit("enshell.done", count=count)
145
-
146
-
147
- def _run(rest):
148
- inputs, rest = _pop_inputs(rest)
149
- path = _one_positional(rest)
150
- from .interp import run as interp_run
151
-
152
- # Interpreter outputs are data, not protocol messages — printed directly.
153
- for name, value in interp_run(ir.load_ir(path), inputs).items():
154
- print(f"{name}={value}")
155
- return EXIT_OK
156
-
157
-
158
- # --- rendering (the single I/O point) ---------------------------------------
159
-
160
-
161
- def _emit(key, **params):
162
- """Render one catalog message to the right stream; return its exit code.
163
- The only function in the engine that writes user-facing output."""
164
- line, stream, code = messages.render(key, **params)
165
- print(line, file=sys.stderr if stream == messages.ERR else sys.stdout)
166
- return code
167
-
168
-
169
- # --- helpers ----------------------------------------------------------------
170
-
171
-
172
- def _run_gate(module):
173
- _name, check = GATE
174
- return check(module)
175
-
176
-
177
- def _write_artifact(module, out_dir):
178
- os.makedirs(out_dir, exist_ok=True)
179
- out = os.path.join(out_dir, f"{module['name']}.sealed.json")
180
- with open(out, "w", encoding="utf-8") as f:
181
- json.dump(module, f, indent=2)
182
- f.write("\n")
183
- return out
184
-
185
-
186
- def _show_levels(levels):
187
- return ",".join(levels) if levels else "L0 (identity)"
188
-
189
-
190
- def _parse_levels(raw):
191
- if not raw:
192
- return []
193
- return [tok.strip() for tok in raw.split(",") if tok.strip()]
194
-
195
-
196
- def _one_positional(rest):
197
- positionals = [a for a in rest if not a.startswith("--")]
198
- if len(positionals) != 1:
199
- raise EngineError("arg.one_positional")
200
- return positionals[0]
201
-
202
-
203
- def _pop_opt(rest, name):
204
- """Remove `--name value` and return (value, remaining)."""
205
- if name in rest:
206
- i = rest.index(name)
207
- value = rest[i + 1] if i + 1 < len(rest) else None
208
- return value, rest[:i] + rest[i + 2 :]
209
- return None, rest
210
-
211
-
212
- def _pop_flag(rest, name):
213
- if name in rest:
214
- return True, [a for a in rest if a != name]
215
- return False, rest
216
-
217
-
218
- def _pop_inputs(rest):
219
- """Collect `--input k=v ...` pairs (consumes k=v tokens after --input)."""
220
- inputs = {}
221
- if "--input" not in rest:
222
- return inputs, rest
223
- i = rest.index("--input")
224
- out = rest[:i]
225
- j = i + 1
226
- while j < len(rest) and "=" in rest[j] and not rest[j].startswith("--"):
227
- key, val = rest[j].split("=", 1)
228
- inputs[key] = int(val)
229
- j += 1
230
- out += rest[j:]
231
- return inputs, out
@@ -1,36 +0,0 @@
1
- """Equivalence harness (docs/interfaces/05-verification-harness.md).
2
-
3
- Runs baseline (L0) and candidate (transformed) through the interpreter on the
4
- same inputs and compares observable outputs (`returns`) only — never internal
5
- registers / instruction count / path, since noising changes exactly those.
6
-
7
- Sample-based: absence of a counterexample, NOT an equivalence proof.
8
- """
9
-
10
- from .interp import run
11
-
12
-
13
- def verify(baseline, candidate, inputs_list):
14
- mismatches = []
15
- for inputs in inputs_list:
16
- expected = run(baseline, inputs)
17
- actual = run(candidate, inputs)
18
- if expected != actual:
19
- mismatches.append(
20
- {"input": inputs, "expected": expected, "actual": actual}
21
- )
22
- return {
23
- "equivalent": not mismatches,
24
- "mismatches": mismatches,
25
- "note": "sample-based (counterexample absence), not an equivalence proof",
26
- }
27
-
28
-
29
- def sample_inputs(module, n=6):
30
- """Deterministic input vectors to exercise the harness in the PoC."""
31
- pool = [0, 1, 2, 3, 7, 42]
32
- params = module["params"]
33
- return [
34
- {p: pool[(i + j) % len(pool)] for j, p in enumerate(params)}
35
- for i in range(n)
36
- ]
@@ -1,84 +0,0 @@
1
- """Toy interpreter — executes an IR module on value inputs.
2
-
3
- This is the PoC's only execution backend (no native/LLVM yet) and the primitive
4
- the equivalence harness is built on: `verify` just runs two modules here and
5
- compares outputs (docs/interfaces/05). PoC/dev-only; production execution is
6
- native.
7
- """
8
-
9
- from .ir import BIN_OPS
10
- from .messages import EngineError
11
-
12
- _STEP_LIMIT = 1_000_000
13
-
14
-
15
- def run(module, inputs):
16
- """inputs: {param_name: int} -> {return_name: int}."""
17
- regs = {}
18
- for p in module["params"]:
19
- if p not in inputs:
20
- raise EngineError("interp.missing_input", param=p)
21
- regs[p] = int(inputs[p])
22
-
23
- mem = {} # isolated local store, index -> value
24
- blocks = {b["label"]: b for b in module["blocks"]}
25
- cur = module["blocks"][0]["label"]
26
-
27
- steps = 0
28
- while True:
29
- steps += 1
30
- if steps > _STEP_LIMIT:
31
- raise EngineError("interp.step_limit")
32
-
33
- next_label = None
34
- for inst in blocks[cur]["insts"]:
35
- op = inst["op"]
36
- if op == "const":
37
- regs[inst["dst"]] = int(inst["imm"])
38
- elif op == "mov":
39
- regs[inst["dst"]] = regs[inst["src"]]
40
- elif op in BIN_OPS:
41
- regs[inst["dst"]] = _binop(op, regs[inst["lhs"]], regs[inst["rhs"]])
42
- elif op == "load":
43
- regs[inst["dst"]] = mem.get(_addr(regs, inst["addr"]), 0)
44
- elif op == "store":
45
- mem[_addr(regs, inst["addr"])] = regs[inst["src"]]
46
- elif op == "br":
47
- next_label = inst["then"] if regs[inst["cond"]] != 0 else inst["else"]
48
- break
49
- elif op == "jmp":
50
- next_label = inst["target"]
51
- break
52
- elif op == "ret":
53
- return {r: regs[r] for r in module["returns"]}
54
- else:
55
- raise EngineError("interp.unknown_op", op=op)
56
-
57
- if next_label is None:
58
- # Fell off the end of a block with no branch/ret: implicit return.
59
- return {r: regs.get(r, 0) for r in module["returns"]}
60
- cur = next_label
61
-
62
-
63
- def _addr(regs, a):
64
- return a if isinstance(a, int) else regs[a]
65
-
66
-
67
- def _binop(op, a, b):
68
- if op == "add":
69
- return a + b
70
- if op == "sub":
71
- return a - b
72
- if op == "mul":
73
- return a * b
74
- if op == "and":
75
- return a & b
76
- if op == "or":
77
- return a | b
78
- if op == "xor":
79
- return a ^ b
80
- if op == "shl":
81
- return a << b
82
- if op == "shr":
83
- return a >> b
84
- raise EngineError("interp.unknown_op", op=op)
@@ -1,50 +0,0 @@
1
- """Toy IR model — load + validate (docs/interfaces/03-ir-model.md).
2
-
3
- The IR is JSON. A module is one sealed unit: a function with value inputs
4
- (`params`), value outputs (`returns`), virtual registers (`locals`), and basic
5
- blocks. No pointers / globals / I/O are representable — that is the §5
6
- condition-1 isolation enforced structurally.
7
-
8
- This layer never prints: malformed IR raises EngineError (rendered by the
9
- driver, docs/interfaces/02 error handling).
10
- """
11
-
12
- import json
13
-
14
- from .messages import EngineError
15
-
16
- BIN_OPS = {"add", "sub", "mul", "and", "or", "xor", "shl", "shr"}
17
-
18
-
19
- def load_ir(path):
20
- try:
21
- with open(path, "r", encoding="utf-8") as f:
22
- module = json.load(f)
23
- except FileNotFoundError:
24
- raise EngineError("file.not_found", path=path)
25
- except json.JSONDecodeError as e:
26
- raise EngineError("ir.bad_json", path=path, detail=str(e))
27
- validate(module)
28
- return module
29
-
30
-
31
- def validate(m):
32
- for key in ("name", "params", "returns", "locals", "blocks"):
33
- if key not in m:
34
- raise EngineError("ir.missing_field", field=key)
35
- if not m["blocks"]:
36
- raise EngineError("ir.no_blocks")
37
-
38
- labels = {b["label"] for b in m["blocks"]}
39
- for b in m["blocks"]:
40
- if "insts" not in b:
41
- raise EngineError("ir.block_no_insts", label=b.get("label"))
42
- for inst in b["insts"]:
43
- op = inst.get("op")
44
- if op is None:
45
- raise EngineError("ir.inst_no_op", label=b["label"])
46
- if op == "br" and (inst["then"] not in labels or inst["else"] not in labels):
47
- raise EngineError("ir.bad_branch", label=b["label"])
48
- if op == "jmp" and inst["target"] not in labels:
49
- raise EngineError("ir.bad_branch", label=b["label"])
50
- return m
@@ -1,61 +0,0 @@
1
- """Single source of truth for user-facing messages and the exit-code protocol
2
- (docs/interfaces/02-driver.md).
3
-
4
- Pipeline code (ir / interp / passes) never prints — it raises
5
- ``EngineError(key, **params)``. The driver is the only place that renders a
6
- message (``driver._emit``), looking everything up here. Keeping the whole
7
- catalog in one module is what lets a future JS-side CLI take over rendering by
8
- consuming this table, instead of the driver.
9
- """
10
-
11
- EXIT_OK = 0
12
- EXIT_ERR = 1
13
- EXIT_REJECT = 2 # gate rejected a unit (§5 condition 1)
14
- EXIT_ENGINE_MISSING = 127 # set by the JS launcher; listed here for completeness
15
-
16
- OUT, ERR = "out", "err"
17
-
18
- # key -> (template, stream, exit_code)
19
- CATALOG = {
20
- # --- errors (stderr, exit 1) ---
21
- "ir.missing_field": ("error: IR missing field: {field}", ERR, EXIT_ERR),
22
- "ir.no_blocks": ("error: module has no blocks", ERR, EXIT_ERR),
23
- "ir.block_no_insts": ("error: block {label!r} has no insts", ERR, EXIT_ERR),
24
- "ir.inst_no_op": ("error: instruction without op in block {label!r}", ERR, EXIT_ERR),
25
- "ir.bad_branch": ("error: branch to unknown label in block {label!r}", ERR, EXIT_ERR),
26
- "ir.bad_json": ("error: invalid JSON in {path}: {detail}", ERR, EXIT_ERR),
27
- "file.not_found": ("error: file not found: {path}", ERR, EXIT_ERR),
28
- "arg.one_positional": ("error: expected exactly one <ir-file> argument", ERR, EXIT_ERR),
29
- "interp.missing_input": ("error: missing input: {param}", ERR, EXIT_ERR),
30
- "interp.step_limit": ("error: interpreter step limit exceeded (infinite loop?)", ERR, EXIT_ERR),
31
- "interp.unknown_op": ("error: unknown op: {op}", ERR, EXIT_ERR),
32
- "cmd.unknown": ("error: unknown command: {cmd}", ERR, EXIT_ERR),
33
- "stage.not_staged": ("error: not staged: {path}", ERR, EXIT_ERR),
34
- "verify.broken": ("error: {pass_name} broke equivalence on {path}: {mismatch}", ERR, EXIT_ERR),
35
- # --- reject (stderr, exit 2) ---
36
- "gate.reject": ("reject: {path} — {reason}", ERR, EXIT_REJECT),
37
- # --- info (stdout, exit 0) ---
38
- "check.pass": ("pass: {path} is eligible (gate: {gate})", OUT, EXIT_OK),
39
- "stage.added": ("staged: {path} [{levels}]", OUT, EXIT_OK),
40
- "stage.dropped": ("dropped: {path}", OUT, EXIT_OK),
41
- "stage.nothing": ("nothing staged", OUT, EXIT_OK),
42
- "stage.list_item": (" {path} [{levels}]", OUT, EXIT_OK),
43
- "enshell.sealed": ("sealed: {path} -> {out}", OUT, EXIT_OK),
44
- "enshell.done": ("enshell complete: {count} unit(s); staging cleared", OUT, EXIT_OK),
45
- }
46
-
47
-
48
- class EngineError(Exception):
49
- """Raised by pipeline code; carries a catalog key + params so the driver
50
- can render it. Pipeline code must never print directly."""
51
-
52
- def __init__(self, key, **params):
53
- self.key = key
54
- self.params = params
55
- super().__init__(key)
56
-
57
-
58
- def render(key, **params):
59
- """Return (line, stream, exit_code) for a catalog key."""
60
- template, stream, code = CATALOG[key]
61
- return template.format(**params), stream, code
@@ -1,39 +0,0 @@
1
- """Pass registry + dummy passes (docs/interfaces/04-pass-contract.md).
2
-
3
- Two pass kinds, two signatures:
4
- - noising : IR -> IR (semantics-preserving; here: identity)
5
- - gate : IR -> Verdict (read-only; here: accept-all)
6
-
7
- The working-skeleton point: dummy and real passes share these signatures, so
8
- replacing a dummy with a real pass never touches the driver (just swap the
9
- registry entry). Identity noising is SAFE ("correct but unprotected");
10
- accept-all gate is NOT — it gives a false "sealed" confidence and must be
11
- replaced before shipping.
12
- """
13
-
14
- import copy
15
-
16
-
17
- def dummy_gate(module):
18
- """IR -> Verdict. DUMMY accept-all. Replace with the real §5 condition-1
19
- static check before shipping."""
20
- return {"ok": True, "dummy": True}
21
-
22
-
23
- def _identity(module):
24
- """IR -> IR, unchanged. Returns a copy so callers can treat passes as pure."""
25
- return copy.deepcopy(module)
26
-
27
-
28
- # Gate always runs ahead of noising (verdict carries the pass name).
29
- GATE = ("dummy-accept-all", dummy_gate)
30
-
31
- # Noising passes keyed by level; all identity in the skeleton.
32
- NOISING = {
33
- "L1": ("identity-L1", _identity),
34
- "L2": ("identity-L2", _identity),
35
- "L3": ("identity-L3", _identity),
36
- }
37
-
38
- # Fixed application order regardless of selection order.
39
- LEVEL_ORDER = ("L1", "L2", "L3")
@@ -1,50 +0,0 @@
1
- """Staging index (docs/interfaces/02-driver.md).
2
-
3
- The git-style index shared by add / drop / list. Lives in the working
4
- directory at .blackshell/stage.json (cf. .git/index). Records each staged
5
- unit's path and its per-unit noising levels.
6
- """
7
-
8
- import json
9
- import os
10
-
11
- INDEX_DIR = ".blackshell"
12
- INDEX_PATH = os.path.join(INDEX_DIR, "stage.json")
13
-
14
-
15
- def _read():
16
- if not os.path.exists(INDEX_PATH):
17
- return {"units": []}
18
- with open(INDEX_PATH, "r", encoding="utf-8") as f:
19
- return json.load(f)
20
-
21
-
22
- def _write(index):
23
- os.makedirs(INDEX_DIR, exist_ok=True)
24
- with open(INDEX_PATH, "w", encoding="utf-8") as f:
25
- json.dump(index, f, indent=2)
26
- f.write("\n")
27
-
28
-
29
- def add(path, levels):
30
- index = _read()
31
- units = [u for u in index["units"] if u["path"] != path]
32
- units.append({"path": path, "levels": levels})
33
- index["units"] = units
34
- _write(index)
35
-
36
-
37
- def drop(path):
38
- index = _read()
39
- before = len(index["units"])
40
- index["units"] = [u for u in index["units"] if u["path"] != path]
41
- _write(index)
42
- return before != len(index["units"])
43
-
44
-
45
- def staged():
46
- return _read()["units"]
47
-
48
-
49
- def clear():
50
- _write({"units": []})
@@ -1,13 +0,0 @@
1
- {
2
- "name": "add2",
3
- "params": ["a"],
4
- "returns": ["r"],
5
- "locals": ["t0"],
6
- "blocks": [
7
- { "label": "entry", "insts": [
8
- { "op": "const", "dst": "t0", "imm": 2 },
9
- { "op": "add", "dst": "r", "lhs": "a", "rhs": "t0" },
10
- { "op": "ret" }
11
- ]}
12
- ]
13
- }
@@ -1,19 +0,0 @@
1
- {
2
- "name": "select",
3
- "params": ["a", "b"],
4
- "returns": ["r"],
5
- "locals": [],
6
- "blocks": [
7
- { "label": "entry", "insts": [
8
- { "op": "br", "cond": "a", "then": "use_a", "else": "use_b" }
9
- ]},
10
- { "label": "use_a", "insts": [
11
- { "op": "mov", "dst": "r", "src": "a" },
12
- { "op": "ret" }
13
- ]},
14
- { "label": "use_b", "insts": [
15
- { "op": "mov", "dst": "r", "src": "b" },
16
- { "op": "ret" }
17
- ]}
18
- ]
19
- }