@mobcomputing/mob 0.0.0-stage → 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,29 @@
1
+ // Mob's contract for this example: topWords must return exactly what it
2
+ // returns today, for every recorded input, and get faster.
3
+ const SYLLABLES = ['ka', 'mo', 'bu', 'ré', 'SH', 'ü', 'tion', '数', '据', 'x', '7', 'la', 'pe', 'n']
4
+
5
+ // A small deterministic random source, so the recorded inputs never change.
6
+ function rng(seed) {
7
+ let s = seed >>> 0
8
+ return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32)
9
+ }
10
+
11
+ export default {
12
+ entry: 'index.js',
13
+ goal: 'faster',
14
+ inputs() {
15
+ const r = rng(7)
16
+ const out = [['', 3], [' ', 1], ['One one ONE two', 5], ['a-b_c d', 0], ['Ünïcödé ünïcödé', 2]]
17
+ for (let i = 0; i < 300; i++) {
18
+ const len = Math.floor(r() * (i % 10 === 0 ? 3000 : 200))
19
+ const word = () => Array.from({ length: 1 + Math.floor(r() * 3) }, () => SYLLABLES[Math.floor(r() * SYLLABLES.length)]).join('')
20
+ const words = Array.from({ length: len }, word)
21
+ const seps = [' ', ' ', ', ', '\n', '!? ', '—']
22
+ out.push([words.map((w, k) => w + seps[k % seps.length]).join(''), 1 + Math.floor(r() * 12)])
23
+ }
24
+ return out
25
+ },
26
+ run(lib, [text, n]) {
27
+ return lib.topWords(text, n)
28
+ }
29
+ }
@@ -0,0 +1,11 @@
1
+ # wordfreq-py
2
+
3
+ The `wordfreq` example in Python: `top_words` is deliberately slow, so a swarm has something to speed up.
4
+
5
+ ```sh
6
+ cp -r "$(npm root -g)/@mobcomputing/mob/examples/wordfreq-py" /tmp/wordfreq-py && cd /tmp/wordfreq-py
7
+ git init -q -b main && git add -A && git commit -qm wordfreq-py
8
+ mob init
9
+ ```
10
+
11
+ Mob runs each version of the code in its own `python3` process. Network access, new processes and writing files are refused while the gate runs your code. Python's audit hooks stop accidents, not a determined attacker, so run swarms you don't trust in a container or VM.
@@ -0,0 +1,29 @@
1
+ // Mob's contract for this example: top_words must return exactly what it
2
+ // returns today, for every recorded input, and get faster.
3
+ const SYLLABLES = ['ka', 'mo', 'bu', 'ré', 'SH', 'ü', 'tion', '数', '据', 'x', '7', 'la', 'pe', 'n']
4
+
5
+ // A small deterministic random source, so the recorded inputs never change.
6
+ function rng(seed) {
7
+ let s = seed >>> 0
8
+ return () => ((s = (s * 1664525 + 1013904223) >>> 0) / 2 ** 32)
9
+ }
10
+
11
+ export default {
12
+ language: 'python',
13
+ entry: 'wordfreq.py',
14
+ function: 'top_words',
15
+ goal: 'faster',
16
+ inputs() {
17
+ const r = rng(7)
18
+ const out = [['', 3], [' ', 1], ['One one ONE two', 5], ['a-b_c d', 0], ['Ünïcödé ünïcödé', 2]]
19
+ for (let i = 0; i < 300; i++) {
20
+ const len = Math.floor(r() * (i % 10 === 0 ? 3000 : 200))
21
+ const word = () => Array.from({ length: 1 + Math.floor(r() * 3) }, () => SYLLABLES[Math.floor(r() * SYLLABLES.length)]).join('')
22
+ const words = Array.from({ length: len }, word)
23
+ const seps = [' ', ' ', ', ', '\n', '!? ', '—']
24
+ out.push([words.map((w, k) => w + seps[k % seps.length]).join(''), 1 + Math.floor(r() * 12)])
25
+ }
26
+ return out
27
+ }
28
+ // Each input is [text, n]; a list is passed to top_words as its arguments.
29
+ }
@@ -0,0 +1,19 @@
1
+ import re
2
+
3
+
4
+ def top_words(text, n):
5
+ """The n most frequent words in a text, most frequent first; ties are
6
+ broken alphabetically. Words are lowercase runs of letters and digits.
7
+ Deliberately slow, so a swarm has something to speed up."""
8
+ words = [w for w in re.split(r"[\W_]+", text.lower()) if w]
9
+ seen = []
10
+ counts = []
11
+ for word in words:
12
+ if word in seen:
13
+ counts[seen.index(word)] += 1
14
+ else:
15
+ seen.append(word)
16
+ counts.append(1)
17
+ pairs = list(zip(seen, counts))
18
+ pairs.sort(key=lambda p: (-p[1], p[0]))
19
+ return [f"{word} {count}" for word, count in pairs[:n]]
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@mobcomputing/mob",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.1",
4
+ "description": "Fuck it, push to main. A merge gate that lets agent swarms push straight to main and refuses anything that breaks.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "mob": "bin/mob.mjs"
9
+ },
10
+ "files": [
11
+ "bin",
12
+ "src",
13
+ "examples"
14
+ ],
15
+ "engines": {
16
+ "node": ">=22.13"
17
+ },
18
+ "scripts": {
19
+ "test": "node --test test/"
20
+ },
21
+ "repository": {
22
+ "type": "git",
23
+ "url": "git+https://github.com/knownquantity/Mob.git"
24
+ },
25
+ "homepage": "https://mob.computer",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/knownquantity/Mob/issues"
31
+ },
32
+ "keywords": [
33
+ "agents",
34
+ "swarm",
35
+ "merge-gate",
36
+ "ai",
37
+ "coding-agents",
38
+ "git"
39
+ ]
40
+ }
@@ -0,0 +1,12 @@
1
+ <!-- mob:start -->
2
+ ## Landing changes: Mob
3
+
4
+ This repo's main branch is guarded by Mob (https://mob.computer). There is no code review and there are no pull requests: push straight to main through the gate.
5
+
6
+ - Work in a clone whose remote is named `mob` (`git clone -o mob <path to .mob/gate.git>`), or in this repo, which already has it.
7
+ - Push: `git push mob HEAD:main`. Mob runs every recorded input through your commit, and lands it only if every output stays byte-identical{{goal}}.
8
+ - If the push is refused, the reason is printed in the push output (lines starting with `remote: mob:`). Fix it or try a different idea. Do not try to work around the gate.
9
+ - If the push is refused as `stale`, another change landed first: `git pull --rebase mob main`, then push again.
10
+ - Check a commit without landing it: `mob check HEAD`. See progress: `mob status`.
11
+ - Never edit `mob.config.mjs` or anything under `.mob/`; the gate refuses those changes.
12
+ <!-- mob:end -->
@@ -0,0 +1,54 @@
1
+ // Mob's contract for this repo. `mob init` records what the code does now on
2
+ // these inputs; after that, a commit lands on main only if every output stays
3
+ // byte-identical (and, for goal 'faster', it is measurably faster).
4
+ // Commit this file before running `mob init` again. Agents cannot change it:
5
+ // the gate refuses any commit that touches it.
6
+ export default {
7
+ // The module Mob loads from each version of the code, relative to the repo root.
8
+ entry: 'index.js',
9
+
10
+ // For a Python project: language: 'python', entry: 'package/module.py',
11
+ // function: 'name' (the function each input is passed to; a list input is
12
+ // passed as its arguments), and no run(). Mob runs python3, or the python
13
+ // named by `python`, an absolute path (for example a virtualenv's).
14
+ // isolate: true runs each input in a fresh process, for code that carries
15
+ // state from one input to the next.
16
+
17
+ // 'faster': identical outputs and measurably faster than main.
18
+ // 'same': identical outputs only (refactors, cleanups, removing dependencies).
19
+ goal: 'faster',
20
+
21
+ // The inputs to record. Must be JSON-serializable. Cover the real range of
22
+ // use: edge cases, large inputs, unusual characters. More is better.
23
+ inputs() {
24
+ return ['hello world', '', 'Ünïcödé text']
25
+ },
26
+
27
+ // Produce the output for one input. Return a string or any JSON value.
28
+ // Exceptions count as outputs, so they must stay the same too.
29
+ run(lib, input) {
30
+ return lib.default(input)
31
+ },
32
+
33
+ // Optional: more files or folders (ending in /) agents may not change, such
34
+ // as tests or fixtures.
35
+ protect: [],
36
+
37
+ // Optional, for code that must be compiled first (for example a Rust
38
+ // extension module): a command run in each version's folder, inside the
39
+ // sandbox, before its outputs are read. A version that does not build is
40
+ // refused with the build's last lines. `reads` are the toolchain folders
41
+ // it may read, `env` its environment, `cache` folders copied from main's
42
+ // built folder first so builds are incremental.
43
+ // build: { command: ['sh', 'build.sh'], reads: [], env: {}, cache: [], timeoutMs: 900000 },
44
+
45
+ // Agent code runs in an operating-system sandbox: no network, no writes, no
46
+ // view of your home folder, and no API keys from your environment. It needs
47
+ // bubblewrap on Linux (built in on macOS). sandbox: false turns it off; do
48
+ // that only for code you trust.
49
+
50
+ // Optional: more files or folders (ending in /) that are documentation.
51
+ // Commits that change only documentation land without a speed test.
52
+ // Markdown, .txt, LICENSE and CHANGELOG files always count.
53
+ docs: []
54
+ }
package/src/gate.mjs ADDED
@@ -0,0 +1,217 @@
1
+ // The gate: decides whether one commit may land on main.
2
+ // A commit lands only if it touches no protected file, every recorded output
3
+ // stays byte-identical, and (for goal "faster") it is measurably faster than
4
+ // main in two independent timing runs.
5
+ import fs from 'node:fs'
6
+ import path from 'node:path'
7
+ import { execFileSync, spawn } from 'node:child_process'
8
+ import { fileURLToPath } from 'node:url'
9
+ import { pythonPaths, sandboxed, sandboxEnv } from './sandbox.mjs'
10
+
11
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
12
+ const WORKER = path.join(HERE, 'worker.mjs')
13
+
14
+ export function mobPaths(mobDir) {
15
+ return {
16
+ dir: mobDir,
17
+ config: path.join(mobDir, 'config.mjs'),
18
+ inputs: path.join(mobDir, 'inputs.json'),
19
+ expected: path.join(mobDir, 'expected.json'),
20
+ meta: path.join(mobDir, 'meta.json'),
21
+ log: path.join(mobDir, 'log.jsonl'),
22
+ gate: path.join(mobDir, 'gate.git'),
23
+ trees: path.join(mobDir, 'trees'),
24
+ jobs: path.join(mobDir, 'jobs'),
25
+ lock: path.join(mobDir, 'lock'),
26
+ selftest: path.join(mobDir, 'selftest.json')
27
+ }
28
+ }
29
+
30
+ export const readMeta = (p) => JSON.parse(fs.readFileSync(p.meta, 'utf8'))
31
+
32
+ // git without the hook's GIT_DIR leaking into commands aimed at another repo.
33
+ // GIT_OBJECT_DIRECTORY and GIT_ALTERNATE_OBJECT_DIRECTORIES stay, so commits
34
+ // still in a push's quarantine are readable.
35
+ export function git(gitDir, args, options = {}) {
36
+ const env = { ...process.env }
37
+ delete env.GIT_DIR
38
+ delete env.GIT_WORK_TREE
39
+ return execFileSync('git', ['--git-dir', gitDir, ...args], { encoding: 'utf8', maxBuffer: 1 << 28, env, ...options }).trim()
40
+ }
41
+
42
+ // Writes a commit's files to trees/<sha> (once), with the project's
43
+ // node_modules linked in so the code can load its dependencies.
44
+ export function exportTree(p, gitDir, sha, repoRoot) {
45
+ const dest = path.join(p.trees, sha)
46
+ if (fs.existsSync(path.join(dest, '.mob-complete'))) return dest
47
+ fs.rmSync(dest, { recursive: true, force: true })
48
+ fs.mkdirSync(dest, { recursive: true })
49
+ const env = { ...process.env }
50
+ delete env.GIT_DIR
51
+ const tar = execFileSync('git', ['--git-dir', gitDir, 'archive', '--format=tar', sha], { maxBuffer: 1 << 30, env })
52
+ execFileSync('tar', ['-x', '-C', dest], { input: tar })
53
+ // Only buildTree may say a tree is built; a committed marker would skip the build.
54
+ fs.rmSync(path.join(dest, '.mob-built'), { force: true })
55
+ const modules = path.join(repoRoot, 'node_modules')
56
+ // Linked to the real folder: node_modules is often itself a link (pnpm, monorepos).
57
+ if (fs.existsSync(modules) && !fs.existsSync(path.join(dest, 'node_modules'))) fs.symlinkSync(fs.realpathSync(modules), path.join(dest, 'node_modules'))
58
+ fs.writeFileSync(path.join(dest, '.mob-complete'), '')
59
+ return dest
60
+ }
61
+
62
+ // Compiles one tree with the config's `build` command, once, before any of its
63
+ // outputs are read. It runs in the tree's folder inside the OS sandbox: no
64
+ // network, writes only inside the tree (and an empty /tmp), reads only the
65
+ // tree, the paths in build.reads and the Python Mob runs. Folders named in
66
+ // build.cache are copied from `from` (main's built tree) first, so a build
67
+ // can reuse main's compiled dependencies. A command that fails or runs past
68
+ // build.timeoutMs gives { ok: false, reason: 'build-failed' }.
69
+ export function buildTree(meta, tree, from = null) {
70
+ const b = meta.build
71
+ const marker = path.join(tree, '.mob-built')
72
+ if (!b || fs.existsSync(marker)) return Promise.resolve({ ok: true })
73
+ if (from) {
74
+ for (const rel of b.cache ?? []) {
75
+ const src = path.join(from, rel)
76
+ const dest = path.join(tree, rel)
77
+ if (fs.existsSync(src) && !fs.existsSync(dest)) fs.cpSync(src, dest, { recursive: true, verbatimSymlinks: true, preserveTimestamps: true })
78
+ }
79
+ }
80
+ const python = meta.language === 'python' ? meta.python ?? process.env.MOB_PYTHON ?? 'python3' : null
81
+ const env = sandboxEnv({ ...(python && { MOB_PYTHON: pythonPaths(python).exe }), ...b.env })
82
+ const argv = Array.isArray(b.command) ? b.command : ['sh', '-c', b.command]
83
+ const [cmd, args] = meta.sandbox === false ? [argv[0], argv.slice(1)] : sandboxed(argv, { reads: [tree, ...(b.reads ?? [])], writes: [tree], python })
84
+ const timeoutMs = b.timeoutMs ?? 900000
85
+ return new Promise((resolve) => {
86
+ const child = spawn(cmd, args, { cwd: tree, stdio: ['ignore', 'pipe', 'pipe'], env })
87
+ let out = ''
88
+ const keep = (chunk) => { out = (out + chunk).slice(-20000) }
89
+ child.stdout.on('data', keep)
90
+ child.stderr.on('data', keep)
91
+ const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs)
92
+ child.on('close', (code, signal) => {
93
+ clearTimeout(timer)
94
+ if (code === 0) { fs.writeFileSync(marker, ''); return resolve({ ok: true }) }
95
+ const tail = out.trim().split('\n').slice(-15).join('\n').replaceAll(tree, '<tree>')
96
+ resolve({ ok: false, reason: 'build-failed', detail: signal === 'SIGKILL' ? `the build ran past ${timeoutMs / 1000}s` : `the build exited ${code}:\n${tail}` })
97
+ })
98
+ })
99
+ }
100
+
101
+ // Runs one worker job: read access only to the trees it names, the recording,
102
+ // the config snapshot and the project's dependencies.
103
+ export function runJob(p, meta, job, { timeoutMs = 600000, memoryMb = 4096 } = {}) {
104
+ fs.mkdirSync(p.jobs, { recursive: true })
105
+ const file = path.join(p.jobs, `job-${process.pid}-${Math.random().toString(36).slice(2, 10)}.json`)
106
+ // Real paths (no links), so the worker sees and hides the same folder names.
107
+ for (const key of ['lib', 'current']) if (job[key]) job = { ...job, [key]: fs.realpathSync(job[key]) }
108
+ const full = { ...job, memoryMb, config: p.config, inputs: p.inputs, expected: p.expected }
109
+ fs.writeFileSync(file, JSON.stringify(full))
110
+ const modules = path.join(meta.root, 'node_modules')
111
+ const reads = [HERE, p.config, p.inputs, p.expected, file, job.lib, job.current, fs.existsSync(modules) ? fs.realpathSync(modules) : null].filter(Boolean)
112
+ const flags = [`--max-old-space-size=${memoryMb}`, '--single-threaded', '--max-semi-space-size=256', '--expose-gc', '--permission', ...reads.map((r) => `--allow-fs-read=${r}`)]
113
+ if (job.mode === 'record') flags.push(`--allow-fs-write=${job.out}`)
114
+ // Python code runs in runner.py processes the worker starts.
115
+ if (meta.language === 'python') flags.push('--allow-child-process')
116
+ // Coverage is only for recording main at init, which runs the repo owner's
117
+ // own committed code; V8 writes it through the inspector. Node 24+ allows
118
+ // that with --allow-inspector. Node 22 has no such flag and writes no
119
+ // coverage under --permission, so there this one job runs without Node's
120
+ // permission model (still inside the OS sandbox).
121
+ const inspector = process.allowedNodeEnvironmentFlags.has('--allow-inspector')
122
+ if (job.coverage) flags.push(...(inspector ? ['--allow-inspector'] : []), `--allow-fs-write=${job.coverage}`)
123
+ const node = [process.execPath, ...(job.coverage && !inspector ? flags.filter((f) => !/^--(permission|allow-)/.test(f)) : flags), WORKER, file]
124
+ const argv = meta.benchCores && job.mode === 'bench' ? ['taskset', '-c', meta.benchCores, ...node] : node
125
+ // Everything runs inside the operating-system sandbox (src/sandbox.mjs),
126
+ // unless the repo owner turned it off in mob.config.mjs.
127
+ const python = meta.language === 'python' ? meta.python ?? process.env.MOB_PYTHON ?? 'python3' : null
128
+ const env = sandboxEnv({ ...(job.coverage && { NODE_V8_COVERAGE: job.coverage }), ...(python && { MOB_PYTHON: pythonPaths(python).exe }) })
129
+ const [cmd, ...args] = meta.sandbox === false ? argv : sandboxed(argv, { reads, writes: [job.out, job.coverage].filter(Boolean), python }).flat()
130
+ return new Promise((resolve) => {
131
+ const child = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'pipe'], env })
132
+ let out = ''
133
+ let err = ''
134
+ child.stdout.on('data', (chunk) => { out += chunk })
135
+ child.stderr.on('data', (chunk) => { err += chunk })
136
+ const timer = setTimeout(() => child.kill('SIGKILL'), timeoutMs)
137
+ child.on('close', (code, signal) => {
138
+ clearTimeout(timer)
139
+ fs.rmSync(file, { force: true })
140
+ try { return resolve(JSON.parse(out.trim().split('\n').at(-1))) } catch {}
141
+ if (signal === 'SIGKILL') return resolve({ ok: false, reason: 'timeout', detail: `no result within ${timeoutMs / 1000}s`, partial: out })
142
+ resolve({ ok: false, reason: 'crash', detail: `exited ${code}: ${err.trim().split('\n').slice(-3).join(' ').slice(0, 300)}` })
143
+ })
144
+ })
145
+ }
146
+
147
+ const PROTECTED = ['mob.config.mjs', 'mob.inputs.json', '.mob/']
148
+ const isDocs = (file, extra) => /\.(md|markdown|txt)$/i.test(file) || /(^|\/)(LICENSE|AUTHORS|CHANGELOG)[^/]*$/.test(file) || extra.some((rule) => (rule.endsWith('/') ? file.startsWith(rule) : file === rule))
149
+ const isProtected = (file, extra) => [...PROTECTED, ...extra].some((rule) => (rule.endsWith('/') ? file.startsWith(rule) : file === rule))
150
+
151
+ // The full gate for `newSha` against main at `baseSha`. `gitDir` holds both
152
+ // commits. Returns { landed, reason, detail, ... }.
153
+ export async function judge(p, { gitDir, baseSha, newSha, log = () => {} }) {
154
+ const meta = readMeta(p)
155
+ if (baseSha === newSha) return { landed: false, reason: 'no-change', detail: 'the commit is main itself' }
156
+ try { git(gitDir, ['merge-base', '--is-ancestor', baseSha, newSha]) } catch {
157
+ return { landed: false, reason: 'stale', detail: 'not built on the current main; fetch mob main, rebase, and push again' }
158
+ }
159
+ const changed = git(gitDir, ['diff', '--name-only', baseSha, newSha]).split('\n').filter(Boolean)
160
+ if (changed.length === 0) return { landed: false, reason: 'no-change', detail: 'no files differ from main' }
161
+ const touched = changed.filter((file) => isProtected(file, meta.protect ?? []))
162
+ if (touched.length) return { landed: false, reason: 'protected', detail: `changes protected file(s): ${touched.join(', ')}` }
163
+
164
+ const base = exportTree(p, gitDir, baseSha, meta.root)
165
+ const cand = exportTree(p, gitDir, newSha, meta.root)
166
+ if (meta.build) {
167
+ log('building…')
168
+ const built = (await buildTree(meta, base)).ok ? await buildTree(meta, cand, base) : { ok: false, reason: 'build-failed', detail: 'main itself no longer builds on this machine' }
169
+ if (!built.ok) return { landed: false, reason: built.reason, detail: built.detail }
170
+ }
171
+ log('checking recorded outputs…')
172
+ const checked = await runJob(p, meta, { mode: 'check', lib: cand })
173
+ if (!checked.ok) return { landed: false, reason: checked.reason, detail: checked.detail, first: checked.first }
174
+ // Documentation cannot make code faster or slower, so it lands untimed.
175
+ if (changed.every((file) => isDocs(file, meta.docs ?? []))) return { landed: true, reason: 'docs-only', detail: `only documentation changed; all ${meta.inputs} recorded outputs identical` }
176
+ if (meta.goal !== 'faster') return { landed: true, reason: 'identical', detail: `all ${meta.inputs} recorded outputs identical` }
177
+ const timings = []
178
+ for (const run of [1, 2]) {
179
+ log(`timing against main (run ${run} of 2)…`)
180
+ const t = await runJob(p, meta, { mode: 'bench', lib: cand, current: base, samples: meta.samples, minMs: meta.minMs, alpha: meta.alpha })
181
+ if (!t.ok) return { landed: false, reason: t.reason, detail: t.detail }
182
+ timings.push(t)
183
+ if (t.lower < meta.minSpeedup) {
184
+ const reason = run === 1 ? 'not-faster' : 'not-reproducible'
185
+ const detail = `${t.speedup.toFixed(3)}× vs main (95% lower bound ${t.lower.toFixed(3)}×, needs ≥ ${meta.minSpeedup}×)${run === 2 ? ' on the second timing run' : ''}`
186
+ return { landed: false, reason, detail, speedup: t.speedup, lower: t.lower }
187
+ }
188
+ }
189
+ const speedup = Math.min(...timings.map((t) => t.speedup))
190
+ return { landed: true, reason: 'faster', detail: `${speedup.toFixed(3)}× faster than main, all ${meta.inputs} recorded outputs identical`, speedup, lower: Math.min(...timings.map((t) => t.lower)) }
191
+ }
192
+
193
+ // Serializes gate runs: one check at a time, so timings never overlap.
194
+ export async function withLock(p, fn) {
195
+ for (;;) {
196
+ try {
197
+ fs.writeFileSync(p.lock, String(process.pid), { flag: 'wx' })
198
+ break
199
+ } catch {
200
+ const holder = Number(fs.readFileSync(p.lock, 'utf8') || 0)
201
+ let alive = false
202
+ try { process.kill(holder, 0); alive = true } catch {}
203
+ if (!alive) { fs.rmSync(p.lock, { force: true }); continue }
204
+ await new Promise((resolve) => setTimeout(resolve, 250))
205
+ }
206
+ }
207
+ try { return await fn() } finally { fs.rmSync(p.lock, { force: true }) }
208
+ }
209
+
210
+ export function appendLog(p, entry) {
211
+ fs.appendFileSync(p.log, JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n')
212
+ }
213
+
214
+ export function readLog(p) {
215
+ if (!fs.existsSync(p.log)) return []
216
+ return fs.readFileSync(p.log, 'utf8').split('\n').filter(Boolean).map((line) => JSON.parse(line))
217
+ }
package/src/runner.py ADDED
@@ -0,0 +1,163 @@
1
+ # Runs one version of a Python project for Mob's gate. The Node worker starts
2
+ # one runner per version of the code and sends it inputs, one JSON line each;
3
+ # the runner answers each with {"out": <output string>, "ns": <time of the
4
+ # call in nanoseconds>}. It exits when its input ends.
5
+ # python3 -I -B runner.py <tree> <entry.py> <function> [--memory-mb N] [--coverage <file>]
6
+ # The function is called with the input's items as arguments if the input is a
7
+ # list, else with the input itself. A string result is the output as it is;
8
+ # anything else is stored as JSON. An exception is an output too.
9
+ # With --coverage, it writes which lines of the tree's own files ran, the lines
10
+ # that can run, and each function with whether it ran.
11
+ #
12
+ # Candidate code is untrusted. An audit hook refuses network access, new
13
+ # processes and writing files once the code is loaded, so mistakes fail with a
14
+ # clear message. Audit hooks are not a security boundary; the wall is the OS
15
+ # sandbox the whole job runs in (src/sandbox.mjs).
16
+ import ast
17
+ import importlib
18
+ import json
19
+ import os
20
+ import sys
21
+ import threading
22
+ import time
23
+
24
+ tree, entry, function = os.path.realpath(sys.argv[1]), sys.argv[2], sys.argv[3]
25
+ coverage_file = sys.argv[sys.argv.index("--coverage") + 1] if "--coverage" in sys.argv else None
26
+ memory_mb = int(sys.argv[sys.argv.index("--memory-mb") + 1]) if "--memory-mb" in sys.argv else 0
27
+ if memory_mb: # a planted bug can take memory without limit; it gets MemoryError instead
28
+ try:
29
+ import resource
30
+
31
+ resource.setrlimit(resource.RLIMIT_DATA, (memory_mb << 20, memory_mb << 20))
32
+ except (ImportError, ValueError, OSError):
33
+ pass
34
+ sys.dont_write_bytecode = True
35
+
36
+
37
+ # Each version of the code runs from its own folder. Outputs that mention it,
38
+ # such as error messages with file paths, show <tree> instead.
39
+ def hide_tree(text):
40
+ return text.replace(tree, "<tree>").replace(sys.argv[1], "<tree>")
41
+
42
+
43
+ sys.setrecursionlimit(10000)
44
+ out = sys.stdout
45
+ sys.stdout = open(os.devnull, "w") # the project's own prints must not break the protocol
46
+ coverage_out = open(coverage_file, "w") if coverage_file else None
47
+
48
+ ran = set()
49
+ if coverage_out:
50
+ def own(path):
51
+ return path.startswith(tree + os.sep)
52
+
53
+ if hasattr(sys, "monitoring"):
54
+ mon = sys.monitoring
55
+ tool = mon.COVERAGE_ID
56
+
57
+ def on_line(code, line):
58
+ if own(code.co_filename):
59
+ ran.add((code.co_filename, line))
60
+ return mon.DISABLE
61
+
62
+ mon.use_tool_id(tool, "mob")
63
+ mon.register_callback(tool, mon.events.LINE, on_line)
64
+ mon.set_events(tool, mon.events.LINE)
65
+ else:
66
+ def tracer(frame, event, arg):
67
+ if not own(frame.f_code.co_filename):
68
+ return None
69
+ if event == "line":
70
+ ran.add((frame.f_code.co_filename, frame.f_lineno))
71
+ return tracer
72
+
73
+ sys.settrace(tracer)
74
+
75
+ BLOCKED = ("socket.", "subprocess.", "os.system", "os.exec", "os.posix_spawn", "os.spawn", "os.fork", "os.kill",
76
+ "os.remove", "os.rename", "os.rmdir", "os.mkdir", "os.chmod", "os.truncate", "shutil.", "ctypes.")
77
+
78
+
79
+ def guard(event, args):
80
+ if event.startswith(BLOCKED):
81
+ raise PermissionError(f"mob: {event} is not allowed while the gate runs your code")
82
+ if event == "open":
83
+ mode, flags = args[1], args[2] if len(args) > 2 else 0
84
+ writes = os.O_WRONLY | os.O_RDWR | os.O_CREAT | os.O_APPEND | os.O_TRUNC
85
+ if (mode is not None and any(c in str(mode) for c in "wax+")) or (isinstance(flags, int) and flags & writes):
86
+ raise PermissionError("mob: writing files is not allowed while the gate runs your code")
87
+
88
+
89
+ # If the worker that started this runner dies (for example on a timeout while
90
+ # the code loops forever), exit too.
91
+ parent = os.getppid()
92
+
93
+
94
+ def watch_parent():
95
+ while True:
96
+ time.sleep(0.5)
97
+ if os.getppid() != parent:
98
+ os._exit(1)
99
+
100
+
101
+ threading.Thread(target=watch_parent, daemon=True).start()
102
+ sys.path.insert(0, tree)
103
+ module_name = entry[:-3].replace("/", ".").replace(os.sep, ".") if entry.endswith(".py") else entry
104
+ loaded = None
105
+ load_error = None
106
+ sys.addaudithook(guard)
107
+ try:
108
+ loaded = getattr(importlib.import_module(module_name), function)
109
+ except BaseException as error: # a version that does not load gives that as every output
110
+ load_error = hide_tree(f"THROWS: does not load: {type(error).__name__}: {error}")[:200]
111
+
112
+
113
+ def output(value):
114
+ if isinstance(value, str):
115
+ return hide_tree(value)
116
+ try:
117
+ return hide_tree(json.dumps(value, ensure_ascii=False, allow_nan=True))
118
+ except (TypeError, ValueError):
119
+ return hide_tree(repr(value))
120
+
121
+
122
+ for line in sys.stdin:
123
+ given = json.loads(line)
124
+ if load_error:
125
+ out.write(json.dumps({"out": load_error, "ns": 0}) + "\n")
126
+ out.flush()
127
+ continue
128
+ start = time.perf_counter_ns()
129
+ try:
130
+ result = loaded(*given) if isinstance(given, list) else loaded(given)
131
+ ns = time.perf_counter_ns() - start
132
+ text = output(result)
133
+ except RecursionError:
134
+ ns = time.perf_counter_ns() - start
135
+ text = "THROWS: RecursionError"
136
+ except BaseException as error: # SystemExit too: a call must not end the runner
137
+ ns = time.perf_counter_ns() - start
138
+ text = hide_tree(f"THROWS: {type(error).__name__}: {error}")[:200]
139
+ out.write(json.dumps({"out": text, "ns": ns}, ensure_ascii=False) + "\n")
140
+ out.flush()
141
+
142
+ if coverage_out:
143
+ files = {}
144
+ for path in {p for p, _ in ran} | {getattr(m, "__file__", None) or "" for m in list(sys.modules.values())}:
145
+ if not path.startswith(tree + os.sep) or not path.endswith(".py"):
146
+ continue
147
+ source = open(path, encoding="utf-8").read()
148
+ code_lines = set()
149
+ stack = [compile(source, path, "exec")]
150
+ while stack:
151
+ code = stack.pop()
152
+ code_lines.update(line for _, _, line in code.co_lines() if line)
153
+ stack.extend(c for c in code.co_consts if hasattr(c, "co_lines"))
154
+ lines = sorted(line for p, line in ran if p == path)
155
+ hit = set(lines)
156
+ functions = []
157
+ for node in ast.walk(ast.parse(source)):
158
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
159
+ body = range(node.body[0].lineno, (node.end_lineno or node.lineno) + 1)
160
+ functions.append({"name": node.name, "line": node.lineno, "end": node.end_lineno, "run": any(n in hit for n in body)})
161
+ files[os.path.relpath(path, tree)] = {"lines": lines, "code": sorted(code_lines), "functions": functions}
162
+ coverage_out.write(json.dumps({"files": files}))
163
+ coverage_out.close()