@tangle-network/agent-bench 0.11.2 → 0.13.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.
Files changed (174) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/HARNESS.md +6 -2
  3. package/README.md +1 -4
  4. package/dist/benchmarks/swe-bench.js +4 -9
  5. package/dist/benchmarks/swe-bench.js.map +1 -1
  6. package/package.json +5 -5
  7. package/scripts/run-package-tests.mjs +2 -2
  8. package/src/benchmarks/swe-bench.test.mts +49 -0
  9. package/src/benchmarks/swe-bench.ts +4 -9
  10. package/src/quant-arena/README.md +0 -144
  11. package/src/quant-arena/backtest.test.mts +0 -135
  12. package/src/quant-arena/backtest.ts +0 -218
  13. package/src/quant-arena/data.test.mts +0 -44
  14. package/src/quant-arena/data.ts +0 -141
  15. package/src/quant-arena/driver.test.mts +0 -253
  16. package/src/quant-arena/driver.ts +0 -219
  17. package/src/quant-arena/fixtures/data/PROVENANCE.md +0 -26
  18. package/src/quant-arena/fixtures/data/holdout/IDX.csv +0 -523
  19. package/src/quant-arena/fixtures/data/holdout/S01.csv +0 -523
  20. package/src/quant-arena/fixtures/data/holdout/S02.csv +0 -523
  21. package/src/quant-arena/fixtures/data/holdout/S03.csv +0 -523
  22. package/src/quant-arena/fixtures/data/holdout/S04.csv +0 -523
  23. package/src/quant-arena/fixtures/data/holdout/S05.csv +0 -523
  24. package/src/quant-arena/fixtures/data/holdout/S06.csv +0 -523
  25. package/src/quant-arena/fixtures/data/holdout/S07.csv +0 -523
  26. package/src/quant-arena/fixtures/data/holdout/S08.csv +0 -523
  27. package/src/quant-arena/fixtures/data/holdout/S09.csv +0 -523
  28. package/src/quant-arena/fixtures/data/holdout/S10.csv +0 -523
  29. package/src/quant-arena/fixtures/data/insample/IDX.csv +0 -2087
  30. package/src/quant-arena/fixtures/data/insample/S01.csv +0 -2087
  31. package/src/quant-arena/fixtures/data/insample/S02.csv +0 -2087
  32. package/src/quant-arena/fixtures/data/insample/S03.csv +0 -2087
  33. package/src/quant-arena/fixtures/data/insample/S04.csv +0 -2087
  34. package/src/quant-arena/fixtures/data/insample/S05.csv +0 -2087
  35. package/src/quant-arena/fixtures/data/insample/S06.csv +0 -2087
  36. package/src/quant-arena/fixtures/data/insample/S07.csv +0 -2087
  37. package/src/quant-arena/fixtures/data/insample/S08.csv +0 -2087
  38. package/src/quant-arena/fixtures/data/insample/S09.csv +0 -2087
  39. package/src/quant-arena/fixtures/data/insample/S10.csv +0 -2087
  40. package/src/quant-arena/fixtures/demo-campaign/cost-ledger.jsonl +0 -16
  41. package/src/quant-arena/fixtures/demo-campaign/notebook.jsonl +0 -5
  42. package/src/quant-arena/fixtures/demo-campaign/rollout-manifest.json +0 -171
  43. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-001-default-author/strategy.ts +0 -119
  44. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-002-default-author/strategy.ts +0 -119
  45. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-003-quant-researcher/strategy.ts +0 -105
  46. package/src/quant-arena/fixtures/demo-campaign/strategies/cand-004-quant-researcher/strategy.ts +0 -102
  47. package/src/quant-arena/fixtures/demo-campaign-v2/cost-ledger.jsonl +0 -4
  48. package/src/quant-arena/fixtures/demo-campaign-v2/notebook.jsonl +0 -2
  49. package/src/quant-arena/fixtures/demo-campaign-v2/rollout-manifest.json +0 -84
  50. package/src/quant-arena/fixtures/demo-campaign-v2/strategies/cand-001-quant-researcher/strategy.ts +0 -117
  51. package/src/quant-arena/holdout-certify.mts +0 -206
  52. package/src/quant-arena/holdout-certify.test.mts +0 -82
  53. package/src/quant-arena/leak-audit.test.mts +0 -79
  54. package/src/quant-arena/leak-audit.ts +0 -95
  55. package/src/quant-arena/make-fixtures.mts +0 -161
  56. package/src/quant-arena/multiplicity.test.mts +0 -68
  57. package/src/quant-arena/multiplicity.ts +0 -87
  58. package/src/quant-arena/nautilus-certify.ts +0 -31
  59. package/src/quant-arena/oms.ts +0 -90
  60. package/src/quant-arena/profiles/quant-researcher.profile.json +0 -12
  61. package/src/quant-arena/python/pyproject.toml +0 -8
  62. package/src/quant-arena/python/uv.lock +0 -1297
  63. package/src/quant-arena/python/vbt-worker.py +0 -192
  64. package/src/quant-arena/quant-loop.mts +0 -840
  65. package/src/quant-arena/quant-loop.test.mts +0 -75
  66. package/src/quant-arena/strategies/buy-hold-index/strategy.ts +0 -11
  67. package/src/quant-arena/strategies/equal-weight/strategy.ts +0 -20
  68. package/src/quant-arena/strategies/sma-crossover/strategy.ts +0 -42
  69. package/src/quant-arena/types.ts +0 -133
  70. package/src/quant-arena/vbt-client.ts +0 -321
  71. package/src/quant-arena/vbt-parity.test.mts +0 -183
  72. package/src/quant-arena/windows.test.mts +0 -45
  73. package/src/quant-arena/windows.ts +0 -54
  74. package/src/rollout-ledger/backfill-swe-arena.mts +0 -610
  75. package/src/rollout-ledger/backfill-swe-arena.test.mts +0 -347
  76. package/src/rollout-ledger/settle-capture.mts +0 -448
  77. package/src/rollout-ledger/settle-capture.test.mts +0 -270
  78. package/src/swe-arena/activation.mts +0 -225
  79. package/src/swe-arena/activation.test.mts +0 -300
  80. package/src/swe-arena/analyze.ts +0 -211
  81. package/src/swe-arena/arms.ts +0 -862
  82. package/src/swe-arena/bootstrap-meta.mts +0 -188
  83. package/src/swe-arena/bootstrap-meta.test.mts +0 -51
  84. package/src/swe-arena/briefing.mts +0 -217
  85. package/src/swe-arena/briefing.test.mts +0 -179
  86. package/src/swe-arena/calibrate.ts +0 -217
  87. package/src/swe-arena/capabilities.mts +0 -76
  88. package/src/swe-arena/capabilities.test.mts +0 -57
  89. package/src/swe-arena/capacity.ts +0 -198
  90. package/src/swe-arena/cell-evidence.mts +0 -437
  91. package/src/swe-arena/cell-evidence.test.mts +0 -248
  92. package/src/swe-arena/diagnosis-ensemble.test.mts +0 -210
  93. package/src/swe-arena/diagnosis-ensemble.ts +0 -523
  94. package/src/swe-arena/execution.test.mts +0 -1171
  95. package/src/swe-arena/factory-command-container.ts +0 -284
  96. package/src/swe-arena/factory-judge-child.mts +0 -228
  97. package/src/swe-arena/factory.test.mts +0 -645
  98. package/src/swe-arena/fixtures/analyze.py +0 -80
  99. package/src/swe-arena/fixtures/excludes.txt +0 -8
  100. package/src/swe-arena/fixtures/factory/agent-eval-309/calibration.md +0 -51
  101. package/src/swe-arena/fixtures/factory/agent-eval-309/manifest.json +0 -29
  102. package/src/swe-arena/fixtures/factory/agent-eval-309/spec.md +0 -64
  103. package/src/swe-arena/fixtures/factory/agent-runtime-232/calibration.md +0 -48
  104. package/src/swe-arena/fixtures/factory/agent-runtime-232/manifest.json +0 -29
  105. package/src/swe-arena/fixtures/factory/agent-runtime-232/spec.md +0 -48
  106. package/src/swe-arena/fixtures/factory/loops-28/calibration.md +0 -47
  107. package/src/swe-arena/fixtures/factory/loops-28/manifest.json +0 -30
  108. package/src/swe-arena/fixtures/factory/loops-28/spec.md +0 -50
  109. package/src/swe-arena/fixtures/gen1-salvage/README.md +0 -45
  110. package/src/swe-arena/fixtures/gen1-salvage/cand0-e6d7361.diff +0 -116
  111. package/src/swe-arena/fixtures/gen1-salvage/cand1-76a8590.diff +0 -293
  112. package/src/swe-arena/fixtures/holdout-preregister.log +0 -12
  113. package/src/swe-arena/fixtures/holdout.json +0 -44
  114. package/src/swe-arena/fixtures/instances.json +0 -146
  115. package/src/swe-arena/fixtures/ledger.jsonl +0 -12
  116. package/src/swe-arena/fixtures/patches/pallets__flask-5014.solo.patch +0 -36
  117. package/src/swe-arena/fixtures/patches/pydata__xarray-4687.sup.patch +0 -33
  118. package/src/swe-arena/fixtures/rejudge.jsonl +0 -15
  119. package/src/swe-arena/fixtures/rematch.jsonl +0 -3
  120. package/src/swe-arena/fixtures/rematch2.jsonl +0 -3
  121. package/src/swe-arena/fixtures/rematch3.jsonl +0 -3
  122. package/src/swe-arena/fixtures/run-report/README.md +0 -43
  123. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.json +0 -173
  124. package/src/swe-arena/fixtures/run-report/factory-agent-eval-309-FSUP0.md +0 -100
  125. package/src/swe-arena/fixtures/run-report/gen3-rollup.json +0 -551
  126. package/src/swe-arena/fixtures/run-report/gen3-rollup.md +0 -64
  127. package/src/swe-arena/fixtures/sup-journal-true.json +0 -19
  128. package/src/swe-arena/fixtures/verify/astropy__astropy-13033.sh +0 -48
  129. package/src/swe-arena/fixtures/verify/django__django-11532.sh +0 -50
  130. package/src/swe-arena/fixtures/verify/matplotlib__matplotlib-20826.sh +0 -76
  131. package/src/swe-arena/fixtures/verify/pydata__xarray-4687.sh +0 -44
  132. package/src/swe-arena/fixtures/verify/pytest-dev__pytest-6197.sh +0 -32
  133. package/src/swe-arena/fixtures/verify/sphinx-doc__sphinx-9658.sh +0 -51
  134. package/src/swe-arena/fixtures/worker-tokens.json +0 -42
  135. package/src/swe-arena/fixtures.ts +0 -237
  136. package/src/swe-arena/gepa-seat.mts +0 -886
  137. package/src/swe-arena/gepa-seat.test.mts +0 -1136
  138. package/src/swe-arena/holdout-certify.mts +0 -408
  139. package/src/swe-arena/holdout-certify.test.mts +0 -160
  140. package/src/swe-arena/implementation-ref.test.mts +0 -64
  141. package/src/swe-arena/implementation-ref.ts +0 -62
  142. package/src/swe-arena/judge-child.mts +0 -37
  143. package/src/swe-arena/ledger-orphans.mts +0 -77
  144. package/src/swe-arena/ledger-orphans.test.mts +0 -149
  145. package/src/swe-arena/manifest.mts +0 -293
  146. package/src/swe-arena/manifest.test.mts +0 -169
  147. package/src/swe-arena/materialize.ts +0 -142
  148. package/src/swe-arena/outer-loop.mts +0 -2854
  149. package/src/swe-arena/outer-loop.test.mts +0 -714
  150. package/src/swe-arena/parity.test.mts +0 -87
  151. package/src/swe-arena/premeasured-from-cells.mts +0 -296
  152. package/src/swe-arena/premeasured-from-cells.test.mts +0 -201
  153. package/src/swe-arena/proc.test.mts +0 -172
  154. package/src/swe-arena/proc.ts +0 -260
  155. package/src/swe-arena/profiles/deepseek-author.profile.json +0 -12
  156. package/src/swe-arena/profiles/default-author.profile.json +0 -12
  157. package/src/swe-arena/proposer-fanout.mts +0 -736
  158. package/src/swe-arena/proposer-fanout.test.mts +0 -660
  159. package/src/swe-arena/proposer-provenance.mts +0 -176
  160. package/src/swe-arena/proposer-provenance.test.mts +0 -106
  161. package/src/swe-arena/reconcile.ts +0 -0
  162. package/src/swe-arena/replay.mts +0 -183
  163. package/src/swe-arena/replay.test.mts +0 -300
  164. package/src/swe-arena/run-experiment.mts +0 -729
  165. package/src/swe-arena/run-report.mts +0 -75
  166. package/src/swe-arena/run-supervisor.mjs +0 -297
  167. package/src/swe-arena/run-supervisor.test.mts +0 -539
  168. package/src/swe-arena/score-split.mts +0 -140
  169. package/src/swe-arena/score-split.test.mts +0 -123
  170. package/src/swe-arena/scratch-worktree-serialization.test.mts +0 -72
  171. package/src/swe-arena/scratch-worktree.test.mts +0 -56
  172. package/src/swe-arena/scratch-worktree.ts +0 -64
  173. package/src/swe-arena/serialized-judge.ts +0 -414
  174. package/src/swe-arena/types.ts +0 -218
