@linxin666/dsh-liangshen 0.3.21 → 0.3.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,354 @@
1
+ /**
2
+ * Aggregate live benchmark run records into a comparison report.
3
+ *
4
+ * The runner writes one JSON record per session plus a suite index. This module
5
+ * turns those records into per-group statistics, paired per-task comparisons with
6
+ * confidence intervals, and a Markdown summary. It keeps the outcome measures
7
+ * separate from trajectory-style measurements: language-style counters stay with
8
+ * tools/analyze-session.mjs.
9
+ *
10
+ * Usage:
11
+ * node tools/benchmark-report.mjs <results-dir> [--baseline B]
12
+ */
13
+
14
+ import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'
15
+ import { join } from 'node:path'
16
+ import { pathToFileURL } from 'node:url'
17
+
18
+ /** Presentational order of the candidate matrix. */
19
+ export const GROUP_ORDER = ['B', 'P', 'T', 'N', 'M']
20
+
21
+ /** Two-sided 95% t critical values for small samples; the normal limit past 30 df. */
22
+ const T95 = {
23
+ 1: 12.706, 2: 4.303, 3: 3.182, 4: 2.776, 5: 2.571, 6: 2.447, 7: 2.365, 8: 2.306,
24
+ 9: 2.262, 10: 2.228, 11: 2.201, 12: 2.179, 13: 2.16, 14: 2.145, 15: 2.131,
25
+ 16: 2.12, 17: 2.11, 18: 2.101, 19: 2.093, 20: 2.086, 21: 2.08, 22: 2.074,
26
+ 23: 2.069, 24: 2.064, 25: 2.06, 26: 2.056, 27: 2.052, 28: 2.048, 29: 2.045,
27
+ 30: 2.042,
28
+ }
29
+
30
+ /** Wilson score interval for a binomial success rate. */
31
+ export function wilsonInterval(successes, total, z = 1.96) {
32
+ if (!Number.isFinite(total) || total <= 0) return null
33
+ const p = successes / total
34
+ const denominator = 1 + (z * z) / total
35
+ const centre = (p + (z * z) / (2 * total)) / denominator
36
+ const spread = (z / denominator) * Math.sqrt((p * (1 - p)) / total + (z * z) / (4 * total * total))
37
+ return { low: Math.max(0, centre - spread), high: Math.min(1, centre + spread) }
38
+ }
39
+
40
+ /** Mean of a numeric sample with a two-sided confidence interval. */
41
+ export function meanConfidenceInterval(values, confidence = 0.95) {
42
+ const clean = values.filter((value) => typeof value === 'number' && Number.isFinite(value))
43
+ if (clean.length === 0) return null
44
+ const mean = clean.reduce((total, value) => total + value, 0) / clean.length
45
+ // One observation cannot estimate spread: report the point estimate and leave
46
+ // the interval unestimable rather than manufacturing a zero-width one.
47
+ if (clean.length === 1) return { mean, low: null, high: null, n: 1, sd: null }
48
+ const variance = clean.reduce((total, value) => total + (value - mean) ** 2, 0) / (clean.length - 1)
49
+ const sd = Math.sqrt(variance)
50
+ const standardError = sd / Math.sqrt(clean.length)
51
+ const critical = confidence === 0.95 ? (T95[clean.length - 1] ?? 1.96) : 1.96
52
+ return { mean, low: mean - critical * standardError, high: mean + critical * standardError, n: clean.length, sd }
53
+ }
54
+
55
+ /**
56
+ * A run that produced no gradeable model attempt: the session log carries no
57
+ * request, or nothing graded it. These stay out of every success-rate
58
+ * denominator. A task timeout is NOT an infrastructure failure: the model ran
59
+ * and did not finish, so it counts as a task failure and is reported as a
60
+ * timeout separately.
61
+ */
62
+ export function isInfrastructureFailure(run) {
63
+ return (run?.requests?.length ?? 0) === 0
64
+ || run?.passed === null
65
+ || run?.passed === undefined
66
+ }
67
+
68
+ function sumOf(entries, pick) {
69
+ return entries.reduce((total, entry) => total + (pick(entry) ?? 0), 0)
70
+ }
71
+
72
+ function costOf(entries) {
73
+ let total = 0
74
+ let priced = 0
75
+ for (const entry of entries) {
76
+ if (typeof entry.costUsd === 'number' && Number.isFinite(entry.costUsd)) { total += entry.costUsd; priced += 1 }
77
+ }
78
+ return priced === 0 ? null : total
79
+ }
80
+
81
+ /** Per-group descriptive statistics over the raw run records. */
82
+ export function aggregateGroups(runs) {
83
+ const byGroup = new Map()
84
+ for (const run of runs) {
85
+ const key = run?.variant
86
+ if (typeof key !== 'string') continue
87
+ if (!byGroup.has(key)) byGroup.set(key, [])
88
+ byGroup.get(key).push(run)
89
+ }
90
+ const groups = {}
91
+ for (const [group, entries] of byGroup) {
92
+ const graded = entries.filter((run) => !isInfrastructureFailure(run))
93
+ const passed = graded.filter((run) => run.passed === true).length
94
+ groups[group] = {
95
+ sessions: entries.length,
96
+ graded: graded.length,
97
+ infrastructureFailures: entries.length - graded.length,
98
+ timeouts: entries.filter((run) => run.timedOut === true).length,
99
+ passed,
100
+ successRate: graded.length === 0 ? null : passed / graded.length,
101
+ successInterval: wilsonInterval(passed, graded.length),
102
+ uncachedInputTokens: sumOf(entries, (run) => run.usage?.uncachedInputTokens),
103
+ outputTokens: sumOf(entries, (run) => run.usage?.outputTokens),
104
+ cacheReadTokens: sumOf(entries, (run) => run.usage?.cacheReadTokens),
105
+ totalTokens: sumOf(entries, (run) => run.usage?.totalTokens),
106
+ durationMs: sumOf(entries, (run) => run.durationMs),
107
+ toolCalls: sumOf(entries, (run) => run.toolCalls),
108
+ toolErrors: sumOf(entries, (run) => run.toolErrors),
109
+ humanInterventions: sumOf(entries, (run) => run.humanInterventions),
110
+ approvalAsks: sumOf(entries, (run) => run.approvalsAsked),
111
+ estimatedCostUsd: costOf(entries),
112
+ }
113
+ }
114
+ return groups
115
+ }
116
+
117
+ /**
118
+ * Paired per-task comparison of two groups: the paired unit is the task, and each
119
+ * task contributes the difference between the two groups' pass rates over the
120
+ * repetitions actually run.
121
+ */
122
+ export function pairedComparison(runs, baselineGroup, candidateGroup) {
123
+ const taskIds = [...new Set(runs.map((run) => run?.taskId).filter((id) => typeof id === 'string'))].sort()
124
+ const perTask = []
125
+ const deltas = []
126
+ for (const taskId of taskIds) {
127
+ const baseline = runs.filter((run) => run.variant === baselineGroup && run.taskId === taskId && !isInfrastructureFailure(run))
128
+ const candidate = runs.filter((run) => run.variant === candidateGroup && run.taskId === taskId && !isInfrastructureFailure(run))
129
+ if (baseline.length === 0 || candidate.length === 0) continue
130
+ const baselineRate = baseline.filter((run) => run.passed === true).length / baseline.length
131
+ const candidateRate = candidate.filter((run) => run.passed === true).length / candidate.length
132
+ const delta = candidateRate - baselineRate
133
+ deltas.push(delta)
134
+ perTask.push({
135
+ taskId,
136
+ baselineRate,
137
+ candidateRate,
138
+ delta,
139
+ baselineRuns: baseline.length,
140
+ candidateRuns: candidate.length,
141
+ })
142
+ }
143
+ const interval = meanConfidenceInterval(deltas)
144
+ const estimable = interval !== null && interval.low !== null && interval.high !== null
145
+ return {
146
+ baseline: baselineGroup,
147
+ candidate: candidateGroup,
148
+ tasks: perTask.length,
149
+ pairedMeanDelta: interval?.mean ?? null,
150
+ // A difference of two rates cannot leave [-1, 1]; a tiny sample's t interval can.
151
+ low: estimable ? Math.max(-1, interval.low) : null,
152
+ high: estimable ? Math.min(1, interval.high) : null,
153
+ sd: interval?.sd ?? null,
154
+ // Fewer than two paired tasks cannot support an interval at all.
155
+ insufficientEvidence: perTask.length < 2,
156
+ perTask,
157
+ }
158
+ }
159
+
160
+ /** The comparisons the improvement plan asks for, in attribution order. */
161
+ export function plannedComparisons(runs, baselineGroup = 'B') {
162
+ const present = new Set(runs.map((run) => run.variant))
163
+ const comparisons = []
164
+ if (present.has(baselineGroup) && present.has('P')) comparisons.push(pairedComparison(runs, baselineGroup, 'P'))
165
+ if (present.has('P') && present.has('T')) comparisons.push(pairedComparison(runs, 'P', 'T'))
166
+ if (present.has('T') && present.has('N')) comparisons.push(pairedComparison(runs, 'T', 'N'))
167
+ if (present.has(baselineGroup) && present.has('M')) comparisons.push(pairedComparison(runs, baselineGroup, 'M'))
168
+ return comparisons
169
+ }
170
+
171
+ /**
172
+ * The run-record file names a report may read. A suite index records exactly the
173
+ * files it wrote, so a reused results directory does not silently mix a previous
174
+ * run's records into this one; without an index the directory is scanned.
175
+ */
176
+ export function runFileNames(dir, suite) {
177
+ if (Array.isArray(suite?.runs)) {
178
+ const names = suite.runs
179
+ .map((entry) => String(entry?.file ?? entry?.name ?? '').replaceAll('\\', '/').split('/').pop())
180
+ .filter((name) => typeof name === 'string' && name.startsWith('live-') && name.endsWith('.json'))
181
+ return [...new Set(names)].sort()
182
+ }
183
+ return readdirSync(dir).filter((name) => name.startsWith('live-') && name.endsWith('.json')).sort()
184
+ }
185
+
186
+ /** Read the named run records from one directory. */
187
+ export function loadRuns(dir, names) {
188
+ const files = names ?? runFileNames(dir, undefined)
189
+ const runs = []
190
+ for (const name of files) {
191
+ const path = join(dir, name)
192
+ if (!existsSync(path)) continue
193
+ runs.push(JSON.parse(readFileSync(path, 'utf8')))
194
+ }
195
+ return runs
196
+ }
197
+
198
+ /** The facts that make two runs comparable; a mismatch invalidates the report. */
199
+ export function baselineIdentity(baseline) {
200
+ return JSON.stringify({
201
+ commit: baseline?.repository?.commit ?? null,
202
+ presetSourceHash: baseline?.presetSourceHash ?? null,
203
+ dshVersion: baseline?.dshVersion ?? null,
204
+ route: baseline?.route ?? null,
205
+ taskRevision: baseline?.taskRevision ?? null,
206
+ })
207
+ }
208
+
209
+ /**
210
+ * Assemble the full report object from a results directory. Only the suite index
211
+ * own records are read when an index exists, and a record whose baseline does not
212
+ * match the index baseline is rejected instead of being averaged in.
213
+ */
214
+ export function buildReport(dir, baselineGroup = 'B') {
215
+ const suitePath = join(dir, 'suite.json')
216
+ const suite = existsSync(suitePath) ? JSON.parse(readFileSync(suitePath, 'utf8')) : null
217
+ const runs = loadRuns(dir, runFileNames(dir, suite))
218
+ const baseline = suite?.baseline ?? runs[0]?.baseline ?? null
219
+ const expected = baselineIdentity(baseline)
220
+ for (const run of runs) {
221
+ if (baselineIdentity(run.baseline) !== expected) {
222
+ throw new Error('benchmark-report: the results directory mixes runs from different baselines; re-run into a fresh directory')
223
+ }
224
+ }
225
+ return {
226
+ generatedAt: new Date().toISOString(),
227
+ baselineGroup,
228
+ baseline,
229
+ suite,
230
+ groups: aggregateGroups(runs),
231
+ comparisons: plannedComparisons(runs, baselineGroup),
232
+ runs: runs.length,
233
+ }
234
+ }
235
+
236
+ function percent(value) {
237
+ return value === null || value === undefined ? 'n/a' : (value * 100).toFixed(1) + '%'
238
+ }
239
+
240
+ function interval(intervalValue) {
241
+ return intervalValue === null || intervalValue === undefined ? 'n/a' : percent(intervalValue.low) + '..' + percent(intervalValue.high)
242
+ }
243
+
244
+ function signed(value) {
245
+ if (value === null || value === undefined) return 'n/a'
246
+ return (value >= 0 ? '+' : '') + (value * 100).toFixed(1) + 'pp'
247
+ }
248
+
249
+ /** Human-readable Markdown summary of one report object. */
250
+ export function renderMarkdown(report) {
251
+ const lines = []
252
+ lines.push('# LiangShen V4.1 Flash comparison report')
253
+ lines.push('')
254
+ lines.push('Generated: ' + report.generatedAt + ' from ' + report.runs + ' run record(s).')
255
+ lines.push('')
256
+ if (report.baseline !== null && report.baseline !== undefined) {
257
+ const baseline = report.baseline
258
+ lines.push('## Baseline')
259
+ lines.push('')
260
+ lines.push('| Fact | Value |')
261
+ lines.push('| --- | --- |')
262
+ lines.push('| Repository commit | ' + (baseline.repository?.commit ?? 'n/a') + ' |')
263
+ lines.push('| Repository dirty | ' + JSON.stringify(baseline.repository?.dirty ?? null) + ' |')
264
+ lines.push('| Shipped preset hash | ' + (baseline.presetSourceHash ?? 'n/a') + ' |')
265
+ lines.push('| DSH version | ' + (baseline.dshVersion ?? 'n/a') + ' |')
266
+ lines.push('| Route | ' + (baseline.route?.provider ?? '?') + '/' + (baseline.route?.model ?? '?') + '/' + (baseline.route?.reasoningEffort ?? '?') + ' |')
267
+ lines.push('| Platform | ' + (baseline.platform ?? 'n/a') + ' / node ' + (baseline.node ?? '?') + ' |')
268
+ lines.push('| Task revision | ' + (baseline.taskRevision === null || baseline.taskRevision === undefined ? 'n/a' : baseline.taskRevision.id + ' v' + baseline.taskRevision.version + ' (' + baseline.taskRevision.tasks + ' tasks, ' + baseline.taskRevision.hash.slice(0, 12) + ')') + ' |')
269
+ if (report.suite !== null && report.suite !== undefined) {
270
+ lines.push('| Stop reason | ' + report.suite.stopReason + ' after ' + report.suite.sessions + ' session(s) |')
271
+ }
272
+ lines.push('')
273
+ }
274
+ lines.push('## Group results')
275
+ lines.push('')
276
+ lines.push('| Group | Sessions | Graded | Passed | Success rate (95% CI) | Infra failures | Timeouts | Input tokens | Output tokens | Cache read | Tool calls | Tool errors | Interventions | Cost USD |')
277
+ lines.push('| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |')
278
+ for (const group of GROUP_ORDER) {
279
+ const stats = report.groups[group]
280
+ if (stats === undefined) continue
281
+ lines.push('| ' + [
282
+ group,
283
+ stats.sessions,
284
+ stats.graded,
285
+ stats.passed,
286
+ percent(stats.successRate) + ' (' + interval(stats.successInterval) + ')',
287
+ stats.infrastructureFailures,
288
+ stats.timeouts,
289
+ stats.uncachedInputTokens,
290
+ stats.outputTokens,
291
+ stats.cacheReadTokens,
292
+ stats.toolCalls,
293
+ stats.toolErrors,
294
+ stats.humanInterventions,
295
+ stats.estimatedCostUsd === null ? 'n/a' : stats.estimatedCostUsd.toFixed(4),
296
+ ].join(' | ') + ' |')
297
+ }
298
+ lines.push('')
299
+ lines.push('## Paired comparisons')
300
+ lines.push('')
301
+ lines.push('| Comparison | Purpose | Tasks paired | Mean delta (95% CI) |')
302
+ lines.push('| --- | --- | --- | --- |')
303
+ const purposes = {
304
+ 'B-P': 'isolates the persona change',
305
+ 'P-T': 'tests whether anchoring helps',
306
+ 'T-N': 'compares PTC against native presentation',
307
+ 'B-M': 'external reference, not single-factor attribution',
308
+ }
309
+ for (const comparison of report.comparisons) {
310
+ const key = comparison.baseline + '-' + comparison.candidate
311
+ const spread = comparison.pairedMeanDelta === null
312
+ ? 'n/a'
313
+ : comparison.insufficientEvidence
314
+ ? signed(comparison.pairedMeanDelta) + ' (interval not estimable)'
315
+ : signed(comparison.pairedMeanDelta) + ' (' + signed(comparison.low) + '..' + signed(comparison.high) + ')'
316
+ lines.push('| ' + key + ' | ' + (purposes[key] ?? '') + ' | ' + comparison.tasks + ' | ' + spread + ' |')
317
+ }
318
+ lines.push('')
319
+ lines.push('## Treatment notes')
320
+ lines.push('')
321
+ lines.push('- Infrastructure failures (a session log with no request, or an ungraded run) are reported separately and excluded from every success-rate denominator.')
322
+ lines.push('- A task timeout counts as a task failure; timeouts are reported in their own column so the two failure modes stay distinguishable.')
323
+ lines.push('- A paired comparison over fewer than two tasks reports its point estimate with no interval: one paired task cannot support a confidence statement.')
324
+ lines.push('- The report reads only the run records listed in the suite index and rejects a directory whose runs disagree on commit, preset hash, route, or task revision.')
325
+ lines.push('- Group M is the bundle-provided Minimal preset as an external reference; it is not a single-factor arm.')
326
+ lines.push('- Group N is the full native roster, not Minimal and not a curated minimal toolset.')
327
+ lines.push('- Language-style counters (we and let me) stay with tools/analyze-session.mjs and are not part of the outcome measures here.')
328
+ lines.push('- A small sample screens a direction; it does not claim a stable improvement. Widen the sample within the stated budget before concluding.')
329
+ lines.push('')
330
+ return lines.join('\n')
331
+ }
332
+
333
+ function isMain() {
334
+ const entry = process.argv[1]
335
+ return entry !== undefined && pathToFileURL(entry).href === import.meta.url
336
+ }
337
+
338
+ if (isMain()) {
339
+ const args = process.argv.slice(2)
340
+ const positional = args.filter((arg) => !arg.startsWith('--'))
341
+ const dir = positional[0]
342
+ if (dir === undefined || !existsSync(dir)) {
343
+ console.error('usage: node tools/benchmark-report.mjs <results-dir> [--baseline B]')
344
+ process.exitCode = 1
345
+ } else {
346
+ const baselineIndex = args.indexOf('--baseline')
347
+ const baselineGroup = baselineIndex === -1 ? 'B' : args[baselineIndex + 1]
348
+ const report = buildReport(dir, baselineGroup)
349
+ const markdown = renderMarkdown(report)
350
+ writeFileSync(join(dir, 'report.json'), JSON.stringify(report, null, 2))
351
+ writeFileSync(join(dir, 'report.md'), markdown)
352
+ console.log(markdown)
353
+ }
354
+ }
@@ -0,0 +1,127 @@
1
+ {
2
+ "id": "liangshen-v41-flash-seed",
3
+ "version": 1,
4
+ "description": "Seed task corpus for the LiangShen V4.1 Flash comparison. Covers code repair, first-turn specialized tools, multi-turn edits, failure recovery, and workspace-instruction compliance. Extend to 20-30 tasks before the main run.",
5
+ "tasks": [
6
+ {
7
+ "id": "repair-mean",
8
+ "category": "code-repair",
9
+ "files": {
10
+ "stats.mjs": "export function mean(values) {\n let total = 0\n for (const value of values) total += value\n return total / (values.length + 1)\n}\n"
11
+ },
12
+ "turns": [
13
+ "Fix stats.mjs so mean([1, 2, 3]) returns exactly 2 and mean([2, 4]) returns exactly 3. Keep the exported name. Verify the result, then reply DONE and stop."
14
+ ],
15
+ "check": "const m = await import('./stats.mjs'); if (m.mean([1, 2, 3]) !== 2) throw new Error('mean([1,2,3]) = ' + m.mean([1, 2, 3])); if (m.mean([2, 4]) !== 3) throw new Error('mean([2,4]) = ' + m.mean([2, 4]))"
16
+ },
17
+ {
18
+ "id": "repair-negative-number",
19
+ "category": "code-repair",
20
+ "files": {
21
+ "parse.mjs": "export function toNumber(text) {\n return Number(String(text).replace('-', ''))\n}\n"
22
+ },
23
+ "turns": [
24
+ "Fix parse.mjs so toNumber('-12') returns -12 and toNumber('7') returns 7. Keep the exported name. Verify the result, then reply DONE and stop."
25
+ ],
26
+ "check": "const m = await import('./parse.mjs'); if (m.toNumber('-12') !== -12) throw new Error('negative = ' + m.toNumber('-12')); if (m.toNumber('7') !== 7) throw new Error('positive = ' + m.toNumber('7'))"
27
+ },
28
+ {
29
+ "id": "repair-default-value",
30
+ "category": "code-repair",
31
+ "files": {
32
+ "config.mjs": "export function resolvePort(options) {\n return options.port | 8080\n}\n"
33
+ },
34
+ "turns": [
35
+ "Fix config.mjs so resolvePort({}) returns 8080 and resolvePort({ port: 0 }) returns 0. Keep the exported name. Verify the result, then reply DONE and stop."
36
+ ],
37
+ "check": "const m = await import('./config.mjs'); if (m.resolvePort({}) !== 8080) throw new Error('default = ' + m.resolvePort({})); if (m.resolvePort({ port: 0 }) !== 0) throw new Error('zero = ' + m.resolvePort({ port: 0 }))"
38
+ },
39
+ {
40
+ "id": "first-turn-edit",
41
+ "category": "first-turn-specialized",
42
+ "files": {
43
+ "version.mjs": "export const VERSION = '1.0.0'\n"
44
+ },
45
+ "turns": [
46
+ "Change the VERSION constant in version.mjs to 2.0.0. Do not change the exported name. Verify the file content, then reply DONE and stop."
47
+ ],
48
+ "check": "const m = await import('./version.mjs'); if (m.VERSION !== '2.0.0') throw new Error('VERSION = ' + m.VERSION)"
49
+ },
50
+ {
51
+ "id": "first-turn-create-file",
52
+ "category": "first-turn-specialized",
53
+ "turns": [
54
+ "Create a file named greeting.txt in the current directory whose only content is hello, then reply DONE and stop."
55
+ ],
56
+ "check": "const fs = await import('node:fs'); if (!fs.existsSync('greeting.txt')) throw new Error('greeting.txt missing'); const text = fs.readFileSync('greeting.txt', 'utf8').trim(); if (text !== 'hello') throw new Error('content = ' + JSON.stringify(text))"
57
+ },
58
+ {
59
+ "id": "multiturn-cube-and-test",
60
+ "category": "multi-turn-edits",
61
+ "files": {
62
+ "math.mjs": "export function square(value) {\n return value * value\n}\n"
63
+ },
64
+ "turns": [
65
+ "Add an exported function cube(value) to math.mjs, next to square.",
66
+ "Create check.mjs that imports cube from math.mjs and throws when cube(3) is not 27.",
67
+ "Run check.mjs and reply DONE and stop."
68
+ ],
69
+ "check": "const m = await import('./math.mjs'); if (m.cube(3) !== 27) throw new Error('cube(3) = ' + m.cube(3)); const fs = await import('node:fs'); if (!fs.existsSync('check.mjs')) throw new Error('check.mjs missing')"
70
+ },
71
+ {
72
+ "id": "multiturn-rename-export",
73
+ "category": "multi-turn-edits",
74
+ "files": {
75
+ "util.mjs": "export function oldName() {\n return 1\n}\n",
76
+ "main.mjs": "import { oldName } from './util.mjs'\n\nexport const value = oldName()\n"
77
+ },
78
+ "turns": [
79
+ "Rename the exported function oldName in util.mjs to currentName.",
80
+ "Update main.mjs so it keeps exporting value === 1 through the new name, then reply DONE and stop."
81
+ ],
82
+ "check": "const main = await import('./main.mjs'); if (main.value !== 1) throw new Error('value = ' + main.value); const util = await import('./util.mjs'); if (typeof util.currentName !== 'function') throw new Error('currentName missing'); if (util.oldName !== undefined) throw new Error('oldName still exported')"
83
+ },
84
+ {
85
+ "id": "recovery-failing-check",
86
+ "category": "failure-recovery",
87
+ "files": {
88
+ "sum.mjs": "export function sum(values) {\n return values.reduce((total, value) => total + value, 1)\n}\n",
89
+ "check.mjs": "import { sum } from './sum.mjs'\n\nif (sum([1, 2, 3]) !== 6) {\n throw new Error('sum([1, 2, 3]) should be 6 but is ' + sum([1, 2, 3]))\n}\n\nconsole.log('check passed')\n"
90
+ },
91
+ "turns": [
92
+ "Run the existing check.mjs, read the failure it reports, fix the bug in sum.mjs, and rerun check.mjs until it passes. Then reply DONE and stop."
93
+ ],
94
+ "check": "const m = await import('./sum.mjs'); if (m.sum([1, 2, 3]) !== 6) throw new Error('sum([1,2,3]) = ' + m.sum([1, 2, 3])); if (m.sum([]) !== 0) throw new Error('sum([]) = ' + m.sum([]))"
95
+ },
96
+ {
97
+ "id": "recovery-missing-directory",
98
+ "category": "failure-recovery",
99
+ "turns": [
100
+ "Write a file at src/nested/deep.txt whose only content is ok. If that path does not exist yet, make it exist. Then reply DONE and stop."
101
+ ],
102
+ "check": "const fs = await import('node:fs'); if (!fs.existsSync('src/nested/deep.txt')) throw new Error('deep.txt missing'); const text = fs.readFileSync('src/nested/deep.txt', 'utf8').trim(); if (text !== 'ok') throw new Error('content = ' + JSON.stringify(text))"
103
+ },
104
+ {
105
+ "id": "instruction-generated-header",
106
+ "category": "workspace-instruction-compliance",
107
+ "files": {
108
+ "AGENTS.md": "# Workspace rules\n\nEvery generated source file must start with the comment line `// generated`.\n"
109
+ },
110
+ "turns": [
111
+ "Create a file named report.mjs that exports const ready = true. Follow the workspace rules in AGENTS.md. Then reply DONE and stop."
112
+ ],
113
+ "check": "const fs = await import('node:fs'); if (!fs.existsSync('report.mjs')) throw new Error('report.mjs missing'); const first = fs.readFileSync('report.mjs', 'utf8').split(/\\r?\\n/)[0].trim(); if (first !== '// generated') throw new Error('first line = ' + JSON.stringify(first)); const m = await import('./report.mjs'); if (m.ready !== true) throw new Error('ready = ' + m.ready)"
114
+ },
115
+ {
116
+ "id": "instruction-forbidden-extension",
117
+ "category": "workspace-instruction-compliance",
118
+ "files": {
119
+ "AGENTS.md": "# Workspace rules\n\nNever create a file named config.js. Name configuration modules config.mjs instead.\n"
120
+ },
121
+ "turns": [
122
+ "Create the configuration module described by the workspace rules, exporting const port = 3000. Follow AGENTS.md. Then reply DONE and stop."
123
+ ],
124
+ "check": "const fs = await import('node:fs'); if (fs.existsSync('config.js')) throw new Error('config.js must not exist'); if (!fs.existsSync('config.mjs')) throw new Error('config.mjs missing'); const m = await import('./config.mjs'); if (m.port !== 3000) throw new Error('port = ' + m.port)"
125
+ }
126
+ ]
127
+ }