@handfly/sandbox 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 VISTA CONSULTORES S.A. de C.V.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,8 @@
1
+ export interface Contract {
2
+ canBeNone: boolean;
3
+ /** Lines (in the file) that prove a None return; empty when it cannot be None. */
4
+ lines: number[];
5
+ /** Why, per line: "bare_return" | "return_none" | "falls_off_end" | "first" | "get" | "next_default" | "getattr_default" | "regex". */
6
+ reasons: Record<string, string>;
7
+ }
8
+ export declare function pythonContract(source: string, startLine: number, endLine: number): Promise<Contract | null>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * N11 "Can it be None?": read a function's contract from its code. A function that returns a value on some path
3
+ * can also return None when another path returns nothing, returns None explicitly, or returns something that is
4
+ * None by its own contract (`.first()`, `dict.get(k)`, `next(it, None)`, `getattr(o, n, None)`, `re.match`).
5
+ * The proof is the line of that path. Structural evidence; Python in v1.
6
+ */
7
+ import { getParser } from "@handfly/indexer";
8
+ const isNode = (n) => n !== null;
9
+ const kids = (n) => n.namedChildren.filter(isNode);
10
+ function noneish(expr) {
11
+ if (expr.type === "none")
12
+ return "return_none";
13
+ if (expr.type !== "call")
14
+ return null;
15
+ const fn = expr.childForFieldName("function");
16
+ const args = kids(expr.childForFieldName("arguments"));
17
+ const attr = fn?.type === "attribute" ? fn.childForFieldName("attribute")?.text : undefined;
18
+ if (attr === "first" || attr === "last")
19
+ return "first";
20
+ if (attr === "get" && args.length === 1)
21
+ return "get";
22
+ if (fn?.text === "next" && args.length === 2 && args[1].type === "none")
23
+ return "next_default";
24
+ if (fn?.text === "getattr" && args.length === 3 && args[2].type === "none")
25
+ return "getattr_default";
26
+ if (/^re\.(match|search|fullmatch)$/.test(fn?.text ?? ""))
27
+ return "regex";
28
+ return null;
29
+ }
30
+ function terminates(stmt) {
31
+ if (!stmt)
32
+ return false;
33
+ if (stmt.type === "return_statement" || stmt.type === "raise_statement")
34
+ return true;
35
+ if (stmt.type === "if_statement") {
36
+ const alt = kids(stmt).filter((k) => k.type === "else_clause");
37
+ if (!alt.length)
38
+ return false;
39
+ const blocks = [stmt.childForFieldName("consequence"), ...kids(stmt).filter((k) => k.type === "elif_clause").map((e) => e.childForFieldName("consequence")), alt[0].childForFieldName("body")];
40
+ return blocks.every((b) => b && terminates(kids(b).at(-1)));
41
+ }
42
+ if (stmt.type === "with_statement")
43
+ return terminates(kids(stmt.childForFieldName("body")).at(-1));
44
+ if (stmt.type === "while_statement" && stmt.childForFieldName("condition")?.text === "True")
45
+ return true;
46
+ return false;
47
+ }
48
+ export async function pythonContract(source, startLine, endLine) {
49
+ const parser = await getParser("python");
50
+ const tree = parser.parse(source);
51
+ let fn = null;
52
+ const find = (n) => {
53
+ if (fn)
54
+ return;
55
+ if (n.type === "function_definition" && n.startPosition.row + 1 === startLine)
56
+ fn = n;
57
+ else
58
+ for (const c of kids(n))
59
+ if (c.startPosition.row + 1 <= startLine && c.endPosition.row + 1 >= startLine)
60
+ find(c);
61
+ };
62
+ find(tree.rootNode);
63
+ if (!fn) {
64
+ tree.delete();
65
+ return null;
66
+ }
67
+ const f = fn;
68
+ const reasons = {};
69
+ let valueReturns = 0;
70
+ const visit = (n) => {
71
+ if (n.type === "function_definition" && n !== f)
72
+ return; // nested defs have their own contract
73
+ if (n.type === "lambda")
74
+ return;
75
+ if (n.type === "return_statement") {
76
+ const v = kids(n)[0];
77
+ const line = String(n.startPosition.row + 1);
78
+ if (!v)
79
+ reasons[line] = "bare_return";
80
+ else {
81
+ const why = noneish(v);
82
+ if (why)
83
+ reasons[line] = why;
84
+ if (v.type !== "none")
85
+ valueReturns++;
86
+ }
87
+ }
88
+ for (const c of kids(n))
89
+ visit(c);
90
+ };
91
+ visit(f.childForFieldName("body"));
92
+ const body = kids(f.childForFieldName("body"));
93
+ if (valueReturns > 0 && !terminates(body.at(-1)))
94
+ reasons[String(Math.min(endLine, f.endPosition.row + 1))] = "falls_off_end";
95
+ tree.delete();
96
+ if (valueReturns === 0)
97
+ return null; // a procedure: nothing to ask about its return value
98
+ const lines = Object.keys(reasons).map(Number).sort((a, b) => a - b);
99
+ return { canBeNone: lines.length > 0, lines, reasons };
100
+ }
101
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"contract.js","sourceRoot":"","sources":["../src/contract.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAG7C,MAAM,MAAM,GAAG,CAAC,CAAc,EAAa,EAAE,CAAC,CAAC,KAAK,IAAI,CAAC;AACzD,MAAM,IAAI,GAAG,CAAC,CAAO,EAAE,EAAE,CAAC,CAAC,CAAC,aAAa,CAAC,MAAM,CAAC,MAAM,CAA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AAK,CAAC,MAAM,GAAG,CAAC,EAAE,KAAK,EAAE,OAAO,EAAE,CAAC;AACzD,CAAC"}
@@ -0,0 +1,47 @@
1
+ export declare const LIMITS: {
2
+ readonly cpus: "2";
3
+ readonly memory: "2g";
4
+ readonly pids: 256;
5
+ readonly wallSeconds: 30;
6
+ readonly tmpfsMb: 256;
7
+ };
8
+ export interface RunSpec {
9
+ image: string;
10
+ cmd: string[];
11
+ workdir?: string;
12
+ /** host path -> container path, always mounted read-only */
13
+ mounts?: Array<{
14
+ host: string;
15
+ container: string;
16
+ }>;
17
+ env?: Record<string, string>;
18
+ timeoutSeconds?: number;
19
+ network?: string;
20
+ }
21
+ export interface RunResult {
22
+ exitCode: number;
23
+ stdout: string;
24
+ stderr: string;
25
+ timedOut: boolean;
26
+ durationMs: number;
27
+ runtime: "runsc" | "runc";
28
+ }
29
+ export declare class SandboxUnavailable extends Error {
30
+ }
31
+ export interface Engine {
32
+ runtime: "runsc" | "runc";
33
+ podman: boolean;
34
+ selinux: boolean;
35
+ }
36
+ /**
37
+ * Docker or Podman (including podman's docker emulation). gVisor (runsc) when the engine offers it;
38
+ * on SELinux hosts bind mounts are relabelled so the container can read them.
39
+ */
40
+ export declare function detectEngine(): Promise<Engine>;
41
+ export declare function detectRuntime(): Promise<"runsc" | "runc">;
42
+ export declare function sandboxArgs(spec: RunSpec, runtime: "runsc" | "runc", name: string, engine?: Engine): string[];
43
+ export declare function run(spec: RunSpec): Promise<RunResult>;
44
+ export declare function imageExists(tag: string): Promise<boolean>;
45
+ export declare function imageDigest(tag: string): Promise<string>;
46
+ /** Build an image (the only step with network, and only for dependency installation). */
47
+ export declare function build(contextDir: string, tag: string, dockerfile?: string, buildArgs?: Record<string, string>): Promise<string>;
package/dist/driver.js ADDED
@@ -0,0 +1,108 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ export const LIMITS = { cpus: "2", memory: "2g", pids: 256, wallSeconds: 30, tmpfsMb: 256 };
3
+ export class SandboxUnavailable extends Error {
4
+ }
5
+ function sh(cmd, args) {
6
+ return new Promise((resolve, reject) => execFile(cmd, args, { maxBuffer: 16 * 1024 * 1024 }, (err, out, errOut) => (err ? reject(new Error(errOut || err.message)) : resolve(out))));
7
+ }
8
+ let engineCache = null;
9
+ /**
10
+ * Docker or Podman (including podman's docker emulation). gVisor (runsc) when the engine offers it;
11
+ * on SELinux hosts bind mounts are relabelled so the container can read them.
12
+ */
13
+ export function detectEngine() {
14
+ engineCache ??= sh("docker", ["info"])
15
+ .then(async (info) => {
16
+ const version = await sh("docker", ["--version"]).catch(() => "");
17
+ const podman = /podman/i.test(version) || /podman/i.test(info);
18
+ return {
19
+ // HANDFLY_SANDBOX_RUNTIME=runsc pins gVisor (cloud runner): a missing runsc then fails closed, never falls back.
20
+ runtime: process.env.HANDFLY_SANDBOX_RUNTIME === "runsc" || /runsc/.test(info) ? "runsc" : "runc",
21
+ podman,
22
+ selinux: /selinux(enabled)?:\s*true|selinux/i.test(info) && podman,
23
+ };
24
+ })
25
+ .catch(() => {
26
+ engineCache = null;
27
+ throw new SandboxUnavailable("No container engine is running: only structural questions can be generated.");
28
+ });
29
+ return engineCache;
30
+ }
31
+ export async function detectRuntime() {
32
+ return (await detectEngine()).runtime;
33
+ }
34
+ export function sandboxArgs(spec, runtime, name, engine) {
35
+ const args = [
36
+ "run", "--rm", "--name", name,
37
+ "--network", spec.network ?? "none",
38
+ "--read-only",
39
+ "--tmpfs", `/tmp:rw,size=${LIMITS.tmpfsMb}m,mode=1777`,
40
+ "--cpus", LIMITS.cpus,
41
+ "--memory", LIMITS.memory, "--memory-swap", LIMITS.memory,
42
+ "--pids-limit", String(LIMITS.pids),
43
+ "--cap-drop", "ALL",
44
+ "--security-opt", "no-new-privileges",
45
+ "--user", "65534:65534",
46
+ "--ulimit", "nofile=1024:1024",
47
+ "--ulimit", "fsize=67108864:67108864",
48
+ "-e", "HOME=/tmp", "-e", "PYTHONDONTWRITEBYTECODE=1", "-e", "PYTHONHASHSEED=0", "-e", "TZ=UTC", "-e", "LANG=C.UTF-8",
49
+ ];
50
+ if (runtime === "runsc")
51
+ args.push("--runtime", "runsc");
52
+ for (const [k, v] of Object.entries(spec.env ?? {}))
53
+ args.push("-e", `${k}=${v}`);
54
+ const relabel = engine?.selinux ? ",relabel=shared" : "";
55
+ for (const m of spec.mounts ?? [])
56
+ args.push("--mount", `type=bind,source=${m.host},target=${m.container},readonly${relabel}`);
57
+ if (spec.workdir)
58
+ args.push("--workdir", spec.workdir);
59
+ args.push(spec.image, "timeout", "-s", "KILL", String(spec.timeoutSeconds ?? LIMITS.wallSeconds), ...spec.cmd);
60
+ return args;
61
+ }
62
+ export async function run(spec) {
63
+ const engine = await detectEngine();
64
+ const runtime = engine.runtime;
65
+ const name = `handfly-sbx-${process.pid}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`;
66
+ const args = sandboxArgs(spec, runtime, name, engine);
67
+ const t0 = Date.now();
68
+ const wall = ((spec.timeoutSeconds ?? LIMITS.wallSeconds) + 5) * 1000;
69
+ return new Promise((resolve) => {
70
+ const p = spawn("docker", args, { stdio: ["ignore", "pipe", "pipe"] });
71
+ let out = "";
72
+ let err = "";
73
+ let timedOut = false;
74
+ p.stdout.on("data", (d) => (out.length < 1_000_000 ? (out += d) : null));
75
+ p.stderr.on("data", (d) => (err.length < 200_000 ? (err += d) : null));
76
+ const timer = setTimeout(() => {
77
+ timedOut = true;
78
+ execFile("docker", ["kill", name], () => { });
79
+ }, wall);
80
+ p.on("close", (code) => {
81
+ clearTimeout(timer);
82
+ resolve({ exitCode: code ?? -1, stdout: out, stderr: err, timedOut: timedOut || code === 137, durationMs: Date.now() - t0, runtime });
83
+ });
84
+ });
85
+ }
86
+ export async function imageExists(tag) {
87
+ try {
88
+ await sh("docker", ["image", "inspect", tag, "--format", "{{.Id}}"]);
89
+ return true;
90
+ }
91
+ catch {
92
+ return false;
93
+ }
94
+ }
95
+ export async function imageDigest(tag) {
96
+ return (await sh("docker", ["image", "inspect", tag, "--format", "{{.Id}}"])).trim();
97
+ }
98
+ /** Build an image (the only step with network, and only for dependency installation). */
99
+ export function build(contextDir, tag, dockerfile, buildArgs = {}) {
100
+ const args = ["build", "-t", tag, "-q"];
101
+ for (const [k, v] of Object.entries(buildArgs))
102
+ args.push("--build-arg", `${k}=${v}`);
103
+ if (dockerfile)
104
+ args.push("-f", dockerfile);
105
+ args.push(contextDir);
106
+ return sh("docker", args);
107
+ }
108
+ //# sourceMappingURL=driver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"driver.js","sourceRoot":"","sources":["../src/driver.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AAErD,MAAM,CAAC,MAAM,MAAM,GAAG,EAAE,IAAI,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,EAAE,GAAG,EAAE,WAAW,EAAE,EAAE,EAAE,OAAO,EAAE,GAAG,EAAW,CAAC;AAsBrG,MAAM,OAAO,kBAAmB,SAAQ,KAAK;CAAG;AAEhD,SAAS,EAAE,CAAC,GAAW,EAAE,IAAc;IACrC,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE,CACrC,QAAQ,CAAC,GAAG,EAAE,IAAI,EAAE,EAAE,SAAS,EAAE,EAAE,GAAG,IAAI,GAAG,IAAI,EAAE,EAAE,CAAC,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,MAAM,IAAI,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAC5I,CAAC;AACJ,CAAC;AAQD,IAAI,WAAW,GAA2B,IAAI,CAAC;AAE/C;;;GAGG;AACH,MAAM,UAAU,YAAY;IAC1B,WAAW,KAAK,EAAE,CAAC,QAAQ,EAAE,CAAC,MAA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,GAAW,EAAE,UAAmB,EAAE,YAAoC,EAAE;IAChH,MAAM,IAAI,GAAG,CAAC,OAAO,EAAE,IAAI,EAAE,GAAG,EAAE,IAAI,CAAC,CAAC;IACxC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC;QAAE,IAAI,CAAC,IAAI,CAAC,aAAa,EAAE,GAAG,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACtF,IAAI,UAAU;QAAE,IAAI,CAAC,IAAI,CAAC,IAAI,EAAE,UAAU,CAAC,CAAC;IAC5C,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC;IACtB,OAAO,EAAE,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AAC5B,CAAC"}
package/dist/env.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Where the runner images live: HANDFLY_SANDBOX_IMAGES, then the copy shipped in the package (`images/`, made by
3
+ * `build`), then the monorepo's `sandbox-images/` (tests and dev from source).
4
+ */
5
+ export declare function resolveImagesDir(pkgRoot?: string, override?: string | undefined): string;
6
+ /** Content-addressed: editing the runner Dockerfile or harness yields a new tag, so no host keeps a stale harness. */
7
+ export declare const BASE_PY: string;
8
+ export interface PyEnv {
9
+ image: string;
10
+ pyRoot: string;
11
+ }
12
+ /** HANDFLY_SANDBOX_BASE overrides the base Python image (e.g. a locally cached or mirrored image). */
13
+ export declare function ensureBaseImage(): Promise<void>;
14
+ /**
15
+ * `prepare`: build the dependency layer for this repo from its lockfiles only. This is the only step that
16
+ * touches the network, it never sees source code, and its image is cached by lockfile hash.
17
+ */
18
+ export declare function preparePython(repoRoot: string, pyRoot: string): Promise<PyEnv>;
19
+ /** Read-only snapshot of the tracked tree (APFS clone on macOS, reflink on Linux, plain copy otherwise). */
20
+ export declare function snapshot(repoRoot: string, workDir: string, snapshotHash: string): string;
21
+ export declare const BASE_NODE: string;
22
+ export interface NodeEnv {
23
+ image: string;
24
+ jsRoot: string;
25
+ }
26
+ /** `prepare` for JS/TS: dependencies from package.json + lockfile only, cached by their hash. */
27
+ export declare function prepareNode(repoRoot: string, jsRoot: string): Promise<NodeEnv>;
package/dist/env.js ADDED
@@ -0,0 +1,143 @@
1
+ import { createHash } from "node:crypto";
2
+ import { cpSync, existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { dirname, join, resolve } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { execFileSync } from "node:child_process";
7
+ import { build, imageExists } from "./driver.js";
8
+ const PKG_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
9
+ /**
10
+ * Where the runner images live: HANDFLY_SANDBOX_IMAGES, then the copy shipped in the package (`images/`, made by
11
+ * `build`), then the monorepo's `sandbox-images/` (tests and dev from source).
12
+ */
13
+ export function resolveImagesDir(pkgRoot = PKG_ROOT, override = process.env.HANDFLY_SANDBOX_IMAGES) {
14
+ const candidates = [override, join(pkgRoot, "images"), resolve(pkgRoot, "../../sandbox-images")].filter((c) => !!c);
15
+ const found = candidates.find((c) => existsSync(join(c, "py-runner", "Dockerfile")));
16
+ if (!found)
17
+ throw new Error(`@handfly/sandbox: runner images not found (looked in ${candidates.join(", ")})`);
18
+ return found;
19
+ }
20
+ const IMAGES = resolveImagesDir();
21
+ /** Content-addressed: editing the runner Dockerfile or harness yields a new tag, so no host keeps a stale harness. */
22
+ export const BASE_PY = `handfly/py-runner:${createHash("sha256")
23
+ .update(readFileSync(join(IMAGES, "py-runner", "Dockerfile")))
24
+ .update(readFileSync(join(IMAGES, "py-runner", "harness.py")))
25
+ .update(readFileSync(join(IMAGES, "py-runner", "hf_queries.py")))
26
+ .update(process.env.HANDFLY_SANDBOX_BASE ?? "")
27
+ .digest("hex")
28
+ .slice(0, 12)}`;
29
+ const LOCKS = ["requirements.txt", "requirements-dev.txt", "requirements/base.txt", "requirements/dev.txt", "requirements/tests.txt", "requirements/test.txt", "pyproject.toml", "poetry.lock", "uv.lock"];
30
+ /** HANDFLY_SANDBOX_BASE overrides the base Python image (e.g. a locally cached or mirrored image). */
31
+ export async function ensureBaseImage() {
32
+ if (await imageExists(BASE_PY))
33
+ return;
34
+ const base = process.env.HANDFLY_SANDBOX_BASE;
35
+ await build(join(IMAGES, "py-runner"), BASE_PY, undefined, base ? { BASE: base } : {});
36
+ }
37
+ /**
38
+ * `prepare`: build the dependency layer for this repo from its lockfiles only. This is the only step that
39
+ * touches the network, it never sees source code, and its image is cached by lockfile hash.
40
+ */
41
+ export async function preparePython(repoRoot, pyRoot) {
42
+ await ensureBaseImage();
43
+ const dir = join(repoRoot, pyRoot);
44
+ const found = LOCKS.filter((l) => existsSync(join(dir, l)));
45
+ const h = createHash("sha256").update(BASE_PY);
46
+ for (const f of found)
47
+ h.update(f).update(readFileSync(join(dir, f)));
48
+ const tag = `handfly/env-py:${h.digest("hex").slice(0, 16)}`;
49
+ if (await imageExists(tag))
50
+ return { image: tag, pyRoot };
51
+ const ctx = mkdtempSync(join(tmpdir(), "hf-env-"));
52
+ for (const f of found) {
53
+ mkdirSync(dirname(join(ctx, f)), { recursive: true });
54
+ cpSync(join(dir, f), join(ctx, f));
55
+ }
56
+ const reqs = found.filter((f) => f.endsWith(".txt"));
57
+ const lines = [`FROM ${BASE_PY}`, "USER 0", "WORKDIR /deps", "COPY . /deps"];
58
+ if (reqs.length)
59
+ lines.push(`RUN pip install ${reqs.map((r) => `-r ${r}`).join(" ")}`);
60
+ else if (found.includes("pyproject.toml"))
61
+ lines.push("RUN pip install . || true");
62
+ lines.push("USER 65534:65534", "WORKDIR /repo");
63
+ writeFileSync(join(ctx, "Dockerfile"), lines.join("\n") + "\n");
64
+ try {
65
+ await build(ctx, tag);
66
+ }
67
+ finally {
68
+ rmSync(ctx, { recursive: true, force: true }); // build context holds only lockfiles; never leave it behind
69
+ }
70
+ return { image: tag, pyRoot };
71
+ }
72
+ /** Read-only snapshot of the tracked tree (APFS clone on macOS, reflink on Linux, plain copy otherwise). */
73
+ export function snapshot(repoRoot, workDir, snapshotHash) {
74
+ const dest = join(workDir, "snapshots", snapshotHash.slice(0, 16));
75
+ if (existsSync(join(dest, ".hf-complete")))
76
+ return dest;
77
+ mkdirSync(dest, { recursive: true });
78
+ let files;
79
+ try {
80
+ files = execFileSync("git", ["ls-files", "-co", "--exclude-standard", "-z"], { cwd: repoRoot, encoding: "utf8", maxBuffer: 256 * 1024 * 1024 })
81
+ .split("\0").filter(Boolean);
82
+ }
83
+ catch {
84
+ files = listAll(repoRoot);
85
+ }
86
+ for (const f of files) {
87
+ if (/(^|\/)\.env(\.|$)|\.pem$|\.key$|id_rsa/.test(f))
88
+ continue; // secrets never enter the sandbox
89
+ const src = join(repoRoot, f);
90
+ if (!existsSync(src))
91
+ continue;
92
+ mkdirSync(dirname(join(dest, f)), { recursive: true });
93
+ try {
94
+ execFileSync("cp", process.platform === "darwin" ? ["-c", src, join(dest, f)] : ["--reflink=auto", src, join(dest, f)], { stdio: "ignore" });
95
+ }
96
+ catch {
97
+ cpSync(src, join(dest, f));
98
+ }
99
+ }
100
+ writeFileSync(join(dest, ".hf-complete"), "");
101
+ return dest;
102
+ }
103
+ function listAll(root, rel = "") {
104
+ const out = [];
105
+ for (const n of readdirSync(join(root, rel), { withFileTypes: true })) {
106
+ if (["node_modules", ".git", ".venv", "venv", "__pycache__"].includes(n.name))
107
+ continue;
108
+ const r = rel ? `${rel}/${n.name}` : n.name;
109
+ if (n.isDirectory())
110
+ out.push(...listAll(root, r));
111
+ else
112
+ out.push(r);
113
+ }
114
+ return out;
115
+ }
116
+ export const BASE_NODE = process.env.HANDFLY_SANDBOX_NODE_BASE ?? "node:22-alpine";
117
+ /** `prepare` for JS/TS: dependencies from package.json + lockfile only, cached by their hash. */
118
+ export async function prepareNode(repoRoot, jsRoot) {
119
+ const dir = join(repoRoot, jsRoot);
120
+ const files = ["package.json", "package-lock.json", "npm-shrinkwrap.json", "pnpm-lock.yaml", "yarn.lock"].filter((f) => existsSync(join(dir, f)));
121
+ const h = createHash("sha256");
122
+ for (const f of files)
123
+ h.update(f).update(readFileSync(join(dir, f)));
124
+ const tag = `handfly/env-node:${h.digest("hex").slice(0, 16)}`;
125
+ if (await imageExists(tag))
126
+ return { image: tag, jsRoot };
127
+ const ctx = mkdtempSync(join(tmpdir(), "hf-env-"));
128
+ for (const f of files)
129
+ cpSync(join(dir, f), join(ctx, f));
130
+ const install = files.includes("pnpm-lock.yaml") ? "corepack enable && pnpm install --frozen-lockfile --ignore-scripts"
131
+ : files.includes("yarn.lock") ? "corepack enable && yarn install --frozen-lockfile --ignore-scripts"
132
+ : files.includes("package-lock.json") ? "npm ci --ignore-scripts --no-audit --no-fund"
133
+ : "npm install --ignore-scripts --no-audit --no-fund";
134
+ writeFileSync(join(ctx, "Dockerfile"), [`FROM ${BASE_NODE}`, "WORKDIR /app", "COPY . /app", `RUN ${install}`, "USER 65534:65534"].join("\n") + "\n");
135
+ try {
136
+ await build(ctx, tag);
137
+ }
138
+ finally {
139
+ rmSync(ctx, { recursive: true, force: true });
140
+ }
141
+ return { image: tag, jsRoot };
142
+ }
143
+ //# sourceMappingURL=env.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"env.js","sourceRoot":"","sources":["../src/env.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,SAAS,EAAE,WAAW,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AACvH,OAAO,EAAE,MAAM,EAAE,MAAM,SAAS,CAAC;AACjC,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnD,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAC;AACzC,OAAO,EAAE,YAAY,EAAE,MAAM,oBAAoB,CAAC;AAClD,OA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AI,CAAC,MAAM,EAAE,EAAE,SAAS,CAAC,CAAC,CAAC;IACnD,KAAK,MAAM,CAAC,IAAI,KAAK;QAAE,MAAM,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAI,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC;IAC1D,MAAM,OAAO,GAAG,KAAK,CAAC,QAAQ,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,oEAAoE;QACrH,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,oEAAoE;YACpG,CAAC,CAAC,KAAK,CAAC,QAAQ,CAAC,mBAAmB,CAAC,CAAC,CAAC,CAAC,8CAA8C;gBACtF,CAAC,CAAC,mDAAmD,CAAC;IACxD,aAAa,CAAC,IAAI,CAAC,GAAG,EAAE,YAAY,CAAC,EAAE,CAAC,QAAQ,SAAS,EAAE,EAAE,cAAc,EAAE,aAAa,EAAE,OAAO,OAAO,EAAE,EAAE,kBAAkB,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,IAAI,CAAC,CAAC;IACrJ,IAAI,CAAC;QACH,MAAM,KAAK,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC;IACxB,CAAC;YAAS,CAAC;QACT,MAAM,CAAC,GAAG,EAAE,EAAE,SAAS,EAAE,IAAI,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAChD,CAAC;IACD,OAAO,EAAE,KAAK,EAAE,GAAG,EAAE,MAAM,EAAE,CAAC;AAChC,CAAC"}
@@ -0,0 +1,11 @@
1
+ export { LIMITS, SandboxUnavailable, build, detectEngine, detectRuntime, imageDigest, imageExists, run, sandboxArgs, type Engine, type RunResult, type RunSpec } from "./driver.js";
2
+ export { BASE_NODE, BASE_PY, ensureBaseImage, prepareNode, preparePython, snapshot, type NodeEnv, type PyEnv } from "./env.js";
3
+ export { mutantsFor, pythonMutants, syntacticallyValid, typescriptMutants, type Mutant, type Operator } from "./mutate.js";
4
+ export { runHarness, runPytest, runVitest } from "./pytest.js";
5
+ export { CLOZE_BLANK, buildExecutionItems, display, failureEvidence, type ExecutionItems, type LocalFragment, type LocalRecipe } from "./items.js";
6
+ export { runLocalRecipe, type LocalOutcome } from "./local.js";
7
+ export { VULN_CLASSES, pythonVulnMutants, type VulnClass } from "./security.js";
8
+ export { pythonContract, type Contract } from "./contract.js";
9
+ export { COST_CLASSES, costClass, parsonsBlocks, safeRefactors } from "./items.js";
10
+ export { assembleParsons } from "./local.js";
11
+ export { RACE_INITIAL, allSchedules, parseRaceOutput, pythonRaces, raceScript, simulateRace, type RaceModel, type RaceTrace } from "./race.js";
package/dist/index.js ADDED
@@ -0,0 +1,12 @@
1
+ export { LIMITS, SandboxUnavailable, build, detectEngine, detectRuntime, imageDigest, imageExists, run, sandboxArgs } from "./driver.js";
2
+ export { BASE_NODE, BASE_PY, ensureBaseImage, prepareNode, preparePython, snapshot } from "./env.js";
3
+ export { mutantsFor, pythonMutants, syntacticallyValid, typescriptMutants } from "./mutate.js";
4
+ export { runHarness, runPytest, runVitest } from "./pytest.js";
5
+ export { CLOZE_BLANK, buildExecutionItems, display, failureEvidence } from "./items.js";
6
+ export { runLocalRecipe } from "./local.js";
7
+ export { VULN_CLASSES, pythonVulnMutants } from "./security.js";
8
+ export { pythonContract } from "./contract.js";
9
+ export { COST_CLASSES, costClass, parsonsBlocks, safeRefactors } from "./items.js";
10
+ export { assembleParsons } from "./local.js";
11
+ export { RACE_INITIAL, allSchedules, parseRaceOutput, pythonRaces, raceScript, simulateRace } from "./race.js";
12
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,kBAAkB,EAAE,KAAK,EAAE,YAAY,EAAE,aAAa,EAAE,WAAW,EAAE,WAAW,EAAE,GAAG,EAAE,WAAW,EAA6C,MAAM,aAAa,CAAC;AACpL,OAAO,EAAE,SAAS,EAAE,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,aAAa,EAAE,QAAQ,EAA4B,MAAM,UAAU,CAAC;AAC/H,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,kBAAkB,EAAE,iBAAiB,EAA8B,MAAM,aAAa,CAAC;AAC3H,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,SAAS,EAAE,MAAM,aAAa,CAAC;AAC/D,OAAO,EAAE,WAAW,EAAE,mBAAmB,EAAE,OAAO,EAAE,eAAe,EAA6D,MAAM,YAAY,CAAC;AACnJ,OAAO,EAAE,cAAc,EAAqB,MAAM,YAAY,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,iBAAiB,EAAkB,MAAM,eAAe,CAAC;AAChF,OAAO,EAAE,cAAc,EAAiB,MAAM,eAAe,CAAC;AAC9D,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AACnF,OAAO,EAAE,eAAe,EAAE,MAAM,YAAY,CAAC;AAC7C,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,WAAW,EAAE,UAAU,EAAE,YAAY,EAAkC,MAAM,WAAW,CAAC"}
@@ -0,0 +1,90 @@
1
+ import type { RepoIndex, RNode } from "@handfly/indexer";
2
+ import type { ItemSpec } from "@handfly/protocol";
3
+ import { type Mutant } from "./mutate.js";
4
+ export interface LocalFragment {
5
+ path: string;
6
+ start_line: number;
7
+ end_line: number;
8
+ text: string;
9
+ /** Run evidence shown beside the code (failure triage): the real failing-test trace. */
10
+ evidence?: string;
11
+ }
12
+ /** Header line of each context-code section in a query-count item's evidence: `⟦FILE path:start⟧`. */
13
+ export declare const QUERY_SECTION: (path: string, start: number) => string;
14
+ /** Marker for the blank in cloze items; the web renders an input in its place. */
15
+ export declare const CLOZE_BLANK = "\u27E6BLANK\u27E7";
16
+ /** How the learner's CLI re-runs an answer against their own code (`handfly verify`). Never uploaded. */
17
+ export interface LocalRecipe {
18
+ kind: "reverse_trace" | "kill_mutant" | "fix_bug" | "bug_test" | "regen" | "parsons";
19
+ path: string;
20
+ qual: string;
21
+ pyRoot: string;
22
+ snapshot: string;
23
+ /** sha256 of the file when the item was made: a changed file cannot be judged against the old question. */
24
+ sourceSha: string;
25
+ mutant?: {
26
+ start: number;
27
+ end: number;
28
+ replacement: string;
29
+ };
30
+ /** fix_bug: the function's lines in the mutated file, and the tests that must pass after the learner's patch. */
31
+ span?: [number, number];
32
+ tests?: string[];
33
+ /** bug_test: repo-relative directory where the learner's test file is placed (next to the tests that caught it). */
34
+ testDir?: string;
35
+ /** parsons: the def line, then the shuffled blocks (stripped of indentation), distractors included. */
36
+ blocks?: string[];
37
+ }
38
+ export interface ExecutionItems {
39
+ specs: ItemSpec[];
40
+ /** Mutated code shown to the learner; kept on disk locally, uploaded only as an approved fragment. */
41
+ local: Record<string, LocalFragment>;
42
+ /** Recipes for answers that run on the learner's machine, by item fingerprint. */
43
+ recipes: Record<string, LocalRecipe>;
44
+ /** M3: functions whose tests pass, by node id. An explanation of one can be checked by regenerating it. */
45
+ regen: Record<string, LocalRecipe>;
46
+ log: string[];
47
+ }
48
+ export declare function display(canon: string): string;
49
+ /**
50
+ * Seeded bugs (F-301) and output prediction (F-302), both verified by execution in the sandbox.
51
+ * Python only in v1. Returns nothing (and says why) when Docker is unavailable.
52
+ */
53
+ export declare function buildExecutionItems(index: RepoIndex, root: string, workDir: string, opts?: {
54
+ maxBugs?: number;
55
+ maxPredictions?: number;
56
+ maxQueries?: number;
57
+ maxVulns?: number;
58
+ maxCost?: number;
59
+ maxSpot?: number;
60
+ maxParsons?: number;
61
+ maxContracts?: number;
62
+ maxRaces?: number;
63
+ onLog?: (s: string) => void;
64
+ }): Promise<ExecutionItems>;
65
+ /** A minimal unified diff of one function, original vs changed, with real line numbers. */
66
+ export declare function unifiedDiff(path: string, before: string, after: string, start: number, end: number, endAfter: number): string;
67
+ /** 0-based indexes of the added or removed rows of a unified diff (headers excluded). */
68
+ export declare function changedRows(diff: string): number[];
69
+ /** The first failure's section of `pytest --tb=short` output: frames and the assertion, capped at 3.5 KB. */
70
+ export declare function failureEvidence(stdout: string): string | null;
71
+ /** N9: a function of 4-9 simple lines (no docstring, no continuation lines) as shuffled blocks + 1 distractor. */
72
+ export declare function parsonsBlocks(source: string, n: RNode, killed: Mutant[]): {
73
+ lines: string[];
74
+ order: number[];
75
+ indents: number[];
76
+ distractors: number[];
77
+ } | null;
78
+ export declare const COST_CLASSES: readonly ["O(1)", "O(log n)", "O(n)", "O(n log n)", "O(n²)"];
79
+ /** Fit the growth of the hottest line (not the def line) across n = 10, 100, 1000. Null when the fit is ambiguous. */
80
+ export declare function costClass(c10: Record<string, number>, c100: Record<string, number>, c1000: Record<string, number>, defLine: number): {
81
+ line: number;
82
+ cls: (typeof COST_CLASSES)[number];
83
+ counts: [number, number, number];
84
+ } | null;
85
+ /** Behaviour-preserving edits for N7: flip a comparison (a < b -> b > a), or `x = x + y` -> `x += y` on a name.
86
+ * Never on the broken mutant's own line, so the two versions differ in different places. */
87
+ export declare function safeRefactors(source: string, n: RNode, avoid: Mutant): Array<{
88
+ kind: string;
89
+ text: string;
90
+ }>;