@@ -1,75 +0,0 @@
1
- /**
2
- * CLI over the supervisor-run reader. NO metric logic lives here.
3
- *
4
- * The reader itself is `@tangle-network/agent-eval/supervisor-run` — a
5
- * supervision tree is a rollout trace with one more dimension, so it sits in
6
- * the trace-analysis layer next to single-rollout analysis, beside the
7
- * `tangle.rollout.v1` ledger whose row type its tree nodes ARE. This file is
8
- * only argv parsing plus the entry points the arenas already call.
9
- *
10
- * Harness-session view of the same run (model calls, latency, stuck loops,
11
- * tool errors):
12
- * `npx @tangle-network/traces analyze --harness opencode --cwd <worker-clone-cwd>`.
13
- */
14
-
15
- import { pathToFileURL } from 'node:url'
16
- import {
17
- renderSupervisorRunMarkdown,
18
- reportSupervisorRound,
19
- type WriteSupervisorRunOptions,
20
- writeSupervisorRunReport,
21
- } from '@tangle-network/agent-eval/supervisor-run'
22
-
23
- const isMain =
24
- process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href
25
-
26
- if (isMain) {
27
- const args = process.argv.slice(2)
28
- const usage =
29
- 'usage:\n' +
30
- ' tsx run-report.mts <cellDir> [--log <run.log>] [--patch <file>] [--ledger <ledger.jsonl>] [--report-dir <dir>] [--no-opencode]\n' +
31
- ' tsx run-report.mts --round <outDir> [--log <run.log>] [--ledger <ledger.jsonl>] [--report-dir <dir>] [--no-opencode]\n' +
32
- '\n--report-dir writes the reports outside the run directory (use it when the run dir is READ-ONLY).\n'
33
- const noOpencode = args.includes('--no-opencode')
34
- const flagValue = (flag: string): string | undefined => {
35
- const i = args.indexOf(flag)
36
- return i >= 0 ? args[i + 1] : undefined
37
- }
38
- const appendHeadlineTo = flagValue('--log')
39
- const patchPath = flagValue('--patch')
40
- const reportDir = flagValue('--report-dir')
41
- const ledgerPath = flagValue('--ledger')
42
- const flagValueIndices = new Set(
43
- ['--log', '--patch', '--report-dir', '--ledger', '--round']
44
- .map((f) => args.indexOf(f))
45
- .filter((i) => i >= 0)
46
- .map((i) => i + 1),
47
- )
48
- const positional = args.filter((a, i) => !a.startsWith('--') && !flagValueIndices.has(i))
49
- const roundIdx = args.indexOf('--round')
50
- const opts: WriteSupervisorRunOptions = {
51
- ...(appendHeadlineTo !== undefined ? { appendHeadlineTo } : {}),
52
- ...(patchPath !== undefined ? { patchPath } : {}),
53
- ...(reportDir !== undefined ? { reportDir } : {}),
54
- ...(ledgerPath !== undefined ? { ledgerPath } : {}),
55
- ...(noOpencode ? { opencodeDb: null } : {}),
56
- echo: true,
57
- }
58
- if (roundIdx >= 0) {
59
- const outDir = args[roundIdx + 1]
60
- if (outDir === undefined) {
61
- console.error(usage)
62
- process.exit(2)
63
- }
64
- await reportSupervisorRound(outDir, opts)
65
- } else {
66
- const cellDir = positional[0]
67
- if (cellDir === undefined) {
68
- console.error(usage)
69
- process.exit(2)
70
- }
71
- const report = await writeSupervisorRunReport(cellDir, opts)
72
- console.log('')
73
- console.log(renderSupervisorRunMarkdown(report))
74
- }
75
- }
@@ -1,297 +0,0 @@
1
- /**
2
- * Thin driver over the REAL loops pi extension. It constructs a minimal
3
- * ExtensionAPI, calls the extension's default export to register the real tools
4
- * (spawn_supervisor / supervisor_status / supervisor_watch / compute_watch), then
5
- * invokes the REAL spawn_supervisor tool and polls the on-disk run dir until the
6
- * supervisor settles. No supervisor logic is reimplemented — this only replaces
7
- * pi's chat operator as the caller of the already-registered tool.
8
- *
9
- * usage: node --import tsx run-supervisor.mjs <extPath> <cwd> <paramsJsonPath>
10
- */
11
- import { existsSync, readFileSync, readdirSync } from 'node:fs'
12
- import { join } from 'node:path'
13
- import { pathToFileURL } from 'node:url'
14
-
15
- const [extPath, cwd, paramsPath] = process.argv.slice(2)
16
- if (!extPath || !cwd || !paramsPath) {
17
- console.error('usage: node --import tsx run-supervisor.mjs <extPath> <cwd> <paramsJsonPath>')
18
- process.exit(2)
19
- }
20
- const params = JSON.parse(readFileSync(paramsPath, 'utf8'))
21
-
22
- const tools = new Map()
23
- const pi = {
24
- on() {},
25
- registerTool(t) { tools.set(t.name, t) },
26
- }
27
-
28
- const mod = await import(pathToFileURL(extPath).href)
29
- mod.default(pi)
30
- console.log(`[driver] registered tools: ${[...tools.keys()].join(', ')}`)
31
-
32
- const ctx = { cwd }
33
- const spawn = tools.get('spawn_supervisor')
34
- const cancel = tools.get('supervisor_cancel')
35
- if (!spawn || !cancel) {
36
- console.error('[driver] extension must register spawn_supervisor and supervisor_cancel')
37
- process.exit(2)
38
- }
39
-
40
- const positiveNumberEnv = (name, fallback) => {
41
- const value = Number(process.env[name] ?? fallback)
42
- if (!Number.isFinite(value) || value <= 0) throw new Error(`${name} must be a positive number`)
43
- return value
44
- }
45
- const deadlineMs = positiveNumberEnv('DRIVER_DEADLINE_MS', 25 * 60 * 1000)
46
- const pollMs = positiveNumberEnv('DRIVER_POLL_MS', 4000)
47
- const cancelTimeoutMs = positiveNumberEnv('DRIVER_CANCEL_TIMEOUT_MS', 30_000)
48
- const settlementTimeoutMs = positiveNumberEnv('DRIVER_SETTLEMENT_TIMEOUT_MS', cancelTimeoutMs)
49
- const t0 = Date.now()
50
- const supervisorRoot = join(cwd, '.loops', 'supervisor')
51
- const readJson = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')) } catch { return undefined } }
52
- const tail = (p, n) => {
53
- if (!existsSync(p)) return []
54
- const lines = readFileSync(p, 'utf8').split('\n').filter(Boolean)
55
- return lines.slice(-n)
56
- }
57
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
58
- const listSupervisorIds = () => {
59
- try {
60
- return readdirSync(supervisorRoot, { withFileTypes: true })
61
- .filter((entry) => entry.isDirectory() && /^sup-\d+-[a-z0-9]+$/i.test(entry.name))
62
- .map((entry) => entry.name)
63
- .sort()
64
- } catch {
65
- return []
66
- }
67
- }
68
- const idsBeforeSpawn = new Set(listSupervisorIds())
69
- const runDirFor = (id) => join(supervisorRoot, id)
70
-
71
- const workerSettlement = (id) => {
72
- const runDir = runDirFor(id)
73
- const status = readJson(join(runDir, 'state.json'))?.status ?? 'missing'
74
- const journalPath = join(runDir, 'journal.jsonl')
75
- const lines = tail(journalPath, Number.MAX_SAFE_INTEGER)
76
- let invalidLines = 0
77
- const events = lines.flatMap((line) => {
78
- try { return [JSON.parse(line)] } catch { invalidLines += 1; return [] }
79
- })
80
- const rootSpawned = events.some((event) => event.kind === 'spawned' && event.id === id && !event.parent)
81
- const spawnedEvents = events.filter((event) => event.kind === 'spawned' && event.parent)
82
- let missingIds = 0
83
- const workerIds = new Set()
84
- for (const event of spawnedEvents) {
85
- if (typeof event.id === 'string' && event.id.length > 0) workerIds.add(event.id)
86
- else missingIds += 1
87
- }
88
- const terminalIds = new Set(events.flatMap((event) =>
89
- (event.kind === 'settled' || event.kind === 'cancelled') && typeof event.id === 'string' ? [event.id] : [],
90
- ))
91
- const unsettled = [...workerIds].filter((workerId) => !terminalIds.has(workerId))
92
- return {
93
- status,
94
- journalPresent: existsSync(journalPath),
95
- rootSpawned,
96
- invalidLines,
97
- workers: workerIds.size,
98
- terminal: workerIds.size - unsettled.length,
99
- missingIds,
100
- unsettled,
101
- }
102
- }
103
-
104
- const hasTerminalWorkerEvidence = (settlement) =>
105
- settlement.journalPresent &&
106
- settlement.rootSpawned &&
107
- settlement.invalidLines === 0 &&
108
- settlement.missingIds === 0 &&
109
- settlement.unsettled.length === 0
110
-
111
- const settlementProblem = (settlement) =>
112
- `status=${settlement.status}, journal=${settlement.journalPresent ? 'present' : 'missing'}, root=${settlement.rootSpawned ? 'present' : 'missing'}, ` +
113
- `workers=${settlement.workers}, terminal=${settlement.terminal}, unsettled=${settlement.unsettled.length}, ` +
114
- `missingIds=${settlement.missingIds}, invalidLines=${settlement.invalidLines}`
115
-
116
- const withTimeout = (promise, timeoutMs, message) => new Promise((resolve, reject) => {
117
- const timer = setTimeout(() => reject(new Error(message)), timeoutMs)
118
- promise.then(
119
- (value) => { clearTimeout(timer); resolve(value) },
120
- (err) => { clearTimeout(timer); reject(err) },
121
- )
122
- })
123
-
124
- const cancellations = new Map()
125
- const cancelAndSettle = (id, reason, deadline = Date.now() + cancelTimeoutMs) => {
126
- if (cancellations.has(id)) return cancellations.get(id)
127
- const cancellation = (async () => {
128
- console.error(`[driver] cancelling ${id}: ${reason}`)
129
- const result = await withTimeout(
130
- Promise.resolve(cancel.execute(`cancel-${id}`, { id }, undefined, () => {}, ctx)),
131
- Math.max(1, deadline - Date.now()),
132
- `supervisor cancellation did not settle within ${cancelTimeoutMs}ms`,
133
- )
134
- const message = result?.content?.[0]?.text ?? ''
135
- while (true) {
136
- const settlement = workerSettlement(id)
137
- const terminalStatus = ['completed', 'failed', 'cancelled'].includes(settlement.status)
138
- if (terminalStatus && hasTerminalWorkerEvidence(settlement)) {
139
- console.error(`[driver] cancellation settled: workers=${settlement.workers}, terminal=${settlement.terminal}; ${message}`)
140
- return settlement
141
- }
142
- if (Date.now() >= deadline) {
143
- throw new Error(`supervisor cancellation left ${settlementProblem(settlement)}`)
144
- }
145
- await sleep(Math.min(pollMs, 250, Math.max(1, deadline - Date.now())))
146
- }
147
- })()
148
- cancellations.set(id, cancellation)
149
- return cancellation
150
- }
151
-
152
- let parsedId
153
- let spawnSettled = false
154
- let receivedSignal
155
- let signalExitPromise
156
- const startedIds = () => {
157
- const ids = listSupervisorIds().filter((id) => !idsBeforeSpawn.has(id))
158
- if (parsedId && !ids.includes(parsedId)) ids.push(parsedId)
159
- return ids.sort()
160
- }
161
- const waitForStartedIds = async (deadline) => {
162
- while (true) {
163
- const ids = startedIds()
164
- if (ids.length > 0 || spawnSettled) return ids
165
- if (Date.now() >= deadline) {
166
- throw new Error(`spawn did not expose a supervisor id within ${cancelTimeoutMs}ms`)
167
- }
168
- await sleep(Math.min(pollMs, 50, Math.max(1, deadline - Date.now())))
169
- }
170
- }
171
- const cancelStartedRuns = async (reason, deadline) => {
172
- const ids = await waitForStartedIds(deadline)
173
- await Promise.all(ids.map((id) => cancelAndSettle(id, reason, deadline)))
174
- return ids
175
- }
176
- const finishSignalExit = () => {
177
- if (!receivedSignal) return Promise.resolve()
178
- signalExitPromise ??= (async () => {
179
- const { signal, code } = receivedSignal
180
- try {
181
- await cancelStartedRuns(`driver received ${signal}`, Date.now() + cancelTimeoutMs)
182
- process.exit(code)
183
- } catch (err) {
184
- console.error(`[driver] cancellation failed: ${err instanceof Error ? err.message : String(err)}`)
185
- process.exit(4)
186
- }
187
- })()
188
- return signalExitPromise
189
- }
190
-
191
- for (const [signal, code] of [['SIGINT', 130], ['SIGTERM', 143]]) {
192
- process.once(signal, () => {
193
- if (receivedSignal) return
194
- receivedSignal = { signal, code }
195
- void finishSignalExit()
196
- })
197
- }
198
-
199
- let res
200
- let spawnError
201
- try {
202
- res = await spawn.execute('call-1', params, undefined, () => {}, ctx)
203
- const responseText = res?.content?.[0]?.text ?? ''
204
- parsedId = responseText.match(/supervisor (sup-\d+-[a-z0-9]+)/i)?.[1]
205
- } catch (err) {
206
- spawnError = err
207
- } finally {
208
- spawnSettled = true
209
- }
210
-
211
- if (receivedSignal) await finishSignalExit()
212
-
213
- const text = res?.content?.[0]?.text ?? ''
214
- if (res) console.log(`[driver] spawn_supervisor returned: ${text}`)
215
- if (spawnError || !parsedId) {
216
- const ids = startedIds()
217
- if (ids.length > 0) {
218
- console.error(`[driver] spawn did not return a usable id; cancelling recovered run(s): ${ids.join(', ')}`)
219
- try {
220
- const deadline = Date.now() + cancelTimeoutMs
221
- await Promise.all(ids.map((id) => cancelAndSettle(id, 'spawn did not return a usable supervisor id', deadline)))
222
- } catch (err) {
223
- console.error(`[driver] recovered-run cancellation failed: ${err instanceof Error ? err.message : String(err)}`)
224
- process.exit(4)
225
- }
226
- }
227
- if (spawnError) {
228
- console.error(`[driver] spawn_supervisor failed: ${spawnError instanceof Error ? spawnError.message : String(spawnError)}`)
229
- } else {
230
- console.error('[driver] could not parse supervisor id')
231
- }
232
- process.exit(1)
233
- }
234
-
235
- const id = parsedId
236
- const runDir = runDirFor(id)
237
- const waitForCompletedSettlement = async () => {
238
- const deadline = Date.now() + settlementTimeoutMs
239
- while (true) {
240
- const settlement = workerSettlement(id)
241
- if (settlement.status !== 'completed' || hasTerminalWorkerEvidence(settlement)) return settlement
242
- if (Date.now() >= deadline) {
243
- throw new Error(`completed supervisor lacks terminal worker evidence after ${settlementTimeoutMs}ms: ${settlementProblem(settlement)}`)
244
- }
245
- await sleep(Math.min(pollMs, 250, Math.max(1, deadline - Date.now())))
246
- }
247
- }
248
-
249
- let last = ''
250
- while (true) {
251
- const st = readJson(join(runDir, 'state.json'))
252
- const status = st?.status ?? 'pending'
253
- const progress = st?.progress ?? ''
254
- const journal = tail(join(runDir, 'journal.jsonl'), 40)
255
- const spawned = journal.filter((l) => l.includes('"kind":"spawned"')).length
256
- const settled = journal.filter((l) => l.includes('"kind":"settled"')).length
257
- const stamp = `${((Date.now() - t0) / 1000).toFixed(0)}s status=${status} progress="${progress}" journal(spawned=${spawned},settled=${settled})`
258
- if (stamp !== last) { console.log(`[watch] ${stamp}`); last = stamp }
259
- if (st && ['completed', 'failed', 'cancelled'].includes(st.status)) {
260
- const terminalStatus = st.status
261
- let settlement = workerSettlement(id)
262
- if (st.status === 'completed') {
263
- try {
264
- settlement = await waitForCompletedSettlement()
265
- } catch (err) {
266
- console.error(`[driver] refusing completed supervisor: ${err instanceof Error ? err.message : String(err)}`)
267
- process.exit(4)
268
- }
269
- if (settlement.status !== 'completed') continue
270
- } else if (!hasTerminalWorkerEvidence(settlement)) {
271
- try {
272
- settlement = await cancelAndSettle(
273
- id,
274
- `supervisor entered ${terminalStatus} before its workers settled`,
275
- )
276
- } catch (err) {
277
- console.error(`[driver] terminal supervisor cleanup failed: ${err instanceof Error ? err.message : String(err)}`)
278
- process.exit(4)
279
- }
280
- }
281
- console.log(`\n[done] id=${id} status=${terminalStatus} verdict=${st.verdict ?? ''} result=${JSON.stringify(st.result ?? {})} error=${st.error ?? ''}`)
282
- console.log(`[done] worker settlement: workers=${settlement.workers}, terminal=${settlement.terminal}`)
283
- console.log(`[done] runDir=${runDir}`)
284
- process.exit(terminalStatus === 'completed' ? 0 : 1)
285
- }
286
- if (Date.now() - t0 > deadlineMs) {
287
- console.error(`[driver] deadline exceeded (${deadlineMs}ms) — supervisor still ${status}. runDir=${runDir}`)
288
- try {
289
- await cancelAndSettle(id, 'driver deadline exceeded')
290
- } catch (err) {
291
- console.error(`[driver] cancellation failed: ${err instanceof Error ? err.message : String(err)}`)
292
- process.exit(4)
293
- }
294
- process.exit(3)
295
- }
296
- await sleep(pollMs)
297
- }