@tangle-network/agent-bench 0.14.1 → 0.14.4

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 (40) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/package.json +6 -6
  3. package/scripts/verify-packed-consumer.mjs +0 -1
  4. package/src/atom-mcp-e2e.mts +14 -2
  5. package/src/coordination-mcp-container-reach.mts +5 -5
  6. package/src/gate.ts +1 -1
  7. package/src/mcp-mount-probe.mts +7 -5
  8. package/src/run-benchmarks.test.mts +0 -4
  9. package/src/search-bench/profiles.ts +1 -1
  10. package/src/tb-supervisor-sidecar.mts +1 -1
  11. package/tb_agents/opencode_supervisor_agent.py +2 -2
  12. package/src/browser/adapters/bad-design-audit.ts +0 -153
  13. package/src/browser/adapters/bad-design-audit.verify.ts +0 -85
  14. package/src/browser/adapters/bad.ts +0 -165
  15. package/src/browser/agent-adapter.ts +0 -145
  16. package/src/browser/process-adapter.ts +0 -146
  17. package/src/browser/run-to-spans.ts +0 -105
  18. package/src/browser/run-to-spans.verify.ts +0 -89
  19. package/src/browser/ui-reviewer.ts +0 -200
  20. package/src/browser/ui-reviewer.verify.ts +0 -94
  21. package/src/browser/verify.ts +0 -96
  22. package/src/clbench-codebase-gate.mts +0 -314
  23. package/src/clbench-context-gate.mts +0 -341
  24. package/src/commit0-env-run.mts +0 -62
  25. package/src/commit0-env.ts +0 -172
  26. package/src/commit0-gate.mts +0 -558
  27. package/src/egress-probe.mts +0 -26
  28. package/src/humaneval-repair-gate.mts +0 -182
  29. package/src/profile-coordinates.ts +0 -134
  30. package/src/run-benchmarks-report.ts +0 -66
  31. package/src/skill-sandbox-smoke.mts +0 -101
  32. package/src/supervisor-arena.mts +0 -825
  33. package/src/swe-emit-patch.mts +0 -125
  34. package/src/swe-local-proof.mts +0 -265
  35. package/src/swe-repro-calibrate.mts +0 -451
  36. package/src/swe-stream.mts +0 -1561
  37. package/src/trajectory-assemble.mjs +0 -130
  38. package/src/worker-browser.ts +0 -115
  39. package/src/worker-cad.ts +0 -470
  40. package/src/workspace-loop.mts +0 -133
