@tangle-network/agent-bench 0.3.6 → 0.3.7
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/CHANGELOG.md +7 -0
- package/dist/adapters.js +2 -2
- package/dist/benchmarks/humaneval.d.ts +10 -1
- package/dist/benchmarks/humaneval.js +5 -3
- package/dist/{chunk-PPYSEKFM.js → chunk-5H5XV76F.js} +73 -15
- package/dist/chunk-5H5XV76F.js.map +1 -0
- package/dist/{chunk-5SBJCB6W.js → chunk-PWQVGAJB.js} +2 -2
- package/dist/index.js +2 -2
- package/package.json +5 -4
- package/scripts/run-package-tests.mjs +30 -8
- package/scripts/verify-pier-agent.mts +1 -0
- package/src/benchmarks/humaneval.test.mts +122 -0
- package/src/benchmarks/humaneval.ts +100 -27
- package/src/david-attribution.mts +78 -0
- package/src/david-goliath.mts +149 -0
- package/src/hev-improve.mts +25 -6
- package/src/humaneval-object-ablation.mts +201 -0
- package/src/live-improve-campaign-mbpp.mts +641 -0
- package/src/live-improve-campaign.mts +500 -0
- package/src/mbpp-structural.mts +12 -7
- package/src/stream-observe.py +45 -0
- package/src/stream-observe.tpl.html +247 -0
- package/src/supervisor-arena.mts +816 -0
- package/src/swe-arena/analyze.ts +211 -0
- package/src/swe-arena/arms.ts +788 -0
- package/src/swe-arena/bootstrap-meta.mts +188 -0
- package/src/swe-arena/bootstrap-meta.test.mts +51 -0
- package/src/swe-arena/calibrate.ts +116 -0
- package/src/swe-arena/capabilities.mts +76 -0
- package/src/swe-arena/capabilities.test.mts +57 -0
- package/src/swe-arena/capacity.ts +194 -0
- package/src/swe-arena/cell-evidence.mts +405 -0
- package/src/swe-arena/cell-evidence.test.mts +248 -0
- package/src/swe-arena/diagnosis-ensemble.test.mts +210 -0
- package/src/swe-arena/diagnosis-ensemble.ts +520 -0
- package/src/swe-arena/execution.test.mts +1170 -0
- package/src/swe-arena/fixtures/analyze.py +80 -0
- package/src/swe-arena/fixtures/excludes.txt +8 -0
- package/src/swe-arena/fixtures/gen1-salvage/README.md +45 -0
- package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +116 -0
- package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +293 -0
- package/src/swe-arena/fixtures/holdout-preregister.log +12 -0
- package/src/swe-arena/fixtures/holdout.json +44 -0
- package/src/swe-arena/fixtures/instances.json +146 -0
- package/src/swe-arena/fixtures/ledger.jsonl +12 -0
- package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +36 -0
- package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +33 -0
- package/src/swe-arena/fixtures/rejudge.jsonl +15 -0
- package/src/swe-arena/fixtures/rematch.jsonl +3 -0
- package/src/swe-arena/fixtures/rematch2.jsonl +3 -0
- package/src/swe-arena/fixtures/rematch3.jsonl +3 -0
- package/src/swe-arena/fixtures/sup-journal-true.json +19 -0
- package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +48 -0
- package/src/swe-arena/fixtures/verify/django__django-11532.sh +50 -0
- package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +76 -0
- package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +44 -0
- package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +32 -0
- package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +51 -0
- package/src/swe-arena/fixtures/worker-tokens.json +42 -0
- package/src/swe-arena/fixtures.ts +104 -0
- package/src/swe-arena/holdout-certify.mts +408 -0
- package/src/swe-arena/holdout-certify.test.mts +160 -0
- package/src/swe-arena/judge-child.mts +37 -0
- package/src/swe-arena/manifest.mts +293 -0
- package/src/swe-arena/manifest.test.mts +169 -0
- package/src/swe-arena/materialize.ts +142 -0
- package/src/swe-arena/outer-loop.mts +2145 -0
- package/src/swe-arena/outer-loop.test.mts +696 -0
- package/src/swe-arena/parity.test.mts +87 -0
- package/src/swe-arena/proc.test.mts +174 -0
- package/src/swe-arena/proc.ts +260 -0
- package/src/swe-arena/profiles/default-author.profile.json +4 -0
- package/src/swe-arena/proposer-fanout.mts +489 -0
- package/src/swe-arena/proposer-fanout.test.mts +372 -0
- package/src/swe-arena/reconcile.ts +0 -0
- package/src/swe-arena/replay.mts +183 -0
- package/src/swe-arena/replay.test.mts +300 -0
- package/src/swe-arena/run-experiment.mts +361 -0
- package/src/swe-arena/run-supervisor.mjs +297 -0
- package/src/swe-arena/run-supervisor.test.mts +498 -0
- package/src/swe-arena/serialized-judge.ts +414 -0
- package/src/swe-arena/types.ts +166 -0
- package/src/swe-code-improve.mts +328 -0
- package/src/swe-emit-patch.mts +104 -0
- package/src/swe-improve.mts +232 -0
- package/src/swe-jail.ts +2 -2
- package/src/swe-local-proof.mts +169 -0
- package/src/swe-repro-calibrate.mts +446 -0
- package/src/swe-stream.mts +1497 -0
- package/dist/chunk-PPYSEKFM.js.map +0 -1
- /package/dist/{chunk-5SBJCB6W.js.map → chunk-PWQVGAJB.js.map} +0 -0
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PARITY GATE for M2: the typed execution path (materialize → patch apply →
|
|
3
|
+
* extractPatch → serialized-judge → official swebench verdict) must reproduce
|
|
4
|
+
* the pinned M1 fixture verdicts for two committed arm patches — one resolved
|
|
5
|
+
* (pallets__flask-5014 SOLO), one unresolved (pydata__xarray-4687 SUP) —
|
|
6
|
+
* WITHOUT executing any arm. Zero model tokens; docker time only (it pulls the
|
|
7
|
+
* two instance images if absent and runs the official judge, ~5-25 min each).
|
|
8
|
+
*
|
|
9
|
+
* Opt-in because of that docker cost:
|
|
10
|
+
*
|
|
11
|
+
* SWE_ARENA_PARITY=1 ../node_modules/.bin/vitest run src/swe-arena/parity.test.mts
|
|
12
|
+
*
|
|
13
|
+
* Expected verdicts are DERIVED from the pinned fixtures (ledger + rejudge
|
|
14
|
+
* reconciliation), not hardcoded — parity means agreeing with the record.
|
|
15
|
+
*
|
|
16
|
+
* TODO(operator approval): the full 12-instance ARM parity re-run (typed path
|
|
17
|
+
* vs the bash harness on the same 12 ids, both arms) costs ~$1 model spend +
|
|
18
|
+
* ~4h wall. Do not run without an explicit operator go — this 2-patch gate is
|
|
19
|
+
* the milestone check.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { mkdtemp, rm } from 'node:fs/promises'
|
|
23
|
+
import { tmpdir } from 'node:os'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
|
26
|
+
import { loadLedger, loadRejudge } from './fixtures.ts'
|
|
27
|
+
import { reconcile } from './reconcile.ts'
|
|
28
|
+
import { createSerializedJudge } from './serialized-judge.ts'
|
|
29
|
+
import { PARITY_CASES, replayPatchParity, type ParityCaseResult } from './run-experiment.mts'
|
|
30
|
+
|
|
31
|
+
const RUN_PARITY = process.env.SWE_ARENA_PARITY === '1'
|
|
32
|
+
// materialize + image pull + official judge, twice; generous but finite.
|
|
33
|
+
const PARITY_BUDGET_MS = 5_400_000
|
|
34
|
+
|
|
35
|
+
describe.runIf(RUN_PARITY)('dry-run parity vs pinned M1 verdicts (docker, no tokens)', () => {
|
|
36
|
+
let results: ParityCaseResult[] = []
|
|
37
|
+
let workDir = ''
|
|
38
|
+
|
|
39
|
+
beforeAll(async () => {
|
|
40
|
+
workDir = await mkdtemp(join(tmpdir(), 'swe-arena-parity-'))
|
|
41
|
+
const judge = createSerializedJudge() // real judge child, 1800s ceiling, serialized
|
|
42
|
+
results = await replayPatchParity(PARITY_CASES, { workDir, judge })
|
|
43
|
+
for (const r of results) {
|
|
44
|
+
console.log(`PARITY ${r.iid} [${r.arm}] verdict=${JSON.stringify(r.verdict)}`)
|
|
45
|
+
}
|
|
46
|
+
}, PARITY_BUDGET_MS)
|
|
47
|
+
|
|
48
|
+
afterAll(async () => {
|
|
49
|
+
if (workDir) await rm(workDir, { recursive: true, force: true })
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
it('re-extraction preserves each committed patch’s changed-file set', () => {
|
|
53
|
+
expect(results).toHaveLength(2)
|
|
54
|
+
for (const r of results) {
|
|
55
|
+
expect(r.applyRc).toBe(0)
|
|
56
|
+
expect(r.extractedFiles, `${r.iid} [${r.arm}]`).toEqual(r.fixtureFiles)
|
|
57
|
+
expect(r.extractedPatchLines).toBeGreaterThan(0)
|
|
58
|
+
}
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
it('pallets__flask-5014 SOLO: typed judge verdict == pinned ledger verdict (resolved)', () => {
|
|
62
|
+
const pinned = loadLedger().find((r) => r.iid === 'pallets__flask-5014')
|
|
63
|
+
expect(pinned?.solo_resolved).toBe(true) // sanity: the fixture side of the parity claim
|
|
64
|
+
const r = results.find((x) => x.iid === 'pallets__flask-5014')
|
|
65
|
+
expect(r?.verdict.attempts).toBeGreaterThan(0)
|
|
66
|
+
expect(r?.verdict.resolved).toBe(pinned?.solo_resolved)
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
it('pydata__xarray-4687 SUP: typed judge verdict == reconciled verdict (unresolved)', () => {
|
|
70
|
+
// The authoritative record for this arm is the personal re-judge
|
|
71
|
+
// (sup-final), which M1's reconciliation applies over the ledger.
|
|
72
|
+
const reconciled = reconcile(loadLedger(), loadRejudge()).valid.find(
|
|
73
|
+
(r) => r.iid === 'pydata__xarray-4687',
|
|
74
|
+
)
|
|
75
|
+
expect(reconciled?.sup.source).toBe('sup-final')
|
|
76
|
+
expect(reconciled?.sup.resolved).toBe(false)
|
|
77
|
+
const r = results.find((x) => x.iid === 'pydata__xarray-4687')
|
|
78
|
+
expect(r?.verdict.attempts).toBeGreaterThan(0)
|
|
79
|
+
expect(r?.verdict.resolved).toBe(reconciled?.sup.resolved)
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
describe.runIf(!RUN_PARITY)('dry-run parity (skipped)', () => {
|
|
84
|
+
it('is opt-in: set SWE_ARENA_PARITY=1 to run the docker-backed parity gate', () => {
|
|
85
|
+
expect(RUN_PARITY).toBe(false)
|
|
86
|
+
})
|
|
87
|
+
})
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { access, mkdtemp, readFile, rm } from 'node:fs/promises'
|
|
2
|
+
import { tmpdir } from 'node:os'
|
|
3
|
+
import { join } from 'node:path'
|
|
4
|
+
import { afterAll, describe, expect, it } from 'vitest'
|
|
5
|
+
import { waitForCapacity, type EndpointCapacityGate } from './capacity.ts'
|
|
6
|
+
import { installProcessSignalAbort, run, TIMEOUT_RC } from './proc.ts'
|
|
7
|
+
|
|
8
|
+
const dirs: string[] = []
|
|
9
|
+
const cleanupPids: number[] = []
|
|
10
|
+
|
|
11
|
+
afterAll(async () => {
|
|
12
|
+
for (const pid of cleanupPids) {
|
|
13
|
+
try {
|
|
14
|
+
process.kill(pid, 'SIGKILL')
|
|
15
|
+
} catch {
|
|
16
|
+
// The expected path already removed it.
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
await Promise.all(dirs.map((dir) => rm(dir, { recursive: true, force: true })))
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
describe('run process-group timeout', () => {
|
|
23
|
+
it('does not spawn when the caller signal is already aborted', () => {
|
|
24
|
+
const controller = new AbortController()
|
|
25
|
+
controller.abort(new Error('stop before spawn'))
|
|
26
|
+
expect(() => run(process.execPath, ['-e', 'process.exit(99)'], { signal: controller.signal })).toThrow(
|
|
27
|
+
'stop before spawn',
|
|
28
|
+
)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('allows a SIGTERM handler to finish cleanup before returning timeout', async () => {
|
|
32
|
+
const dir = await mkdtemp(join(tmpdir(), 'swe-proc-term-'))
|
|
33
|
+
dirs.push(dir)
|
|
34
|
+
const marker = join(dir, 'cleanup.txt')
|
|
35
|
+
const result = await run(process.execPath, [
|
|
36
|
+
'-e',
|
|
37
|
+
`const fs=require('node:fs'); const marker=process.argv[1]; process.on('SIGTERM',()=>{fs.writeFileSync(marker,'settled'); setTimeout(()=>process.exit(0),25)}); setInterval(()=>{},1000)`,
|
|
38
|
+
marker,
|
|
39
|
+
], { timeoutMs: 60, killGraceMs: 500 })
|
|
40
|
+
|
|
41
|
+
expect(result.code).toBe(TIMEOUT_RC)
|
|
42
|
+
expect(result.timedOut).toBe(true)
|
|
43
|
+
expect(await readFile(marker, 'utf8')).toBe('settled')
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
it('force-kills a process group that ignores SIGTERM after the grace period', async () => {
|
|
47
|
+
const dir = await mkdtemp(join(tmpdir(), 'swe-proc-kill-'))
|
|
48
|
+
dirs.push(dir)
|
|
49
|
+
const marker = join(dir, 'should-not-exist.txt')
|
|
50
|
+
const started = Date.now()
|
|
51
|
+
const result = await run(process.execPath, [
|
|
52
|
+
'-e',
|
|
53
|
+
`const fs=require('node:fs'); const marker=process.argv[1]; process.on('SIGTERM',()=>{}); setTimeout(()=>fs.writeFileSync(marker,'escaped'),5000); setInterval(()=>{},1000)`,
|
|
54
|
+
marker,
|
|
55
|
+
], { timeoutMs: 60, killGraceMs: 80 })
|
|
56
|
+
|
|
57
|
+
expect(result.code).toBe(TIMEOUT_RC)
|
|
58
|
+
expect(result.timedOut).toBe(true)
|
|
59
|
+
expect(Date.now() - started).toBeLessThan(2_000)
|
|
60
|
+
await expect(access(marker)).rejects.toMatchObject({ code: 'ENOENT' })
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
it('kills a TERM-ignoring grandchild when its direct parent exits on TERM', async () => {
|
|
64
|
+
if (process.platform === 'win32') return
|
|
65
|
+
const dir = await mkdtemp(join(tmpdir(), 'swe-proc-tree-'))
|
|
66
|
+
dirs.push(dir)
|
|
67
|
+
const pidFile = join(dir, 'grandchild.pid')
|
|
68
|
+
const grandchild = `process.on('SIGTERM',()=>{}); setInterval(()=>{},1000)`
|
|
69
|
+
const parent = [
|
|
70
|
+
`const {spawn}=require('node:child_process')`,
|
|
71
|
+
`const fs=require('node:fs')`,
|
|
72
|
+
`const child=spawn(process.execPath,['-e',${JSON.stringify(grandchild)}],{stdio:'ignore'})`,
|
|
73
|
+
`fs.writeFileSync(process.argv[1],String(child.pid))`,
|
|
74
|
+
`process.on('SIGTERM',()=>process.exit(0))`,
|
|
75
|
+
`setInterval(()=>{},1000)`,
|
|
76
|
+
].join(';')
|
|
77
|
+
|
|
78
|
+
const result = await run(process.execPath, ['-e', parent, pidFile], {
|
|
79
|
+
timeoutMs: 100,
|
|
80
|
+
killGraceMs: 50,
|
|
81
|
+
})
|
|
82
|
+
const grandchildPid = Number(await readFile(pidFile, 'utf8'))
|
|
83
|
+
cleanupPids.push(grandchildPid)
|
|
84
|
+
|
|
85
|
+
expect(result.code).toBe(TIMEOUT_RC)
|
|
86
|
+
expect(result.timedOut).toBe(true)
|
|
87
|
+
expect(() => process.kill(grandchildPid, 0)).toThrow(expect.objectContaining({ code: 'ESRCH' }))
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('kills a TERM-ignoring grandchild when its direct parent exits normally', async () => {
|
|
91
|
+
if (process.platform === 'win32') return
|
|
92
|
+
const dir = await mkdtemp(join(tmpdir(), 'swe-proc-normal-exit-tree-'))
|
|
93
|
+
dirs.push(dir)
|
|
94
|
+
const pidFile = join(dir, 'grandchild.pid')
|
|
95
|
+
const grandchild = [
|
|
96
|
+
`const fs=require('node:fs')`,
|
|
97
|
+
`process.on('SIGTERM',()=>{})`,
|
|
98
|
+
`fs.writeFileSync(process.argv[1],String(process.pid))`,
|
|
99
|
+
`setInterval(()=>{},1000)`,
|
|
100
|
+
].join(';')
|
|
101
|
+
const parent = [
|
|
102
|
+
`const {spawn}=require('node:child_process')`,
|
|
103
|
+
`const fs=require('node:fs')`,
|
|
104
|
+
`spawn(process.execPath,['-e',${JSON.stringify(grandchild)},process.argv[1]],{stdio:'ignore'})`,
|
|
105
|
+
`const ready=setInterval(()=>{if(fs.existsSync(process.argv[1])){clearInterval(ready);process.exit(0)}},5)`,
|
|
106
|
+
].join(';')
|
|
107
|
+
|
|
108
|
+
const result = await run(process.execPath, ['-e', parent, pidFile], { killGraceMs: 50 })
|
|
109
|
+
const grandchildPid = Number(await readFile(pidFile, 'utf8'))
|
|
110
|
+
cleanupPids.push(grandchildPid)
|
|
111
|
+
|
|
112
|
+
expect(result.code).toBe(0)
|
|
113
|
+
expect(result.timedOut).toBe(false)
|
|
114
|
+
expect(result.aborted).toBe(false)
|
|
115
|
+
expect(() => process.kill(grandchildPid, 0)).toThrow(expect.objectContaining({ code: 'ESRCH' }))
|
|
116
|
+
})
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
describe('cooperative process cancellation', () => {
|
|
120
|
+
it('maps the first terminal signal to cancellation and removes its handlers', () => {
|
|
121
|
+
const oldExitCode = process.exitCode
|
|
122
|
+
const beforeInt = new Set(process.rawListeners('SIGINT'))
|
|
123
|
+
const beforeTerm = process.listenerCount('SIGTERM')
|
|
124
|
+
const interrupt = installProcessSignalAbort('test-run')
|
|
125
|
+
const listener = process.rawListeners('SIGINT').find((candidate) => !beforeInt.has(candidate))
|
|
126
|
+
expect(listener).toBeDefined()
|
|
127
|
+
listener?.call(process, 'SIGINT')
|
|
128
|
+
expect(interrupt.signal.aborted).toBe(true)
|
|
129
|
+
expect((interrupt.signal.reason as Error).message).toBe('test-run interrupted by SIGINT')
|
|
130
|
+
expect(interrupt.receivedSignal).toBe('SIGINT')
|
|
131
|
+
expect(process.exitCode).toBe(130)
|
|
132
|
+
interrupt.dispose()
|
|
133
|
+
expect(process.rawListeners('SIGINT').filter((candidate) => !beforeInt.has(candidate))).toHaveLength(0)
|
|
134
|
+
expect(process.listenerCount('SIGTERM')).toBe(beforeTerm)
|
|
135
|
+
process.exitCode = oldExitCode
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
it('cancels during a capacity retry sleep and never starts another probe', async () => {
|
|
139
|
+
const controller = new AbortController()
|
|
140
|
+
let probes = 0
|
|
141
|
+
const gate: EndpointCapacityGate = {
|
|
142
|
+
name: 'cancel-test',
|
|
143
|
+
probe: async () => {
|
|
144
|
+
probes += 1
|
|
145
|
+
return false
|
|
146
|
+
},
|
|
147
|
+
kOfN: { k: 1, n: 1 },
|
|
148
|
+
waitCeilingMs: 10_000,
|
|
149
|
+
retryDelayMs: 10_000,
|
|
150
|
+
}
|
|
151
|
+
const waiting = waitForCapacity(gate, controller.signal)
|
|
152
|
+
await new Promise((resolve) => setTimeout(resolve, 20))
|
|
153
|
+
controller.abort(new Error('capacity cancelled'))
|
|
154
|
+
await expect(waiting).rejects.toThrow('capacity cancelled')
|
|
155
|
+
expect(probes).toBe(1)
|
|
156
|
+
})
|
|
157
|
+
|
|
158
|
+
it('runs zero capacity probes when already aborted', async () => {
|
|
159
|
+
const controller = new AbortController()
|
|
160
|
+
controller.abort(new Error('cancelled before probing'))
|
|
161
|
+
let probes = 0
|
|
162
|
+
const gate: EndpointCapacityGate = {
|
|
163
|
+
name: 'pre-abort',
|
|
164
|
+
probe: async () => {
|
|
165
|
+
probes += 1
|
|
166
|
+
return true
|
|
167
|
+
},
|
|
168
|
+
kOfN: { k: 1, n: 1 },
|
|
169
|
+
waitCeilingMs: 1_000,
|
|
170
|
+
}
|
|
171
|
+
await expect(waitForCapacity(gate, controller.signal)).rejects.toThrow('cancelled before probing')
|
|
172
|
+
expect(probes).toBe(0)
|
|
173
|
+
})
|
|
174
|
+
})
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Process helpers shared by the swe-arena execution path (materialize /
|
|
3
|
+
* calibrate / arms / serialized-judge). One place owns spawn semantics so
|
|
4
|
+
* every port of a bash script gets identical rc/timeout behavior:
|
|
5
|
+
*
|
|
6
|
+
* - `run` never throws on a nonzero exit — the bash scripts branched on `$?`,
|
|
7
|
+
* so callers get `{ code, stdout, stderr, timedOut }` and decide.
|
|
8
|
+
* - timeouts signal the whole process GROUP (detached spawn), because the
|
|
9
|
+
* arm commands are `dotenvx → bash -c → opencode/node` chains; killing only
|
|
10
|
+
* the leader would orphan the model call exactly like a dropped `timeout`.
|
|
11
|
+
* SIGTERM gets a short cleanup window before SIGKILL so children can cancel
|
|
12
|
+
* their own detached workers and flush terminal evidence.
|
|
13
|
+
* - `code` is 124 on timeout, mirroring coreutils `timeout` so ledger rc
|
|
14
|
+
* fields keep the bash experiment's encoding.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { spawn } from 'node:child_process'
|
|
18
|
+
|
|
19
|
+
export interface RunResult {
|
|
20
|
+
code: number
|
|
21
|
+
stdout: string
|
|
22
|
+
stderr: string
|
|
23
|
+
timedOut: boolean
|
|
24
|
+
aborted: boolean
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface RunOptions {
|
|
28
|
+
cwd?: string
|
|
29
|
+
env?: NodeJS.ProcessEnv
|
|
30
|
+
/** 0 / undefined = no timeout. On expiry the process group gets TERM then KILL. */
|
|
31
|
+
timeoutMs?: number
|
|
32
|
+
/** Grace between timeout SIGTERM and fallback SIGKILL. Default 1 second. */
|
|
33
|
+
killGraceMs?: number
|
|
34
|
+
/** Cancels the complete process group and waits until it is gone. */
|
|
35
|
+
signal?: AbortSignal
|
|
36
|
+
/** Cap captured stdout/stderr (bytes); beyond it output is dropped, not buffered. */
|
|
37
|
+
maxBuffer?: number
|
|
38
|
+
/** Piped to the child's stdin, then stdin is closed. */
|
|
39
|
+
stdin?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const DEFAULT_MAX_BUFFER = 64 * 1024 * 1024
|
|
43
|
+
const PROCESS_GROUP_EXIT_CONFIRM_MS = 1_000
|
|
44
|
+
const PROCESS_GROUP_EXIT_POLL_MS = 10
|
|
45
|
+
|
|
46
|
+
const exitKillGroups = new Set<number>()
|
|
47
|
+
const killRegisteredGroupsOnExit = (): void => {
|
|
48
|
+
for (const processGroupId of exitKillGroups) {
|
|
49
|
+
try {
|
|
50
|
+
process.kill(process.platform === 'win32' ? processGroupId : -processGroupId, 'SIGKILL')
|
|
51
|
+
} catch {
|
|
52
|
+
// The group may have settled between its final async check and process exit.
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function registerExitKill(processGroupId: number | undefined): () => void {
|
|
58
|
+
if (processGroupId === undefined) return () => {}
|
|
59
|
+
if (exitKillGroups.size === 0) process.once('exit', killRegisteredGroupsOnExit)
|
|
60
|
+
exitKillGroups.add(processGroupId)
|
|
61
|
+
return () => {
|
|
62
|
+
exitKillGroups.delete(processGroupId)
|
|
63
|
+
if (exitKillGroups.size === 0) process.removeListener('exit', killRegisteredGroupsOnExit)
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** coreutils `timeout` exit code — kept so ledger rc columns stay comparable. */
|
|
68
|
+
export const TIMEOUT_RC = 124
|
|
69
|
+
export const ABORT_RC = 130
|
|
70
|
+
|
|
71
|
+
export interface ProcessSignalAbort {
|
|
72
|
+
signal: AbortSignal
|
|
73
|
+
/** First signal received; null until interrupted. */
|
|
74
|
+
readonly receivedSignal: NodeJS.Signals | null
|
|
75
|
+
/** Removes handlers after the caller has awaited cleanup. */
|
|
76
|
+
dispose: () => void
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Translate terminal interrupts into cooperative cancellation. The handler
|
|
81
|
+
* never exits immediately: callers await their normal cleanup in `finally`,
|
|
82
|
+
* then dispose it. Repeated interrupts remain cooperative rather than
|
|
83
|
+
* bypassing cleanup.
|
|
84
|
+
*/
|
|
85
|
+
export function installProcessSignalAbort(label: string): ProcessSignalAbort {
|
|
86
|
+
const controller = new AbortController()
|
|
87
|
+
let receivedSignal: NodeJS.Signals | null = null
|
|
88
|
+
const onSignal = (signal: NodeJS.Signals): void => {
|
|
89
|
+
if (receivedSignal !== null) return
|
|
90
|
+
receivedSignal = signal
|
|
91
|
+
process.exitCode = signal === 'SIGINT' ? 130 : 143
|
|
92
|
+
controller.abort(new Error(`${label} interrupted by ${signal}`))
|
|
93
|
+
}
|
|
94
|
+
const onSigint = (): void => onSignal('SIGINT')
|
|
95
|
+
const onSigterm = (): void => onSignal('SIGTERM')
|
|
96
|
+
process.on('SIGINT', onSigint)
|
|
97
|
+
process.on('SIGTERM', onSigterm)
|
|
98
|
+
return {
|
|
99
|
+
signal: controller.signal,
|
|
100
|
+
get receivedSignal() {
|
|
101
|
+
return receivedSignal
|
|
102
|
+
},
|
|
103
|
+
dispose: () => {
|
|
104
|
+
process.removeListener('SIGINT', onSigint)
|
|
105
|
+
process.removeListener('SIGTERM', onSigterm)
|
|
106
|
+
},
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function processGroupExists(processGroupId: number): boolean {
|
|
111
|
+
try {
|
|
112
|
+
process.kill(-processGroupId, 0)
|
|
113
|
+
return true
|
|
114
|
+
} catch (err) {
|
|
115
|
+
return (err as NodeJS.ErrnoException).code !== 'ESRCH'
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async function waitUntil(deadline: number, predicate: () => boolean): Promise<boolean> {
|
|
120
|
+
while (predicate()) {
|
|
121
|
+
if (Date.now() >= deadline) return false
|
|
122
|
+
await new Promise((resolve) => setTimeout(resolve, PROCESS_GROUP_EXIT_POLL_MS))
|
|
123
|
+
}
|
|
124
|
+
return true
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function run(bin: string, argv: string[], opts: RunOptions = {}): Promise<RunResult> {
|
|
128
|
+
opts.signal?.throwIfAborted()
|
|
129
|
+
return new Promise((resolve, reject) => {
|
|
130
|
+
const child = spawn(bin, argv, {
|
|
131
|
+
cwd: opts.cwd,
|
|
132
|
+
env: opts.env ?? process.env,
|
|
133
|
+
detached: true,
|
|
134
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
135
|
+
})
|
|
136
|
+
const unregisterExitKill = registerExitKill(child.pid)
|
|
137
|
+
const cap = opts.maxBuffer ?? DEFAULT_MAX_BUFFER
|
|
138
|
+
let stdout = ''
|
|
139
|
+
let stderr = ''
|
|
140
|
+
let outBytes = 0
|
|
141
|
+
let errBytes = 0
|
|
142
|
+
let timedOut = false
|
|
143
|
+
let aborted = false
|
|
144
|
+
let settled = false
|
|
145
|
+
let timer: NodeJS.Timeout | undefined
|
|
146
|
+
const signalGroup = (signal: NodeJS.Signals) => {
|
|
147
|
+
try {
|
|
148
|
+
process.kill(-child.pid!, signal)
|
|
149
|
+
} catch {
|
|
150
|
+
try {
|
|
151
|
+
child.kill(signal)
|
|
152
|
+
} catch {
|
|
153
|
+
/* already dead */
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
let termination: Promise<void> | undefined
|
|
158
|
+
const terminate = (): Promise<void> => {
|
|
159
|
+
termination ??= (async () => {
|
|
160
|
+
signalGroup('SIGTERM')
|
|
161
|
+
if (process.platform === 'win32' || typeof child.pid !== 'number') return
|
|
162
|
+
const processGroupId = child.pid
|
|
163
|
+
const exitedOnTerm = await waitUntil(
|
|
164
|
+
Date.now() + Math.max(0, opts.killGraceMs ?? 1_000),
|
|
165
|
+
() => processGroupExists(processGroupId),
|
|
166
|
+
)
|
|
167
|
+
if (exitedOnTerm) return
|
|
168
|
+
signalGroup('SIGKILL')
|
|
169
|
+
const exitedOnKill = await waitUntil(
|
|
170
|
+
Date.now() + PROCESS_GROUP_EXIT_CONFIRM_MS,
|
|
171
|
+
() => processGroupExists(processGroupId),
|
|
172
|
+
)
|
|
173
|
+
if (!exitedOnKill) throw new Error(`process group ${processGroupId} survived SIGKILL`)
|
|
174
|
+
})()
|
|
175
|
+
// The close handler owns the rejection. Attaching this handler prevents
|
|
176
|
+
// an early unhandled rejection while the direct child is still closing.
|
|
177
|
+
void termination.catch(() => undefined)
|
|
178
|
+
return termination
|
|
179
|
+
}
|
|
180
|
+
const onAbort = () => {
|
|
181
|
+
aborted = true
|
|
182
|
+
void terminate()
|
|
183
|
+
}
|
|
184
|
+
if (opts.timeoutMs && opts.timeoutMs > 0) {
|
|
185
|
+
timer = setTimeout(() => {
|
|
186
|
+
timedOut = true
|
|
187
|
+
void terminate()
|
|
188
|
+
}, opts.timeoutMs)
|
|
189
|
+
}
|
|
190
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true })
|
|
191
|
+
if (opts.signal?.aborted) onAbort()
|
|
192
|
+
child.stdout.on('data', (c: Buffer) => {
|
|
193
|
+
outBytes += c.length
|
|
194
|
+
if (outBytes <= cap) stdout += c.toString('utf8')
|
|
195
|
+
})
|
|
196
|
+
child.stderr.on('data', (c: Buffer) => {
|
|
197
|
+
errBytes += c.length
|
|
198
|
+
if (errBytes <= cap) stderr += c.toString('utf8')
|
|
199
|
+
})
|
|
200
|
+
child.on('error', (err) => {
|
|
201
|
+
if (settled) return
|
|
202
|
+
settled = true
|
|
203
|
+
if (timer) clearTimeout(timer)
|
|
204
|
+
opts.signal?.removeEventListener('abort', onAbort)
|
|
205
|
+
unregisterExitKill()
|
|
206
|
+
reject(err)
|
|
207
|
+
})
|
|
208
|
+
child.on('close', (code, signal) => {
|
|
209
|
+
if (settled) return
|
|
210
|
+
if (timer) clearTimeout(timer)
|
|
211
|
+
opts.signal?.removeEventListener('abort', onAbort)
|
|
212
|
+
void (async () => {
|
|
213
|
+
try {
|
|
214
|
+
if (
|
|
215
|
+
!termination &&
|
|
216
|
+
process.platform !== 'win32' &&
|
|
217
|
+
typeof child.pid === 'number' &&
|
|
218
|
+
processGroupExists(child.pid)
|
|
219
|
+
) {
|
|
220
|
+
await terminate()
|
|
221
|
+
}
|
|
222
|
+
if (termination) await termination
|
|
223
|
+
if (settled) return
|
|
224
|
+
settled = true
|
|
225
|
+
unregisterExitKill()
|
|
226
|
+
resolve({
|
|
227
|
+
code: timedOut ? TIMEOUT_RC : aborted ? ABORT_RC : (code ?? (signal ? 1 : 0)),
|
|
228
|
+
stdout,
|
|
229
|
+
stderr,
|
|
230
|
+
timedOut,
|
|
231
|
+
aborted,
|
|
232
|
+
})
|
|
233
|
+
} catch (err) {
|
|
234
|
+
if (settled) return
|
|
235
|
+
settled = true
|
|
236
|
+
unregisterExitKill()
|
|
237
|
+
reject(err)
|
|
238
|
+
}
|
|
239
|
+
})()
|
|
240
|
+
})
|
|
241
|
+
if (opts.stdin !== undefined) child.stdin.end(opts.stdin)
|
|
242
|
+
else child.stdin.end()
|
|
243
|
+
})
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** `run` that throws (with captured stderr) on nonzero exit — for steps the bash aborted on. */
|
|
247
|
+
export async function runOk(bin: string, argv: string[], opts: RunOptions = {}): Promise<RunResult> {
|
|
248
|
+
const res = await run(bin, argv, opts)
|
|
249
|
+
opts.signal?.throwIfAborted()
|
|
250
|
+
if (res.code !== 0) {
|
|
251
|
+
const detail = (res.stderr || res.stdout).slice(0, 1500)
|
|
252
|
+
throw new Error(`${bin} ${argv.join(' ')} exited ${res.code}${res.timedOut ? ' (timeout)' : ''}: ${detail}`)
|
|
253
|
+
}
|
|
254
|
+
return res
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/** Single-quote shell escaping — identical to the quoting the bash scripts relied on. */
|
|
258
|
+
export function shq(value: string): string {
|
|
259
|
+
return `'${value.replace(/'/g, `'\\''`)}'`
|
|
260
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "swe-arena-default-author",
|
|
3
|
+
"description": "The gen-2 winning author seat, codified: bare claude CLI invocation. No systemPrompt, no instructions, no model override — harnessInvocation() with this profile is byte-identical to the legacy prompt-only buildArgs path, so provenance pins the author identity without changing gen-2 behavior."
|
|
4
|
+
}
|