@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.
- package/LICENSE +21 -0
- package/README.md +224 -2
- package/bin/mob.mjs +347 -0
- package/examples/wordfreq/README.md +13 -0
- package/examples/wordfreq/index.js +15 -0
- package/examples/wordfreq/mob.config.mjs +29 -0
- package/examples/wordfreq-py/README.md +11 -0
- package/examples/wordfreq-py/mob.config.mjs +29 -0
- package/examples/wordfreq-py/wordfreq.py +19 -0
- package/package.json +38 -4
- package/src/agents-section.md +12 -0
- package/src/config-template.mjs +54 -0
- package/src/gate.mjs +217 -0
- package/src/runner.py +163 -0
- package/src/sandbox.mjs +96 -0
- package/src/selftest.mjs +267 -0
- package/src/worker.mjs +328 -0
package/src/sandbox.mjs
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// The operating-system sandbox every gate job runs in. Node's permission
|
|
2
|
+
// model and runner.py's audit hook stop accidents, but neither is a security
|
|
3
|
+
// boundary: code written to get around them can. The sandbox is the wall:
|
|
4
|
+
// - no network (including local sockets such as Docker's),
|
|
5
|
+
// - no writes outside the job's own output files,
|
|
6
|
+
// - the home folder, /tmp and other users' files are hidden, except the
|
|
7
|
+
// paths the job names (the code, the recording, its dependencies),
|
|
8
|
+
// - no environment variables beyond a short safe list, so API keys in the
|
|
9
|
+
// shell that runs Mob never reach the code.
|
|
10
|
+
// Linux uses bubblewrap (bwrap); macOS uses its built-in sandbox-exec.
|
|
11
|
+
import fs from 'node:fs'
|
|
12
|
+
import os from 'node:os'
|
|
13
|
+
import path from 'node:path'
|
|
14
|
+
import { execFileSync } from 'node:child_process'
|
|
15
|
+
|
|
16
|
+
const SAFE_ENV = ['PATH', 'LANG', 'LC_ALL', 'LC_CTYPE', 'TZ', 'MOB_PYTHON', 'SYSTEMROOT']
|
|
17
|
+
export const sandboxEnv = (extra = {}) => ({ ...Object.fromEntries(SAFE_ENV.filter((k) => process.env[k] != null).map((k) => [k, process.env[k]])), HOME: os.homedir(), ...extra })
|
|
18
|
+
|
|
19
|
+
const real = (p) => { try { return fs.realpathSync(p) } catch { return null } }
|
|
20
|
+
const unique = (paths) => [...new Set(paths.filter(Boolean))]
|
|
21
|
+
|
|
22
|
+
let checked = null
|
|
23
|
+
// Whether this machine can run the sandbox; null if yes, else what to do.
|
|
24
|
+
export function sandboxProblem() {
|
|
25
|
+
if (checked !== null) return checked || null
|
|
26
|
+
const fix = 'Install it, or set sandbox: false in mob.config.mjs to run agent code without it (only for code you trust).'
|
|
27
|
+
try {
|
|
28
|
+
if (process.platform === 'linux') {
|
|
29
|
+
try { execFileSync('bwrap', ['--ro-bind', '/', '/', '--unshare-all', '--die-with-parent', 'true'], { stdio: 'pipe' }) } catch (error) {
|
|
30
|
+
checked = error.code === 'ENOENT'
|
|
31
|
+
? `Mob runs agent code in a sandbox, which needs bubblewrap: sudo apt install bubblewrap (or dnf / pacman install bubblewrap). ${fix}`
|
|
32
|
+
: `bubblewrap is installed but cannot start a sandbox here (${String(error.stderr || error.message).trim().split('\n')[0]}). On Ubuntu 24.04+, unprivileged user namespaces may need enabling. ${fix}`
|
|
33
|
+
}
|
|
34
|
+
} else if (process.platform === 'darwin') {
|
|
35
|
+
try { execFileSync('/usr/bin/sandbox-exec', ['-p', '(version 1)(allow default)', '/usr/bin/true'], { stdio: 'pipe' }) } catch { checked = `Mob runs agent code in a sandbox, and /usr/bin/sandbox-exec did not work. ${fix}` }
|
|
36
|
+
} else {
|
|
37
|
+
checked = `Mob's sandbox supports Linux and macOS, not ${process.platform}. Run Mob in WSL or a Linux container, or set sandbox: false in mob.config.mjs (only for code you trust).`
|
|
38
|
+
}
|
|
39
|
+
} finally { checked ??= '' }
|
|
40
|
+
return checked || null
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
// The full path of the python Mob starts (the sandbox may refuse to search
|
|
44
|
+
// PATH for it), and the folders its standard library and packages live in.
|
|
45
|
+
const pythons = new Map()
|
|
46
|
+
export function pythonPaths(python) {
|
|
47
|
+
if (!pythons.has(python)) {
|
|
48
|
+
let found = []
|
|
49
|
+
try {
|
|
50
|
+
found = execFileSync(python, ['-I', '-c', 'import sys,os;print(sys.executable);print(sys.prefix);print(sys.base_prefix);print(sys.exec_prefix);print(os.path.realpath(sys.executable))'], { encoding: 'utf8' }).trim().split('\n')
|
|
51
|
+
} catch {}
|
|
52
|
+
const exe = found.at(-1)
|
|
53
|
+
pythons.set(python, { exe: found[0] || python, dirs: unique([...found.slice(1, 4), exe && path.dirname(exe)]) })
|
|
54
|
+
}
|
|
55
|
+
return pythons.get(python)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// The command that runs `argv` inside the sandbox. `reads` are paths the job
|
|
59
|
+
// may read, `writes` paths it may write. `python` is the Python the job starts,
|
|
60
|
+
// if any.
|
|
61
|
+
export function sandboxed(argv, { reads, writes = [], python = null }) {
|
|
62
|
+
const node = real(process.execPath)
|
|
63
|
+
const shown = unique([...reads, node, path.dirname(path.dirname(node)), ...(python ? pythonPaths(python).dirs : [])].map(real))
|
|
64
|
+
const writable = unique(writes.map(real)) // existing files and folders only
|
|
65
|
+
if (process.platform === 'linux') {
|
|
66
|
+
const hide = unique([os.homedir(), '/home', '/root', '/tmp', '/var/tmp', '/run', '/var/run', '/mnt', '/media'].map(real)).filter((d) => d !== '/')
|
|
67
|
+
const args = ['--ro-bind', '/', '/', '--dev', '/dev', '--proc', '/proc']
|
|
68
|
+
for (const dir of hide) args.push('--tmpfs', dir)
|
|
69
|
+
for (const p of shown) args.push('--ro-bind', p, p)
|
|
70
|
+
for (const p of writable) args.push('--bind', p, p)
|
|
71
|
+
args.push('--unshare-all', '--die-with-parent', '--new-session', '--', ...argv)
|
|
72
|
+
return ['bwrap', args]
|
|
73
|
+
}
|
|
74
|
+
// macOS: later rules win. Reading file contents in the home folder, temp
|
|
75
|
+
// folders and other volumes is denied except for the shown paths; looking up
|
|
76
|
+
// names (metadata) stays allowed so paths still resolve.
|
|
77
|
+
const q = (p) => JSON.stringify(p)
|
|
78
|
+
const hidden = unique([os.homedir(), '/Users', '/private/tmp', '/private/var/folders', '/Volumes'].map(real))
|
|
79
|
+
// Python may exec itself again under another path (a framework build starts
|
|
80
|
+
// Python.app inside its prefix), so its folders are allowed both as named
|
|
81
|
+
// and with links resolved.
|
|
82
|
+
const allowed = [node, ...(python ? [pythonPaths(python).exe, ...pythonPaths(python).dirs] : []), '/usr/bin/python3', '/Library/Developer/CommandLineTools', '/Applications/Xcode.app']
|
|
83
|
+
const exec = unique([...allowed, ...allowed.map(real)])
|
|
84
|
+
const profile = [
|
|
85
|
+
'(version 1)',
|
|
86
|
+
'(allow default)',
|
|
87
|
+
'(deny network*)',
|
|
88
|
+
'(deny file-write*)',
|
|
89
|
+
`(allow file-write* (literal "/dev/null") (regex #"^/dev/fd/")${writable.map((p) => ` (subpath ${q(p)})`).join('')})`,
|
|
90
|
+
`(deny file-read-data ${hidden.map((p) => `(subpath ${q(p)})`).join(' ')})`,
|
|
91
|
+
`(allow file-read-data ${shown.map((p) => `(subpath ${q(p)})`).join(' ')})`,
|
|
92
|
+
'(deny process-exec*)',
|
|
93
|
+
`(allow process-exec* ${exec.map((p) => `(subpath ${q(p)})`).join(' ')})`
|
|
94
|
+
].join('\n')
|
|
95
|
+
return ['/usr/bin/sandbox-exec', ['-p', profile, ...argv]]
|
|
96
|
+
}
|
package/src/selftest.mjs
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// The self-test `mob init` runs after recording: how good are the recorded
|
|
2
|
+
// inputs at noticing a broken change? It plants one small bug at a time at
|
|
3
|
+
// every place in the code where one fits, and runs the normal output check on
|
|
4
|
+
// each. For each bug the recorded outputs miss, it searches for an input that
|
|
5
|
+
// shows the bug, so the report can say which inputs to add. Which code the
|
|
6
|
+
// inputs ran comes from V8 coverage of the recording run.
|
|
7
|
+
import fs from 'node:fs'
|
|
8
|
+
import os from 'node:os'
|
|
9
|
+
import path from 'node:path'
|
|
10
|
+
import { spawnSync } from 'node:child_process'
|
|
11
|
+
import { fileURLToPath } from 'node:url'
|
|
12
|
+
import { runJob } from './gate.mjs'
|
|
13
|
+
|
|
14
|
+
const SWAPS = [[' === ', ' !== '], [' !== ', ' === '], [' == ', ' != '], [' != ', ' == '], [' < ', ' <= '], [' > ', ' >= '], [' <= ', ' < '], [' >= ', ' > '],
|
|
15
|
+
[' && ', ' || '], [' || ', ' && '], [' + ', ' - '], [' - ', ' + '], ['true', 'false'], ['false', 'true']]
|
|
16
|
+
|
|
17
|
+
const PY_SWAPS = [[' == ', ' != '], [' != ', ' == '], [' < ', ' <= '], [' > ', ' >= '], [' <= ', ' < '], [' >= ', ' > '],
|
|
18
|
+
[' and ', ' or '], [' or ', ' and '], [' + ', ' - '], [' - ', ' + '], [' is not ', ' is '], [' not in ', ' in '], ['True', 'False'], ['False', 'True']]
|
|
19
|
+
const PY_KEYWORDS = /^(return|raise|def|class|import|from|if|elif|else|for|while|with|try|except|finally|pass|break|continue|global|nonlocal|yield|async|await|match|case|lambda)\b|^@/
|
|
20
|
+
|
|
21
|
+
// Coverage from the recording run, reduced to the tree's own source files.
|
|
22
|
+
// JavaScript: V8 ranges and their counts. Python: the lines that ran (from
|
|
23
|
+
// runner.py) and each function with whether it ran.
|
|
24
|
+
function readCoverage(dir, tree) {
|
|
25
|
+
const files = new Map()
|
|
26
|
+
for (const name of fs.readdirSync(dir)) {
|
|
27
|
+
const data = JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8'))
|
|
28
|
+
for (const [rel, f] of Object.entries(data.files ?? {})) {
|
|
29
|
+
// Several Python processes (isolate: true) each wrote a file: merge them.
|
|
30
|
+
const seen = files.get(rel)
|
|
31
|
+
if (!seen) { files.set(rel, { python: true, lines: new Set(f.lines), code: new Set(f.code), functions: f.functions }); continue }
|
|
32
|
+
for (const n of f.lines) seen.lines.add(n)
|
|
33
|
+
seen.functions = seen.functions.map((fn, i) => ({ ...fn, run: fn.run || f.functions[i]?.run }))
|
|
34
|
+
}
|
|
35
|
+
for (const script of data.result ?? []) {
|
|
36
|
+
if (!script.url.startsWith('file://')) continue
|
|
37
|
+
const rel = path.relative(tree, fileURLToPath(script.url))
|
|
38
|
+
if (rel.startsWith('..') || rel.split(path.sep).includes('node_modules') || !/\.[cm]?js$/.test(rel)) continue
|
|
39
|
+
files.set(rel, { functions: script.functions })
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return files
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// How often the code at `offset` ran: the count of the innermost range around it.
|
|
46
|
+
function countAt(functions, offset) {
|
|
47
|
+
let best = null
|
|
48
|
+
for (const fn of functions) for (const r of fn.ranges) {
|
|
49
|
+
if (r.startOffset <= offset && offset < r.endOffset && (!best || r.endOffset - r.startOffset < best.endOffset - best.startOffset)) best = r
|
|
50
|
+
}
|
|
51
|
+
return best ? best.count : 0
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const ranAt = (cov, offset, line) => (cov.python ? cov.lines.has(line) : countAt(cov.functions, offset) > 0)
|
|
55
|
+
|
|
56
|
+
const lineOf = (source, offset) => source.slice(0, offset).split('\n').length
|
|
57
|
+
|
|
58
|
+
function insideString(line, col) {
|
|
59
|
+
let quote = null
|
|
60
|
+
for (let i = 0; i < col; i++) {
|
|
61
|
+
const ch = line[i]
|
|
62
|
+
if (quote) { if (ch === '\\') i++; else if (ch === quote) quote = null } else if (ch === "'" || ch === '"' || ch === '`') quote = ch
|
|
63
|
+
}
|
|
64
|
+
return quote !== null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Where a Python line's comment starts (a # outside quotes), or its length.
|
|
68
|
+
function commentAt(line) {
|
|
69
|
+
for (let col = line.indexOf('#'); col !== -1; col = line.indexOf('#', col + 1)) if (!insideString(line, col)) return col
|
|
70
|
+
return line.length
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const balanced = (text) => { let depth = 0; for (const ch of text) { depth += '([{'.includes(ch) ? 1 : ')]}'.includes(ch) ? -1 : 0; if (depth < 0) return false } return depth === 0 }
|
|
74
|
+
|
|
75
|
+
// Every place a swap could go, each marked with whether the inputs ran it.
|
|
76
|
+
function findSites(tree, coverage) {
|
|
77
|
+
const sites = []
|
|
78
|
+
for (const [file, cov] of coverage) {
|
|
79
|
+
const source = fs.readFileSync(path.join(tree, file), 'utf8')
|
|
80
|
+
let offset = 0
|
|
81
|
+
source.split('\n').forEach((text, i) => {
|
|
82
|
+
const line = i + 1
|
|
83
|
+
const end = cov.python ? commentAt(text) : text.length
|
|
84
|
+
const code = text.slice(0, end)
|
|
85
|
+
const add = (col, from, to) => sites.push({ file, line, col, from, to, code: text.trim().slice(0, 100), reached: ranAt(cov, offset + col, line) })
|
|
86
|
+
// Python: only lines that hold code (not text inside a multi-line string).
|
|
87
|
+
if (cov.python ? code.trim() !== '' && cov.code.has(line) : !/^\s*(\/\/|\*|\/\*)/.test(text)) {
|
|
88
|
+
const col = text.search(/\S/)
|
|
89
|
+
const body = code.trim()
|
|
90
|
+
if (cov.python) {
|
|
91
|
+
// Replace one simple statement with `pass`.
|
|
92
|
+
if (!PY_KEYWORDS.test(body) && !/[:,\\([{]$/.test(body) && balanced(body) && !/^["']/.test(body)) add(col, code.slice(col).trimEnd(), 'pass')
|
|
93
|
+
} else if (/;\s*$/.test(text) && !/[{}]/.test(text) && !/^\s*(var|let|const|return|throw|break|continue)\b/.test(text)) {
|
|
94
|
+
// Delete one simple statement: a whole line ending in ';' with no braces.
|
|
95
|
+
add(col, text.slice(col), '')
|
|
96
|
+
}
|
|
97
|
+
for (const [from, to] of cov.python ? PY_SWAPS : SWAPS) {
|
|
98
|
+
for (let c = code.indexOf(from); c !== -1; c = code.indexOf(from, c + 1)) {
|
|
99
|
+
if (insideString(text, c)) continue
|
|
100
|
+
if (/^\w/.test(from) && (/\w/.test(text[c - 1] ?? '') || /\w/.test(text[c + from.length] ?? ''))) continue
|
|
101
|
+
add(c, from, to)
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
offset += text.length + 1
|
|
106
|
+
})
|
|
107
|
+
}
|
|
108
|
+
return sites
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// Python sites whose bug still parses: a syntax error would only show that
|
|
112
|
+
// the file no longer loads. The tree's files are read as text, never run.
|
|
113
|
+
const PY_PARSES = `import ast, json, sys
|
|
114
|
+
tree, sites, cache, ok = sys.argv[1], json.load(sys.stdin), {}, []
|
|
115
|
+
for s in sites:
|
|
116
|
+
if s['file'] not in cache:
|
|
117
|
+
cache[s['file']] = open(tree + '/' + s['file'], encoding='utf-8').read().split('\\n')
|
|
118
|
+
lines = list(cache[s['file']])
|
|
119
|
+
t = lines[s['line'] - 1]
|
|
120
|
+
lines[s['line'] - 1] = t[:s['col']] + s['to'] + t[s['col'] + len(s['from']):]
|
|
121
|
+
try:
|
|
122
|
+
ast.parse('\\n'.join(lines)); ok.append(True)
|
|
123
|
+
except SyntaxError:
|
|
124
|
+
ok.append(False)
|
|
125
|
+
print(json.dumps(ok))`
|
|
126
|
+
|
|
127
|
+
function parsesInPython(tree, sites, python) {
|
|
128
|
+
if (!sites.length) return sites
|
|
129
|
+
const r = spawnSync(python ?? process.env.MOB_PYTHON ?? 'python3', ['-I', '-c', PY_PARSES, tree], { input: JSON.stringify(sites), encoding: 'utf8', maxBuffer: 1 << 28 })
|
|
130
|
+
if (r.status !== 0) throw new Error(`python3 could not check the planted bugs: ${r.stderr.slice(-300)}`)
|
|
131
|
+
const ok = JSON.parse(r.stdout)
|
|
132
|
+
return sites.filter((_, i) => ok[i])
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Named functions the inputs never called, outermost only.
|
|
136
|
+
export function neverRun(tree, coverageDir) {
|
|
137
|
+
const out = []
|
|
138
|
+
for (const [file, cov] of readCoverage(coverageDir, tree)) {
|
|
139
|
+
if (cov.python) {
|
|
140
|
+
const zero = cov.functions.filter((f) => !f.run)
|
|
141
|
+
for (const f of zero) if (!zero.some((o) => o !== f && o.line <= f.line && f.end <= o.end)) out.push({ file, line: f.line, name: f.name })
|
|
142
|
+
continue
|
|
143
|
+
}
|
|
144
|
+
const source = fs.readFileSync(path.join(tree, file), 'utf8')
|
|
145
|
+
const zero = cov.functions.filter((fn) => fn.ranges[0].count === 0).map((fn) => ({ name: fn.functionName, start: fn.ranges[0].startOffset, end: fn.ranges[0].endOffset }))
|
|
146
|
+
for (const fn of zero) {
|
|
147
|
+
if (!fn.name || zero.some((o) => o !== fn && o.start <= fn.start && fn.end <= o.end)) continue
|
|
148
|
+
out.push({ file, line: lineOf(source, fn.start), name: fn.name })
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return out.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Short strings and numbers written in a source file, and the characters that
|
|
155
|
+
// numeric character codes stand for: values that code is likely to test for.
|
|
156
|
+
function literals(source) {
|
|
157
|
+
const out = new Set()
|
|
158
|
+
for (const m of source.matchAll(/'([^'\\\n]{1,16})'|"([^"\\\n]{1,16})"|\b(0x[0-9a-fA-F]+|\d+(?:\.\d+)?)\b/g)) {
|
|
159
|
+
const word = m[1] ?? m[2] ?? m[3]
|
|
160
|
+
out.add(word)
|
|
161
|
+
const n = Number(word)
|
|
162
|
+
if (m[3] && Number.isInteger(n) && n >= 32 && n < 0x110000) out.add(String.fromCodePoint(n))
|
|
163
|
+
}
|
|
164
|
+
return [...out].slice(0, 500)
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function sample(sites, count) {
|
|
168
|
+
if (count >= sites.length) return sites
|
|
169
|
+
let seed = 7
|
|
170
|
+
const r = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 2 ** 32)
|
|
171
|
+
const pool = [...sites]
|
|
172
|
+
const picked = []
|
|
173
|
+
while (picked.length < count && pool.length) picked.push(pool.splice(Math.floor(r() * pool.length), 1)[0])
|
|
174
|
+
return picked.sort((a, b) => a.file.localeCompare(b.file) || a.line - b.line || a.col - b.col)
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function plant(source, site) {
|
|
178
|
+
const lines = source.split('\n')
|
|
179
|
+
const text = lines[site.line - 1]
|
|
180
|
+
lines[site.line - 1] = text.slice(0, site.col) + site.to + text.slice(site.col + site.from.length)
|
|
181
|
+
return lines.join('\n')
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Plants each site's bug, one at a time, in a copy of the tree per worker
|
|
185
|
+
// slot. Each is checked like a push (stopping at the first difference). With
|
|
186
|
+
// `hunt`, a bug the recorded outputs miss is then searched for an input that
|
|
187
|
+
// shows it.
|
|
188
|
+
export async function plantAll(p, meta, tree, sites, { hunt, huntMs = 2000, log = () => {} }) {
|
|
189
|
+
const work = path.join(p.dir, 'selftest')
|
|
190
|
+
// A planted bug often makes the code loop forever. Time one clean check,
|
|
191
|
+
// and treat a check that takes 4 times as long as caught: the gate would
|
|
192
|
+
// refuse it too, for running out of time.
|
|
193
|
+
const started = Date.now()
|
|
194
|
+
const clean = await runJob(p, meta, { mode: 'check', lib: tree })
|
|
195
|
+
if (!clean.ok) throw new Error(`main does not pass its own check: ${clean.reason} ${clean.detail ?? ''}`)
|
|
196
|
+
const timeoutMs = Math.max(3000, 4 * (Date.now() - started))
|
|
197
|
+
// Checks run side by side. A planted bug can make the code take memory
|
|
198
|
+
// without limit, so each gets an equal share of 60% of the machine's memory.
|
|
199
|
+
const slots = Math.min(os.availableParallelism(), sites.length) || 1
|
|
200
|
+
const memoryMb = Math.max(512, Math.min(4096, Math.floor((os.totalmem() / 2 ** 20) * 0.6 / slots)))
|
|
201
|
+
const words = new Map()
|
|
202
|
+
const results = new Array(sites.length)
|
|
203
|
+
const every = Math.max(10, Math.ceil(sites.length / 10))
|
|
204
|
+
// Shared across slots: how often each recorded input caught a bug (tried
|
|
205
|
+
// first next time), and the inputs found so far (tried before a new search).
|
|
206
|
+
const hits = new Map()
|
|
207
|
+
const pool = []
|
|
208
|
+
let next = 0
|
|
209
|
+
let done = 0
|
|
210
|
+
const slot = async (k) => {
|
|
211
|
+
const dir = path.join(work, String(k))
|
|
212
|
+
fs.cpSync(tree, dir, { recursive: true, verbatimSymlinks: true })
|
|
213
|
+
while (next < sites.length) {
|
|
214
|
+
const i = next++
|
|
215
|
+
const site = sites[i]
|
|
216
|
+
const file = path.join(dir, site.file)
|
|
217
|
+
const source = fs.readFileSync(file, 'utf8')
|
|
218
|
+
if (!words.has(site.file)) words.set(site.file, literals(source))
|
|
219
|
+
fs.writeFileSync(file, plant(source, site))
|
|
220
|
+
// Code no input ran cannot change a recorded output; skip to the search.
|
|
221
|
+
const check = site.reached || !hunt
|
|
222
|
+
const order = [...hits].sort((a, b) => b[1] - a[1]).slice(0, 64).map(([n]) => n)
|
|
223
|
+
const h = await runJob(p, meta, { mode: 'probe', lib: dir, current: tree, check, order, hunt, pool: pool.slice(-200), budgetMs: huntMs, seed: i + 1, words: words.get(site.file) }, { timeoutMs: timeoutMs + 2 * huntMs, memoryMb })
|
|
224
|
+
let result
|
|
225
|
+
if (!h.ok) {
|
|
226
|
+
// A bug that hangs on the recorded inputs is refused by the gate for
|
|
227
|
+
// running out of time; one that hangs only in the search is reported.
|
|
228
|
+
const inSearch = (h.partial ?? '').includes('"phase":"hunt"')
|
|
229
|
+
result = inSearch ? { caught: false, hung: true } : { caught: true }
|
|
230
|
+
} else if (h.caught) {
|
|
231
|
+
result = { caught: true }
|
|
232
|
+
if (h.input !== undefined) hits.set(h.input, (hits.get(h.input) ?? 0) + 1)
|
|
233
|
+
} else if (h.found) {
|
|
234
|
+
result = { caught: false, input: h.input, expected: h.expected, got: h.got, tries: h.tries, ms: h.ms }
|
|
235
|
+
if (!h.pool) pool.push(h.input)
|
|
236
|
+
} else result = { caught: false }
|
|
237
|
+
results[i] = { ...site, ...result }
|
|
238
|
+
fs.writeFileSync(file, source)
|
|
239
|
+
if (++done % every === 0 || done === sites.length) log(` ${done} of ${sites.length} checked`)
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
await Promise.all(Array.from({ length: slots }, (_, k) => slot(k)))
|
|
243
|
+
fs.rmSync(work, { recursive: true, force: true })
|
|
244
|
+
return results
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const brief = ({ file, line, col, from, to, code }) => ({ file, line, col, from, to, code })
|
|
248
|
+
|
|
249
|
+
export async function selfTest(p, meta, { tree, coverageDir, count, huntMs, log = () => {} }) {
|
|
250
|
+
const found = findSites(tree, readCoverage(coverageDir, tree))
|
|
251
|
+
const sites = meta.language === 'python' ? parsesInPython(tree, found, meta.python) : found
|
|
252
|
+
const planted = sample(sites, count)
|
|
253
|
+
const results = await plantAll(p, meta, tree, planted, { hunt: true, huntMs, log })
|
|
254
|
+
const exposed = results.filter((r) => !r.caught && 'input' in r).map((r) => ({ ...brief(r), input: r.input, expected: r.expected, got: r.got }))
|
|
255
|
+
const seen = new Set()
|
|
256
|
+
const inputsToAdd = []
|
|
257
|
+
for (const r of exposed) { const key = JSON.stringify(r.input); if (!seen.has(key)) { seen.add(key); inputsToAdd.push(r.input) } }
|
|
258
|
+
return {
|
|
259
|
+
sites: sites.length,
|
|
260
|
+
planted: results.length,
|
|
261
|
+
caught: results.filter((r) => r.caught).length,
|
|
262
|
+
exposed,
|
|
263
|
+
unresolved: results.filter((r) => !r.caught && !('input' in r)).map((r) => ({ ...brief(r), reached: r.reached, ...(r.hung ? { hung: true } : {}) })),
|
|
264
|
+
inputsToAdd,
|
|
265
|
+
neverRun: neverRun(tree, coverageDir)
|
|
266
|
+
}
|
|
267
|
+
}
|