@@ -1,182 +0,0 @@
1
- /**
2
- * HumanEval self-repair gate — the TOOL-USING router backend vs blind resampling
3
- * at equal compute, the strongest form of the steering question.
4
- *
5
- * The earlier steering gate (the rsi analyst arm) used an LLM that AUDITED the
6
- * prior code WITHOUT running it — and was a null (−1.2pp, n.s.). This removes that
7
- * weakness: the worker gets a `run_tests` tool (the deployable Docker checker), so
8
- * it actually RUNS the tests, sees the real failure, and fixes — execution-grounded
9
- * self-repair, off-box over the Tangle router's tool-calling (no sandbox). If
10
- * steering ever beats compute on a deployable checker, this is where it should.
11
- *
12
- * blind@K — K independent completions, verifier-grounded pick (breadth/resample)
13
- * repair@K — ONE worker, up to K tool-turns: write → run_tests → fix → … (depth/tool-grounded)
14
- *
15
- * Equal budget: one inference turn = one router completion, so both arms spend ≤K
16
- * completions. Both finals are judged by the SAME check() suite. Per-task {0,1}
17
- * outcomes, paired 95% bootstrap CI (discordant pairs = the power).
18
- *
19
- * TANGLE_API_KEY=… N=82 K=3 OFFSET=82 WORKER_MODEL=gpt-3.5-turbo \
20
- * tsx src/humaneval-repair-gate.mts
21
- */
22
- import { type HumanEvalTask, basePrompt, extractCode, loadHumanEval, runChecker } from './benchmarks/humaneval'
23
- import {
24
- collectAgentTurn,
25
- createExecutor,
26
- streamAgentTurn,
27
- type ToolSpec,
28
- } from '@tangle-network/agent-runtime/kernel'
29
- import { verifierGroundedSelect } from './selector'
30
- import { type PairedLift, pairedLift, pool } from './stats.mts'
31
- import {
32
- benchRouterProfile,
33
- type BenchRouterTarget,
34
- runBenchRouterTurn,
35
- withBenchProfile,
36
- } from './router-turn'
37
-
38
- function must(name: string): string {
39
- const v = process.env[name]
40
- if (!v) throw new Error(`env ${name} is required`)
41
- return v
42
- }
43
-
44
- const runTestsTool: ToolSpec = {
45
- type: 'function',
46
- function: {
47
- name: 'run_tests',
48
- description:
49
- "Run the task's test suite against your candidate function and return PASS or the real failure output. Verify with this before giving your final answer.",
50
- parameters: {
51
- type: 'object',
52
- properties: { code: { type: 'string', description: 'The COMPLETE Python function definition to test (signature + body, plus any imports).' } },
53
- required: ['code'],
54
- },
55
- },
56
- }
57
-
58
- const repairSystem = [
59
- 'You complete a Python function. You have a run_tests tool that runs the REAL test suite against your code.',
60
- 'Workflow: write the function, call run_tests to check it, and if it fails read the error and fix the function, then call run_tests again.',
61
- 'When run_tests reports all tests passed, reply with the final function in a single ```python block and do NOT call the tool again.',
62
- ].join(' ')
63
-
64
- /** repair@K: one worker, up to K inference turns, steering on real test failures. */
65
- async function repairAttempt(cfg: BenchRouterTarget, task: HumanEvalTask, k: number): Promise<number> {
66
- let lastTested = ''
67
- const profile = {
68
- ...withBenchProfile(cfg.profile, {
69
- name: 'humaneval-repair-worker',
70
- systemPrompt: repairSystem,
71
- maxTurns: k,
72
- temperature: 0.3,
73
- }),
74
- tools: { run_tests: true },
75
- }
76
- const factory = createExecutor({
77
- backend: 'router-tools',
78
- routerBaseUrl: cfg.routerBaseUrl,
79
- routerKey: cfg.routerKey,
80
- tools: [runTestsTool],
81
- executeToolCall: async (name, args) => {
82
- if (name !== 'run_tests') return `error: unknown tool ${name}`
83
- const code = extractCode(String(args.code ?? ''))
84
- lastTested = code
85
- const res = await runChecker(task, code)
86
- return res.pass === 1
87
- ? 'ALL TESTS PASSED. Reply with the final function now; do not call run_tests again.'
88
- : `TESTS FAILED:\n${res.detail ?? 'no output'}\n\nFix the function and call run_tests again.`
89
- },
90
- })
91
- const r = await collectAgentTurn(
92
- streamAgentTurn({ kind: 'executor', factory, profile }, { prompt: basePrompt(task) }),
93
- )
94
- if (r.status !== 'completed') {
95
- throw new Error(r.error?.message ?? `repair turn ended with status ${r.status}`)
96
- }
97
- // Judge the model's final answer; fall back to the last code it tested (it may
98
- // report "done" without re-pasting the passing function).
99
- const finalCode = extractCode(r.finalText) || lastTested
100
- if (!finalCode) return 0
101
- return (await runChecker(task, finalCode)).pass
102
- }
103
-
104
- /** blind@K: K independent completions, verifier-grounded pick (the resample control). */
105
- async function blindAttempts(cfg: BenchRouterTarget, task: HumanEvalTask, k: number): Promise<number[]> {
106
- const base = basePrompt(task)
107
- const passes: number[] = []
108
- for (let i = 0; i < k; i += 1) {
109
- const res = await runBenchRouterTurn(
110
- {
111
- routerBaseUrl: cfg.routerBaseUrl,
112
- routerKey: cfg.routerKey,
113
- profile: withBenchProfile(cfg.profile, {
114
- name: 'humaneval-blind-worker',
115
- temperature: 0.8,
116
- }),
117
- },
118
- base,
119
- )
120
- passes.push((await runChecker(task, extractCode(res.finalText))).pass)
121
- }
122
- return passes
123
- }
124
-
125
- const pct = (x: number) => `${(x * 100).toFixed(1)}%`
126
- const pp = (x: number) => `${x >= 0 ? '+' : ''}${(x * 100).toFixed(1)}pp`
127
-
128
- async function main(): Promise<void> {
129
- const n = Number(process.env.N ?? 82)
130
- const k = Number(process.env.K ?? 3)
131
- const offset = Number(process.env.OFFSET ?? 82)
132
- const model = process.env.WORKER_MODEL ?? 'deepseek-v4-flash'
133
- const cfg: BenchRouterTarget = {
134
- routerBaseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',
135
- routerKey: must('TANGLE_API_KEY'),
136
- profile: benchRouterProfile('humaneval-worker', model),
137
- }
138
- const concurrency = Number(process.env.CONCURRENCY ?? 6)
139
- if (k < 2) throw new Error('K must be >= 2 (repair needs at least write + one fix)')
140
-
141
- console.log(`=== HumanEval self-repair gate · tool-using router worker · N=${n} K=${k} offset=${offset} model=${model} ===`)
142
- const tasks = await loadHumanEval(n, offset)
143
- console.log(`loaded ${tasks.length} task(s); running blind@${k} (resample) vs repair@${k} (run_tests-grounded), conc=${concurrency}\n`)
144
-
145
- const rows = await pool(tasks, concurrency, async (task, i) => {
146
- const blind = await blindAttempts(cfg, task, k)
147
- const repair = await repairAttempt(cfg, task, k)
148
- const blind1 = blind[0] ?? 0
149
- const blindK = blind[verifierGroundedSelect(blind)] ?? 0
150
- process.stderr.write(` [${i + 1}/${tasks.length}] ${task.taskId}: blind@1=${blind1} blind@${k}=${blindK} repair@${k}=${repair}\n`)
151
- return { blind1, blindK, repair }
152
- })
153
-
154
- const blind1 = rows.map((r) => r.blind1)
155
- const blindK = rows.map((r) => r.blindK)
156
- const repairK = rows.map((r) => r.repair)
157
- const rate = (xs: number[]) => xs.reduce((s, x) => s + x, 0) / xs.length
158
-
159
- console.log(`\n${'='.repeat(74)}`)
160
- console.log(`RESULTS · HumanEval self-repair · n=${tasks.length} · k=${k} · ${model}`)
161
- console.log('='.repeat(74))
162
- console.log(` blind pass@1 ${pct(rate(blind1))}`)
163
- console.log(` blind@${k} (resample) ${pct(rate(blindK))}`)
164
- console.log(` repair@${k} (tools) ${pct(rate(repairK))}`)
165
-
166
- const row = (label: string, l: PairedLift) =>
167
- console.log(` ${label.padEnd(34)} ${pp(l.point).padStart(7)} CI [${pp(l.low)}, ${pp(l.high)}] (paired ${l.pairs}, discordant ${l.discordant})`)
168
- const sig = (l: PairedLift) => (l.low > 0 ? 'SIGNIF +' : l.high < 0 ? 'SIGNIF -' : 'n.s. (CI spans 0)')
169
-
170
- const repairVsBlind = pairedLift(blindK, repairK)
171
- const computeVsBlind1 = pairedLift(blind1, blindK)
172
- console.log(`\n PAIRED LIFTS (95% bootstrap CI, B=10000):`)
173
- row(`repair@${k} − blind@${k} (steering)`, repairVsBlind)
174
- row(`blind@${k} − blind@1 (more-compute)`, computeVsBlind1)
175
- console.log(`\n VERDICT:`)
176
- console.log(` execution-grounded self-repair beats blind resampling @ equal k? ${repairVsBlind.point > 0 ? 'yes' : 'no'} (${pp(repairVsBlind.point)}, ${sig(repairVsBlind)})`)
177
- }
178
-
179
- main().catch((err) => {
180
- console.error(`humaneval-repair-gate: ${err instanceof Error ? (err.stack ?? err.message) : String(err)}`)
181
- process.exit(1)
182
- })
@@ -1,134 +0,0 @@
1
- /**
2
- * The AgentProfile genome as independently-optimizable coordinates. Every field the harness lets
3
- * you define — prompt, skills, subagents, hooks, tools, mcp — is a coordinate: a way to inject a
4
- * set of named candidates into a profile while holding every OTHER field fixed. This is the one
5
- * abstraction behind "improve any part of the agent, freeze the rest, combine freely":
6
- *
7
- * compose(baseProfile, selected) = { ...baseProfile, <thisField>: inject(selected) }
8
- *
9
- * Freeze a coordinate ⇒ never select it (it stays as-is in the base profile). Optimize one ⇒
10
- * vary its selection. Combine ⇒ compose several coordinates' composers in sequence. Because a
11
- * subagent is ITSELF an AgentProfile, the same coordinates apply recursively to any node in the
12
- * supervisor flow (root driver, worker, sub-worker) — you point a coordinate at that node's
13
- * base profile.
14
- */
15
- import { readFileSync, readdirSync } from 'node:fs'
16
- import { join } from 'node:path'
17
- import type { AgentProfile } from '@tangle-network/agent-interface'
18
- import { defineInlineResource } from '@tangle-network/agent-interface'
19
-
20
- export interface ProfileCoordinate {
21
- /** Coordinate id (the COORDINATE= knob value). */
22
- readonly name: string
23
- /** Candidate names the optimizer screens (one per independently-testable unit). */
24
- candidates(): readonly string[]
25
- /** Inject the selected candidates into THIS field of the profile, holding all others fixed.
26
- * Empty selection ⇒ the base profile unchanged (the frozen/baseline arm). */
27
- compose(base: AgentProfile, selected: readonly string[]): AgentProfile
28
- }
29
-
30
- const here = (p: string) => join(import.meta.dirname, p)
31
-
32
- // ── skills: SKILL.md packages materialized to disk (resources.skills) ───────────────
33
- function skillsCoordinate(dir = here(process.env.SKILLS_DIR ?? 'coding-skills')): ProfileCoordinate {
34
- const files = () => readdirSync(dir).filter((f) => f.endsWith('.md')).sort()
35
- return {
36
- name: 'skills',
37
- candidates: () => files().map((f) => f.replace(/\.md$/, '')),
38
- compose: (base, selected) => {
39
- if (!selected.length) return base
40
- const refs = selected.map((n) => defineInlineResource(n, readFileSync(join(dir, `${n}.md`), 'utf8')))
41
- return { ...base, resources: { ...base.resources, skills: [...(base.resources?.skills ?? []), ...refs] } }
42
- },
43
- }
44
- }
45
-
46
- // ── hooks: shell commands the harness fires on lifecycle events (enforced, not advisory) ──
47
- const hookDefs: Record<string, { event: string; command: string; matcher?: string }> = {
48
- 'lint-before-edit': { event: 'PreToolUse', matcher: 'Edit|Write', command: 'ruff check . 2>/dev/null || true' },
49
- 'tests-after-edit': { event: 'PostToolUse', matcher: 'Edit|Write', command: 'python -m pytest -q 2>/dev/null | tail -5 || true' },
50
- 'no-print-debugging': { event: 'PreToolUse', matcher: 'Edit|Write', command: 'true' },
51
- }
52
- function hooksCoordinate(): ProfileCoordinate {
53
- return {
54
- name: 'hooks',
55
- candidates: () => Object.keys(hookDefs),
56
- compose: (base, selected) => {
57
- if (!selected.length) return base
58
- const hooks: Record<string, { command: string; matcher?: string }[]> = { ...(base.hooks ?? {}) }
59
- for (const n of selected) {
60
- const d = hookDefs[n]
61
- if (!d) throw new Error(`unknown hook ${n}`)
62
- hooks[d.event] = [...(hooks[d.event] ?? []), { command: d.command, ...(d.matcher ? { matcher: d.matcher } : {}) }]
63
- }
64
- return { ...base, hooks: hooks as AgentProfile['hooks'] }
65
- },
66
- }
67
- }
68
-
69
- // ── tools: enable/disable named harness tools ───────────────────────────────────────
70
- const toolCandidates = ['webfetch', 'websearch', 'bash', 'edit', 'read', 'grep']
71
- function toolsCoordinate(): ProfileCoordinate {
72
- return {
73
- name: 'tools',
74
- candidates: () => toolCandidates,
75
- compose: (base, selected) => {
76
- if (!selected.length) return base
77
- const tools: Record<string, boolean> = { ...(base.tools ?? {}) }
78
- for (const n of selected) tools[n] = true
79
- return { ...base, tools }
80
- },
81
- }
82
- }
83
-
84
- // ── prompt: extra instruction lines appended to the active system prompt ─────────────
85
- const instructionDefs: Record<string, string> = {
86
- 'be-surgical': 'Make the smallest change that satisfies the task; do not touch unrelated code.',
87
- 'check-examples': 'Before finalizing, re-read the examples in the docstring and confirm your output matches them exactly.',
88
- 'edge-cases': 'Enumerate boundary inputs (empty, zero, negative, max) and make sure your solution handles each.',
89
- }
90
- function promptCoordinate(): ProfileCoordinate {
91
- return {
92
- name: 'prompt',
93
- candidates: () => Object.keys(instructionDefs),
94
- compose: (base, selected) => {
95
- if (!selected.length) return base
96
- const instructions = [...(base.prompt?.instructions ?? []), ...selected.map((n) => instructionDefs[n]!)]
97
- return { ...base, prompt: { ...base.prompt, instructions } }
98
- },
99
- }
100
- }
101
-
102
- // ── subagents: helper agents the root can delegate to (each is itself a mini-profile) ──
103
- const subagentDefs: Record<string, { description: string; prompt: string; tools?: Record<string, boolean> }> = {
104
- reviewer: { description: 'Reviews a proposed change for bugs before it is finalized.', prompt: 'You are a strict code reviewer. Find bugs, edge cases, and contract violations in the proposed change. Be concise.' },
105
- tester: { description: 'Writes and runs a focused test for the change.', prompt: 'You write the minimal test that would catch a regression in this change, run it, and report pass/fail.' },
106
- }
107
- function subagentsCoordinate(): ProfileCoordinate {
108
- return {
109
- name: 'subagents',
110
- candidates: () => Object.keys(subagentDefs),
111
- compose: (base, selected) => {
112
- if (!selected.length) return base
113
- const subagents = { ...(base.subagents ?? {}) }
114
- for (const n of selected) subagents[n] = subagentDefs[n]!
115
- return { ...base, subagents: subagents as AgentProfile['subagents'] }
116
- },
117
- }
118
- }
119
-
120
- const REGISTRY: Record<string, () => ProfileCoordinate> = {
121
- skills: () => skillsCoordinate(),
122
- hooks: hooksCoordinate,
123
- tools: toolsCoordinate,
124
- prompt: promptCoordinate,
125
- subagents: subagentsCoordinate,
126
- }
127
-
128
- export function getCoordinate(name: string): ProfileCoordinate {
129
- const make = REGISTRY[name]
130
- if (!make) throw new Error(`unknown coordinate ${name} (have: ${Object.keys(REGISTRY).join(', ')})`)
131
- return make()
132
- }
133
-
134
- export const coordinateNames = (): string[] => Object.keys(REGISTRY)
@@ -1,66 +0,0 @@
1
- /**
2
- * run-benchmarks-report — render a `runBenchmarks` result as a rich, multi-axis leaderboard (markdown +
3
- * SVG + HTML), with the BENCHMARKS as the axes. `runBenchmarks` (the registry matrix runner) already
4
- * returns a fixed-width CLI table; this bridges its per-task results into the domain-agnostic `leaderboard`
5
- * engine so the same run also yields a publishable board — every harness×model×persona cell scored on every
6
- * benchmark, the vals.ai-style surface.
7
- *
8
- * No new aggregation logic: it maps each `BenchCellTaskResult` into the universal `RunRecord` shape the
9
- * engine reads (cell → profile, benchmark → axis, score → score), then calls the shared renderers.
10
- * Errored shots (`ok:false`) are dropped, exactly as the runner excludes them from its own denominator.
11
- */
12
- import type { RunRecord } from '@tangle-network/agent-eval'
13
- import {
14
- type Leaderboard,
15
- leaderboard,
16
- renderLeaderboardHtml,
17
- renderLeaderboardMarkdown,
18
- renderLeaderboardSvg,
19
- } from '@tangle-network/agent-runtime/kernel'
20
- import type { BenchCellTaskResult, RunBenchmarksReport } from './run-benchmarks'
21
-
22
- /** Project the runner's per-task results into `RunRecord`s the leaderboard engine reads. Cost/tokens are
23
- * left at 0 — `runBenchmarks` does not meter them per task, so the board shows them as not-captured rather
24
- * than inventing a number. */
25
- function toRecords(perTask: readonly BenchCellTaskResult[]): RunRecord[] {
26
- return perTask
27
- .filter((t) => t.ok)
28
- .map(
29
- (t) =>
30
- ({
31
- runId: `${t.benchmark}:${t.cell}:${t.taskId}:${t.rep}`,
32
- experimentId: t.benchmark,
33
- candidateId: t.cell,
34
- seed: t.rep,
35
- // The cell label is `harness/model` (or a persona id); carry it as the model + harness so the
36
- // leaderboard's default profile key resolves to the cell.
37
- model: t.cell,
38
- promptHash: '',
39
- configHash: '',
40
- commitSha: '',
41
- wallMs: t.wallMs,
42
- costUsd: 0,
43
- tokenUsage: { input: 0, output: 0 },
44
- outcome: { holdoutScore: t.score, raw: { resolved: t.resolved ? 1 : 0 } },
45
- splitTag: 'holdout',
46
- scenarioId: t.benchmark,
47
- agentProfile: { harness: t.cell.split('/')[0] ?? t.cell, model: t.cell },
48
- }) as unknown as RunRecord,
49
- )
50
- }
51
-
52
- /** Build the rich leaderboard from a `runBenchmarks` result — benchmarks are the axes, cells are the rows. */
53
- export function benchmarksLeaderboard(
54
- report: RunBenchmarksReport,
55
- opts: { title?: string; meta?: Record<string, string> } = {},
56
- ): Leaderboard {
57
- return leaderboard(toRecords(report.perTask), {
58
- title: opts.title ?? 'Benchmark matrix — cell × benchmark',
59
- // The cell (harness/model/persona) is the row label; one column per benchmark.
60
- profileKeyOf: (r) => r.candidateId,
61
- groupOf: (r) => r.scenarioId ?? r.experimentId,
62
- ...(opts.meta ? { meta: opts.meta } : {}),
63
- })
64
- }
65
-
66
- export { renderLeaderboardHtml, renderLeaderboardMarkdown, renderLeaderboardSvg }
@@ -1,101 +0,0 @@
1
- /**
2
- * Proof that a SKILL.md from an AgentProfile actually materializes inside the sandbox where the
3
- * coding harness loads it — the "are we on the right surface" check before any benchmark.
4
- * Creates one opencode box with resources.skills, then asks the IN-SESSION agent to read the
5
- * skill back. PASS keys on a UNIQUE MARKER in the skill body, so a hit is unambiguously OUR
6
- * skill — not opencode's bundled /nix/store skills and not the agent's prose.
7
- *
8
- * Two gotchas this guards against (both produced false readings during bring-up):
9
- * 1. PATH: opencode's discovery dir is ~/.opencode/skill/<name>/SKILL.md (SINGULAR "skill");
10
- * claude-code uses ~/.claude/skills/. resources.skills lands in the backend's own dir.
11
- * 2. VIEW: a bare box.exec() WITHOUT a sessionId sees a DIFFERENT filesystem than the agent
12
- * session (SDK ExecOptions docs). So we verify through the in-SESSION agent (streamPrompt),
13
- * the path the bench actually runs — not a detached exec.
14
- *
15
- * Run: dotenvx run -f ~/company/devops/secrets/.env.keys -- pnpm exec tsx bench/src/skill-sandbox-smoke.mts
16
- */
17
- import { defineInlineResource } from '@tangle-network/agent-interface'
18
- import { Sandbox } from '@tangle-network/sandbox'
19
-
20
- const must = (k: string): string => {
21
- const v = process.env[k]
22
- if (!v) throw new Error(`env ${k} required`)
23
- return v
24
- }
25
-
26
- const skillName = 'reproduce-first'
27
- // A unique token that cannot occur in opencode's bundled skills or in plausible prose.
28
- const marker = 'SKILLMAT-OK-7f3c91'
29
- const skillMd = [
30
- '---',
31
- `name: ${skillName}`,
32
- 'description: Reproduce the failing test before changing any code.',
33
- '---',
34
- '',
35
- `Materialization proof token: ${marker}`,
36
- 'When fixing a bug: run the failing test FIRST to observe the real error, make the smallest',
37
- 'change that turns it green, then re-run to confirm.',
38
- ].join('\n')
39
-
40
- async function main(): Promise<void> {
41
- const client = new Sandbox({
42
- baseUrl: process.env.SANDBOX_BASE_URL ?? 'https://sandbox.tangle.tools',
43
- apiKey: must('TANGLE_API_KEY'),
44
- timeoutMs: 600_000,
45
- } as never)
46
-
47
- console.error(`[smoke] creating opencode box with resources.skills=[${skillName}]…`)
48
- const box: Record<string, (...a: never[]) => unknown> & { id?: string } = (await client.create({
49
- backend: {
50
- type: 'opencode',
51
- model: {
52
- provider: process.env.WORKER_PROVIDER ?? 'openai',
53
- model: process.env.WORKER_MODEL ?? 'deepseek-v4-flash',
54
- baseUrl: process.env.ROUTER_BASE ?? 'https://router.tangle.tools/v1',
55
- },
56
- profile: { name: 'skill-smoke', resources: { skills: [defineInlineResource(skillName, skillMd)] } },
57
- },
58
- } as never)) as never
59
- console.error('[smoke] box id:', box.id, '— waiting for running…')
60
- await box.waitFor('running' as never, { timeoutMs: 180_000 } as never)
61
- console.error('[smoke] box running; asking the IN-SESSION agent to read the materialized skill back…')
62
-
63
- // cat the skill at BOTH backend discovery dirs (opencode singular, claude-code plural) + a
64
- // name-scoped find; the marker appears wherever resources.skills actually landed it.
65
- const prompt =
66
- 'Run this exact shell command and paste its raw output verbatim, nothing else:\n' +
67
- `\`cat ~/.opencode/skill/${skillName}/SKILL.md ~/.claude/skills/${skillName}/SKILL.md 2>/dev/null; ` +
68
- `echo "--FIND--"; find / -name SKILL.md 2>/dev/null | grep -i ${skillName} | grep -vi /nix/store || echo NOFILE\``
69
- let out = ''
70
- const ac = new AbortController()
71
- const timer = setTimeout(() => ac.abort(), 220_000)
72
- try {
73
- for await (const ev of box.streamPrompt(prompt as never, { signal: ac.signal } as never) as AsyncGenerator<unknown>) {
74
- out += (typeof ev === 'string' ? ev : JSON.stringify(ev)) + '\n'
75
- }
76
- } finally {
77
- clearTimeout(timer)
78
- }
79
- console.error(`[smoke] stream chars: ${out.length}`)
80
- console.error('[smoke] tail of stream:\n' + out.slice(-1500))
81
-
82
- try {
83
- await box.delete?.()
84
- } catch {
85
- /* best-effort cleanup */
86
- }
87
-
88
- // Deterministic: PASS only if the agent read OUR unique marker out of the file — not a loose
89
- // match on the skill name (which appears in the prompt/prose) or on "SKILL.md" (bundled skills).
90
- const landed = out.includes(marker)
91
- const path = /\.opencode\/skill\//.test(out) ? '~/.opencode/skill (opencode)' : /\.claude\/skills\//.test(out) ? '~/.claude/skills (claude-code)' : '(path not surfaced)'
92
- console.error(
93
- `\n[smoke] VERDICT: ${landed ? `PASS — resources.skills materialized + the in-session agent read the marker at ${path}` : 'FAIL — marker NOT read back; resources.skills did not land where the harness reads (check backend discovery dir)'}`,
94
- )
95
- process.exit(landed ? 0 : 2)
96
- }
97
-
98
- main().catch((e) => {
99
- console.error('[smoke] FAILED:', e instanceof Error ? (e.stack ?? e.message) : e)
100
- process.exit(1)
101
- })