@sdkurjnk/blackshell 0.1.0 → 0.2.1

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.
@@ -0,0 +1,249 @@
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
+
10
+ const here = (p: string): string => fileURLToPath(new URL(p, import.meta.url));
11
+ const pkg = JSON.parse(readFileSync(here("../package.json"), "utf8")) as { version: string };
12
+
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
+
23
+ // --- staging index (.blackshell/stage.json in the working dir, git-index-like) ---
24
+ const STAGE_FILE = ".blackshell/stage.json";
25
+
26
+ interface Unit {
27
+ path: string;
28
+ levels: string[];
29
+ }
30
+
31
+ export function readStage(): Unit[] {
32
+ if (!existsSync(STAGE_FILE)) {
33
+ return [];
34
+ }
35
+ return JSON.parse(readFileSync(STAGE_FILE, "utf8")) as Unit[];
36
+ }
37
+
38
+ export function writeStage(units: Unit[]): void {
39
+ mkdirSync(".blackshell", { recursive: true });
40
+ writeFileSync(STAGE_FILE, JSON.stringify(units, null, 2) + "\n");
41
+ }
42
+
43
+ export function showLevels(levels: string[]): string {
44
+ if (levels.length === 0) {
45
+ return "L0 (identity)";
46
+ }
47
+ return levels.join(",");
48
+ }
49
+
50
+ // Resolve the engine binary: the published package ships a per-platform prebuilt
51
+ // under vendor/<platform>-<arch>/; a local dev build lands in build/.
52
+ function enginePath(): string {
53
+ const exe = process.platform === "win32" ? "blackshell-engine.exe" : "blackshell-engine";
54
+ const vendored = here(`../vendor/${process.platform}-${process.arch}/${exe}`);
55
+ return existsSync(vendored) ? vendored : here(`../build/${exe}`);
56
+ }
57
+
58
+ // --- engine (C++) per-unit primitive call; returns the structured token line ---
59
+ function engine(args: string[]): { token: string; status: number } {
60
+ const bin = enginePath();
61
+ const res = spawnSync(bin, args, { encoding: "utf8", stdio: ["inherit", "pipe", "inherit"] });
62
+ if (res.error) {
63
+ console.error("error: engine not found (build it: npm run build:engine)");
64
+ return { token: "", status: 127 };
65
+ }
66
+ const token = (res.stdout ?? "").trim().split("\n").pop() ?? "";
67
+ return { token, status: res.status ?? 1 };
68
+ }
69
+
70
+ // engine token -> rendered message. The engine never renders.
71
+ export function render(token: string): { line: string; err: boolean } {
72
+ const [key, ...a] = token.split(" ");
73
+ switch (key) {
74
+ case "gate.ok": {
75
+ return { line: `pass: ${a[0]} is eligible`, err: false };
76
+ }
77
+ case "gate.reject": {
78
+ return { line: `reject: ${a[0]} — ineligible`, err: true };
79
+ }
80
+ case "sealed": {
81
+ return { line: `sealed: ${a[0]} -> ${a[1]}`, err: false };
82
+ }
83
+ case "frontend.failed": {
84
+ return { line: `error: clang (frontend) failed on ${a[0]}`, err: true };
85
+ }
86
+ case "backend.failed": {
87
+ return { line: `error: llc (backend) failed on ${a[0]}`, err: true };
88
+ }
89
+ case "verify.broken": {
90
+ return { line: `error: noising broke equivalence on ${a[0]}`, err: true };
91
+ }
92
+ case "arg.one_positional": {
93
+ return { line: `error: expected exactly one <source> argument`, err: true };
94
+ }
95
+ case "cmd.unknown": {
96
+ return { line: `error: unknown command: ${a[0]}`, err: true };
97
+ }
98
+ default: {
99
+ return { line: token, err: true };
100
+ }
101
+ }
102
+ }
103
+
104
+ function emit(token: string): void {
105
+ if (!token) {
106
+ return;
107
+ }
108
+ const { line, err } = render(token);
109
+ if (err) {
110
+ console.error(line);
111
+ } else {
112
+ console.log(line);
113
+ }
114
+ }
115
+
116
+ // --- arg helpers ---
117
+ export function popOption(rest: string[], name: string): { value: string | undefined; rest: string[] } {
118
+ const i = rest.indexOf(name);
119
+ if (i === -1) {
120
+ return { value: undefined, rest };
121
+ }
122
+ return { value: rest[i + 1], rest: rest.slice(0, i).concat(rest.slice(i + 2)) };
123
+ }
124
+
125
+ export function onePositional(rest: string[]): string | undefined {
126
+ const positionals = rest.filter((a) => !a.startsWith("--"));
127
+ if (positionals.length !== 1) {
128
+ return undefined;
129
+ }
130
+ return positionals[0];
131
+ }
132
+
133
+ // --- commands ---
134
+ function cmdCheck(rest: string[]): number {
135
+ const src = onePositional(rest);
136
+ if (src === undefined) {
137
+ console.error("error: expected exactly one <source> argument");
138
+ return 1;
139
+ }
140
+ const { token, status } = engine(["check", src]);
141
+ emit(token);
142
+ return status;
143
+ }
144
+
145
+ function cmdAdd(rest: string[]): number {
146
+ const opt = popOption(rest, "--level");
147
+ const src = onePositional(opt.rest);
148
+ if (src === undefined) {
149
+ console.error("error: expected exactly one <source> argument");
150
+ return 1;
151
+ }
152
+ if (!existsSync(src)) {
153
+ console.error(`error: file not found: ${src}`);
154
+ return 1;
155
+ }
156
+ const levels = opt.value ? opt.value.split(",").map((s) => s.trim()).filter(Boolean) : ["L3"];
157
+ const units = readStage().filter((u) => u.path !== src);
158
+ units.push({ path: src, levels });
159
+ writeStage(units);
160
+ console.log(`staged: ${src} [${showLevels(levels)}]`);
161
+ return 0;
162
+ }
163
+
164
+ function cmdDrop(rest: string[]): number {
165
+ const src = onePositional(rest);
166
+ if (src === undefined) {
167
+ console.error("error: expected exactly one <source> argument");
168
+ return 1;
169
+ }
170
+ const units = readStage();
171
+ const kept = units.filter((u) => u.path !== src);
172
+ if (kept.length === units.length) {
173
+ console.error(`error: not staged: ${src}`);
174
+ return 1;
175
+ }
176
+ writeStage(kept);
177
+ console.log(`dropped: ${src}`);
178
+ return 0;
179
+ }
180
+
181
+ function cmdList(): number {
182
+ const units = readStage();
183
+ if (units.length === 0) {
184
+ console.log("nothing staged");
185
+ return 0;
186
+ }
187
+ for (const u of units) {
188
+ console.log(` ${u.path} [${showLevels(u.levels)}]`);
189
+ }
190
+ return 0;
191
+ }
192
+
193
+ function cmdEnshell(): number {
194
+ const units = readStage();
195
+ if (units.length === 0) {
196
+ console.log("nothing staged");
197
+ return 0;
198
+ }
199
+ let code = 0;
200
+ for (const u of units) {
201
+ const { token, status } = engine(["enshell", u.path]);
202
+ emit(token);
203
+ if (status !== 0) {
204
+ code = status;
205
+ }
206
+ }
207
+ writeStage([]); // 1-shot: staging is consumed by enshell
208
+ console.log(`enshell complete: ${units.length} unit(s); staging cleared`);
209
+ return code;
210
+ }
211
+
212
+ function main(argv: string[]): number {
213
+ const [cmd, ...rest] = argv;
214
+ if (cmd === "-v" || cmd === "--version" || cmd === "version") {
215
+ console.log(pkg.version);
216
+ return 0;
217
+ }
218
+ if (cmd === undefined || cmd === "help" || cmd === "-h" || cmd === "--help") {
219
+ console.log(USAGE);
220
+ return 0;
221
+ }
222
+ switch (cmd) {
223
+ case "check": {
224
+ return cmdCheck(rest);
225
+ }
226
+ case "add": {
227
+ return cmdAdd(rest);
228
+ }
229
+ case "drop": {
230
+ return cmdDrop(rest);
231
+ }
232
+ case "list": {
233
+ return cmdList();
234
+ }
235
+ case "enshell": {
236
+ return cmdEnshell();
237
+ }
238
+ default: {
239
+ console.error(`error: unknown command: ${cmd}`);
240
+ console.error(USAGE);
241
+ return 1;
242
+ }
243
+ }
244
+ }
245
+
246
+ // Run only when invoked directly (not when imported by tests).
247
+ if (process.argv[1] === fileURLToPath(import.meta.url)) {
248
+ process.exit(main(process.argv.slice(2)));
249
+ }
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
- ]