@tangle-network/agent-runtime 0.89.0 → 0.90.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +51 -18
  2. package/dist/agent.d.ts +53 -2
  3. package/dist/agent.js +168 -6
  4. package/dist/agent.js.map +1 -1
  5. package/dist/analyst-loop.d.ts +1 -1
  6. package/dist/chunk-5QOB7H74.js +387 -0
  7. package/dist/chunk-5QOB7H74.js.map +1 -0
  8. package/dist/{chunk-4WXGK6GV.js → chunk-7ON74BQO.js} +2 -2
  9. package/dist/{chunk-7LO5GMAO.js → chunk-CMYMTRGA.js} +14 -5
  10. package/dist/chunk-CMYMTRGA.js.map +1 -0
  11. package/dist/{chunk-UD4BHQMI.js → chunk-IVGYLCFH.js} +2 -2
  12. package/dist/{chunk-UD4BHQMI.js.map → chunk-IVGYLCFH.js.map} +1 -1
  13. package/dist/{chunk-VNOOH22O.js → chunk-OOL3675H.js} +85 -4
  14. package/dist/chunk-OOL3675H.js.map +1 -0
  15. package/dist/{chunk-5AVV7KAH.js → chunk-QK4DV5PR.js} +2 -2
  16. package/dist/chunk-R2VAJGR3.js +214 -0
  17. package/dist/chunk-R2VAJGR3.js.map +1 -0
  18. package/dist/{chunk-N7EJV7N3.js → chunk-RYBVU4M3.js} +3592 -3562
  19. package/dist/chunk-RYBVU4M3.js.map +1 -0
  20. package/dist/{chunk-BQPFZE2C.js → chunk-WRUSWK4F.js} +5 -5
  21. package/dist/{chunk-PIPPLSOF.js → chunk-ZV4LXYCJ.js} +451 -24
  22. package/dist/chunk-ZV4LXYCJ.js.map +1 -0
  23. package/dist/{worktree-harness-CX_McRLp.d.ts → completion-gate-DkAnUmpb.d.ts} +45 -45
  24. package/dist/{coordination-CuDLO8wj.d.ts → coordination-rRj5hjJK.d.ts} +415 -227
  25. package/dist/environment-provider.d.ts +3 -3
  26. package/dist/index.d.ts +255 -16
  27. package/dist/index.js +463 -72
  28. package/dist/index.js.map +1 -1
  29. package/dist/intelligence.d.ts +228 -84
  30. package/dist/intelligence.js +259 -166
  31. package/dist/intelligence.js.map +1 -1
  32. package/dist/knowledge.d.ts +120 -0
  33. package/dist/knowledge.js +28 -0
  34. package/dist/knowledge.js.map +1 -0
  35. package/dist/lifecycle.d.ts +2 -2
  36. package/dist/lifecycle.js +2 -2
  37. package/dist/{local-harness-sI0S_XNA.d.ts → local-harness-dcD5WTTr.d.ts} +3 -0
  38. package/dist/{loop-runner-bin-hQDUL8Ld.d.ts → loop-runner-bin-DTbZVGfM.d.ts} +2 -2
  39. package/dist/loop-runner-bin.d.ts +6 -6
  40. package/dist/loop-runner-bin.js +7 -7
  41. package/dist/loops.d.ts +34 -369
  42. package/dist/loops.js +31 -5
  43. package/dist/mcp/bin.js +5 -5
  44. package/dist/mcp/index.d.ts +10 -11
  45. package/dist/mcp/index.js +10 -10
  46. package/dist/{mcp-serve-verifier-FL7-ZEb_.d.ts → mcp-serve-verifier-XsX8rkB9.d.ts} +12 -1
  47. package/dist/{openai-tools-BnrOmGjN.d.ts → openai-tools-C4ZfUD4L.d.ts} +1 -1
  48. package/dist/profiles.d.ts +196 -5
  49. package/dist/profiles.js +8 -0
  50. package/dist/profiles.js.map +1 -1
  51. package/dist/{router-client-r8y_VFVM.d.ts → router-client-DJImUDlm.d.ts} +1 -1
  52. package/dist/structural-rollout-MwlpgQ-6.d.ts +446 -0
  53. package/dist/supervise-DPmYPk0j.d.ts +131 -0
  54. package/dist/{types-ESeMOj94.d.ts → types-SyuwunY_.d.ts} +1 -1
  55. package/dist/{types-Driepl87.d.ts → types-eMNgWgFi.d.ts} +2 -2
  56. package/dist/{worktree-fanout-D6xR2CIA.d.ts → worktree-fanout-BDFQIO-Y.d.ts} +234 -234
  57. package/package.json +12 -4
  58. package/skills/agent-runtime-adoption/SKILL.md +74 -24
  59. package/skills/build-with-agent-runtime/SKILL.md +23 -20
  60. package/skills/loop-writer/SKILL.md +6 -5
  61. package/skills/supervise/SKILL.md +2 -2
  62. package/dist/chunk-7LO5GMAO.js.map +0 -1
  63. package/dist/chunk-N7EJV7N3.js.map +0 -1
  64. package/dist/chunk-PIPPLSOF.js.map +0 -1
  65. package/dist/chunk-VNOOH22O.js.map +0 -1
  66. package/dist/otel-export-BKmNwiCb.d.ts +0 -180
  67. /package/dist/{chunk-4WXGK6GV.js.map → chunk-7ON74BQO.js.map} +0 -0
  68. /package/dist/{chunk-5AVV7KAH.js.map → chunk-QK4DV5PR.js.map} +0 -0
  69. /package/dist/{chunk-BQPFZE2C.js.map → chunk-WRUSWK4F.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  mcpToolsForRuntimeMcp,
3
3
  mcpToolsForRuntimeMcpSubset
4
- } from "./chunk-5AVV7KAH.js";
4
+ } from "./chunk-QK4DV5PR.js";
5
5
  import {
6
6
  DEFAULT_ROUTER_BASE_URL,
7
7
  cleanModelId,
@@ -20,25 +20,45 @@ import {
20
20
  runLoopRunnerCli,
21
21
  selfImproveLoopRunner,
22
22
  worktreeLoopRunner
23
- } from "./chunk-BQPFZE2C.js";
23
+ } from "./chunk-WRUSWK4F.js";
24
24
  import "./chunk-SGKPNBXE.js";
25
25
  import {
26
26
  InMemoryRuntimeSessionStore,
27
27
  createIterableBackend,
28
28
  createOpenAICompatibleBackend,
29
29
  createSandboxPromptBackend,
30
+ defaultStructuralRolloutPolicy,
30
31
  newRuntimeSession,
31
32
  normalizeBackendStreamEvent,
32
33
  nowIso,
33
34
  touchSession
34
- } from "./chunk-PIPPLSOF.js";
35
+ } from "./chunk-ZV4LXYCJ.js";
36
+ import "./chunk-ZQZX77MM.js";
37
+ import {
38
+ agenticGenerator,
39
+ commandVerifier,
40
+ mcpBuildPrompt,
41
+ mcpServeVerifier,
42
+ toolBuildPrompt
43
+ } from "./chunk-OOL3675H.js";
44
+ import {
45
+ RESEARCH_SUPERVISOR_SYSTEM_PROMPT,
46
+ createAgentKnowledgeReadinessCheck,
47
+ createSupervisedKnowledgeUpdater,
48
+ formatSupervisedKnowledgeTask,
49
+ knowledgeReadinessDeliverable,
50
+ runKnowledgeImprovementJob,
51
+ runSupervisedKnowledgeUpdate
52
+ } from "./chunk-R2VAJGR3.js";
53
+ import "./chunk-5QOB7H74.js";
35
54
  import {
36
55
  assertModelAllowed,
37
56
  composeRuntimeHooks,
38
57
  defineRuntimeHooks,
39
58
  notifyRuntimeDecisionPoint,
40
59
  notifyRuntimeHookEvent
41
- } from "./chunk-N7EJV7N3.js";
60
+ } from "./chunk-RYBVU4M3.js";
61
+ import "./chunk-DPEUKJRO.js";
42
62
  import {
43
63
  INTELLIGENCE_WIRE_VERSION,
44
64
  buildLoopOtelSpans,
@@ -46,18 +66,10 @@ import {
46
66
  createOtelExporter,
47
67
  exportEvalRuns,
48
68
  loopEventToOtelSpan
49
- } from "./chunk-UD4BHQMI.js";
69
+ } from "./chunk-IVGYLCFH.js";
50
70
  import "./chunk-BZF3KQ6G.js";
51
- import "./chunk-ZQZX77MM.js";
52
71
  import "./chunk-FVJ7M3DA.js";
53
- import {
54
- agenticGenerator,
55
- commandVerifier,
56
- mcpBuildPrompt,
57
- mcpServeVerifier,
58
- toolBuildPrompt
59
- } from "./chunk-VNOOH22O.js";
60
- import "./chunk-7LO5GMAO.js";
72
+ import "./chunk-CMYMTRGA.js";
61
73
  import {
62
74
  AgentEvalError,
63
75
  BackendTransportError,
@@ -69,7 +81,6 @@ import {
69
81
  SessionMismatchError,
70
82
  ValidationError
71
83
  } from "./chunk-YEJR7IXO.js";
72
- import "./chunk-DPEUKJRO.js";
73
84
  import "./chunk-DGUM43GV.js";
74
85
 
75
86
  // src/conversation/call-policy.ts
@@ -171,7 +182,7 @@ function computeBackoff(spec, attempt) {
171
182
  return Math.max(0, spec);
172
183
  }
173
184
  function sleep(ms) {
174
- return new Promise((resolve) => setTimeout(resolve, ms));
185
+ return new Promise((resolve2) => setTimeout(resolve2, ms));
175
186
  }
176
187
 
177
188
  // src/conversation/headers.ts
@@ -1272,10 +1283,353 @@ function deriveExecutionId(input) {
1272
1283
  }
1273
1284
 
1274
1285
  // src/improvement/improve.ts
1275
- import { gepaProposer, skillOptProposer } from "@tangle-network/agent-eval/campaign";
1286
+ import {
1287
+ gepaProposer,
1288
+ gitWorktreeAdapter,
1289
+ skillOptProposer
1290
+ } from "@tangle-network/agent-eval/campaign";
1276
1291
  import {
1277
1292
  selfImprove
1278
1293
  } from "@tangle-network/agent-eval/contract";
1294
+
1295
+ // src/improvement/improvement-driver.ts
1296
+ function improvementDriver(opts) {
1297
+ const baseRef = opts.baseRef ?? "main";
1298
+ return {
1299
+ kind: `improvement:${opts.generator.kind}`,
1300
+ async propose(ctx) {
1301
+ const findings = resolveFindings(ctx);
1302
+ if (findings.length === 0 && ctx.report === void 0 && !opts.generator.proposesWithoutFindings) {
1303
+ return [];
1304
+ }
1305
+ const surfaces = [];
1306
+ for (let i = 0; i < ctx.populationSize; i++) {
1307
+ if (ctx.signal.aborted) break;
1308
+ const wt = await opts.worktree.create({
1309
+ baseRef,
1310
+ label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`
1311
+ });
1312
+ try {
1313
+ const { applied, summary } = await opts.generator.generate({
1314
+ worktreePath: wt.path,
1315
+ report: ctx.report,
1316
+ findings,
1317
+ dataset: ctx.dataset,
1318
+ maxShots: ctx.maxImprovementShots ?? 1,
1319
+ signal: ctx.signal
1320
+ });
1321
+ if (!applied) {
1322
+ await opts.worktree.discard(wt);
1323
+ continue;
1324
+ }
1325
+ surfaces.push(await opts.worktree.finalize(wt, summary));
1326
+ } catch (err) {
1327
+ await opts.worktree.discard(wt).catch(() => {
1328
+ });
1329
+ throw err;
1330
+ }
1331
+ }
1332
+ return surfaces;
1333
+ }
1334
+ };
1335
+ }
1336
+ function resolveFindings(ctx) {
1337
+ const report = ctx.report;
1338
+ if (report && typeof report === "object" && "findings" in report) {
1339
+ const f = report.findings;
1340
+ if (Array.isArray(f) && f.length > 0) return f;
1341
+ }
1342
+ return ctx.findings;
1343
+ }
1344
+
1345
+ // src/improvement/raw-trace-distiller.ts
1346
+ import { existsSync, readdirSync } from "fs";
1347
+ import { basename, join, resolve } from "path";
1348
+ import { makeFinding } from "@tangle-network/agent-eval";
1349
+ var ANALYST_ID = "raw-trace-distiller";
1350
+ var PASS_THRESHOLD = 0.999;
1351
+ function rawTraceDistiller(options = {}) {
1352
+ const maxCandidates = options.maxCandidates ?? 12;
1353
+ const maxCellsPerCandidate = options.maxCellsPerCandidate ?? 8;
1354
+ const maxFilesPerCell = options.maxFilesPerCell ?? 24;
1355
+ return async (input) => {
1356
+ const genRoot = absoluteRunDir(options.runDir ?? input.runDir);
1357
+ const durable = isDurable(genRoot);
1358
+ const ranked = [...input.candidates].map((c) => ({
1359
+ surfaceHash: c.surfaceHash,
1360
+ composite: c.composite,
1361
+ campaignDir: absoluteRunDir(c.campaign.runDir),
1362
+ cells: failingCells(c.campaign, maxCellsPerCandidate, maxFilesPerCell)
1363
+ })).sort((a, b) => a.composite - b.composite).slice(0, maxCandidates);
1364
+ const totalFailingCells = ranked.reduce((n, c) => n + c.cells.length, 0);
1365
+ if (totalFailingCells === 0) {
1366
+ if (options.fallbackFindings && options.fallbackFindings.length > 0) {
1367
+ return options.fallbackFindings;
1368
+ }
1369
+ return [
1370
+ makeFinding({
1371
+ analyst_id: ANALYST_ID,
1372
+ severity: "info",
1373
+ area: "raw-trace-context",
1374
+ confidence: 1,
1375
+ claim: `Generation ${input.generation} had no failing cells. The full raw run traces are on disk under ${genRoot}.`,
1376
+ recommended_action: `To keep improving, grep/cat the raw traces under ${genRoot} (per-cell spans.jsonl + cached-result.json) to find the weakest passing runs, then make a targeted harness-code edit.`,
1377
+ evidence_refs: [{ kind: "artifact", uri: genRoot }],
1378
+ metadata: { generation: input.generation, runDir: genRoot, failingCells: 0 }
1379
+ })
1380
+ ];
1381
+ }
1382
+ const findings = [];
1383
+ findings.push(
1384
+ makeFinding({
1385
+ analyst_id: ANALYST_ID,
1386
+ severity: "high",
1387
+ area: "raw-trace-context",
1388
+ confidence: 1,
1389
+ claim: `Generation ${input.generation} produced ${totalFailingCells} failing/low-scoring cell(s) across ${ranked.length} candidate(s). Their FULL RAW run traces are on disk under ${genRoot} \u2014 the actual event logs (spans.jsonl), scores (cached-result.json), and artifacts, not a summary.${durable ? "" : " (WARNING: this run root does not exist on disk \u2014 it looks like an in-memory run; pass a real runDir to improve() to get raw-trace context.)"}`,
1390
+ recommended_action: `Do NOT rely on a pre-summarized finding. Before editing, DIAGNOSE from the raw traces: run \`grep\`/\`cat\`/\`ls\` over the trace files and directories named in the following findings to see exactly what each failing run did and why it scored low, then make the smallest harness-code edit that fixes the dominant failure. Start with \`grep -rIn "error" ${genRoot}\` then \`cat\` the spans.jsonl of the worst cell.`,
1391
+ evidence_refs: [{ kind: "artifact", uri: genRoot }],
1392
+ metadata: {
1393
+ generation: input.generation,
1394
+ runDir: genRoot,
1395
+ failingCells: totalFailingCells,
1396
+ candidates: ranked.length
1397
+ }
1398
+ })
1399
+ );
1400
+ for (const cand of ranked) {
1401
+ if (cand.cells.length === 0) continue;
1402
+ const scenarioList = cand.cells.map((c) => c.scenarioId).join(", ");
1403
+ const fileLines = cand.cells.map((c) => {
1404
+ const header = ` cell ${c.scenarioId} (composite ${c.composite.toFixed(3)}${c.error ? `, error: ${truncate(c.error, 160)}` : ""}) \u2014 dir ${c.cellDir}`;
1405
+ const files = c.files.map((f) => ` - ${f}`).join("\n");
1406
+ const more = c.truncatedFiles ? `
1407
+ - \u2026(ls ${c.cellDir} for the rest)` : "";
1408
+ return c.files.length > 0 ? `${header}
1409
+ ${files}${more}` : header;
1410
+ }).join("\n");
1411
+ findings.push(
1412
+ makeFinding({
1413
+ analyst_id: ANALYST_ID,
1414
+ severity: cand.composite < 0.5 ? "critical" : "high",
1415
+ area: "raw-trace-context",
1416
+ confidence: 1,
1417
+ subject: cand.surfaceHash,
1418
+ claim: `Candidate ${cand.surfaceHash} scored composite ${cand.composite.toFixed(3)} with ${cand.cells.length} failing cell(s) [${scenarioList}]. Its raw traces are under ${cand.campaignDir}.`,
1419
+ recommended_action: `grep/cat these raw trace files to diagnose WHY this candidate failed before editing:
1420
+ ${fileLines}
1421
+ Or scan the whole candidate at once: \`grep -rIn . ${cand.campaignDir}\` and \`ls -R ${cand.campaignDir}\`.`,
1422
+ evidence_refs: [
1423
+ { kind: "artifact", uri: cand.campaignDir },
1424
+ ...cand.cells.flatMap(
1425
+ (c) => c.files.map((f) => ({ kind: "artifact", uri: f }))
1426
+ )
1427
+ ],
1428
+ metadata: {
1429
+ surfaceHash: cand.surfaceHash,
1430
+ composite: cand.composite,
1431
+ campaignDir: cand.campaignDir,
1432
+ cells: cand.cells.map((c) => ({
1433
+ scenarioId: c.scenarioId,
1434
+ composite: c.composite,
1435
+ cellDir: c.cellDir,
1436
+ files: c.files,
1437
+ ...c.error ? { error: c.error } : {}
1438
+ }))
1439
+ }
1440
+ })
1441
+ );
1442
+ }
1443
+ return findings;
1444
+ };
1445
+ }
1446
+ function failingCells(campaign, maxCells, maxFiles) {
1447
+ const campaignDir = absoluteRunDir(campaign.runDir);
1448
+ const durable = isDurable(campaignDir);
1449
+ const out = [];
1450
+ for (const cell of campaign.cells) {
1451
+ const scores = Object.values(cell.judgeScores ?? {});
1452
+ const composite = scores.length === 0 ? 0 : scores.reduce((sum, s) => sum + (s.composite ?? 0), 0) / scores.length;
1453
+ if (!cell.error && composite >= PASS_THRESHOLD) continue;
1454
+ const cellDir = join(campaignDir, sanitizeCellId(cell.cellId));
1455
+ const artifactPaths = artifactPathsForCell(campaign.artifactsByPath, cell.cellId);
1456
+ const discovered = durable ? listTraceFiles(cellDir) : [];
1457
+ const canonical = [join(cellDir, "spans.jsonl"), join(cellDir, "cached-result.json")];
1458
+ const files = dedupeSorted([...discovered, ...artifactPaths, ...canonical]);
1459
+ out.push({
1460
+ scenarioId: cell.scenarioId,
1461
+ composite: Number(composite.toFixed(3)),
1462
+ ...cell.error ? { error: cell.error } : {},
1463
+ cellDir,
1464
+ files: files.slice(0, maxFiles),
1465
+ truncatedFiles: files.length > maxFiles
1466
+ });
1467
+ if (out.length >= maxCells) break;
1468
+ }
1469
+ return out;
1470
+ }
1471
+ function artifactPathsForCell(artifactsByPath, cellId) {
1472
+ if (!artifactsByPath) return [];
1473
+ const prefix = `${cellId}/`;
1474
+ return Object.entries(artifactsByPath).filter(([key]) => key.startsWith(prefix)).map(([, absPath]) => resolve(absPath));
1475
+ }
1476
+ function listTraceFiles(dir) {
1477
+ const out = [];
1478
+ for (const entry of safeReadDir(dir)) {
1479
+ const full = join(dir, entry.name);
1480
+ if (entry.isFile()) {
1481
+ out.push(full);
1482
+ } else if (!entry.isSymbolicLink() && entry.isDirectory()) {
1483
+ for (const sub of safeReadDir(full)) {
1484
+ if (sub.isFile()) out.push(join(full, sub.name));
1485
+ }
1486
+ }
1487
+ }
1488
+ return out;
1489
+ }
1490
+ function safeReadDir(dir) {
1491
+ try {
1492
+ return readdirSync(dir, { withFileTypes: true });
1493
+ } catch {
1494
+ return [];
1495
+ }
1496
+ }
1497
+ function sanitizeCellId(cellId) {
1498
+ return cellId.replace(/[^a-zA-Z0-9_-]/g, "_");
1499
+ }
1500
+ function isDurable(runDir) {
1501
+ return !runDir.startsWith("mem://") && existsSync(runDir);
1502
+ }
1503
+ function absoluteRunDir(runDir) {
1504
+ return runDir.startsWith("mem://") ? runDir : resolve(runDir);
1505
+ }
1506
+ function dedupeSorted(paths) {
1507
+ return [...new Set(paths)].sort((a, b) => {
1508
+ const da = a.slice(0, a.length - basename(a).length);
1509
+ const db = b.slice(0, b.length - basename(b).length);
1510
+ return da === db ? basename(a).localeCompare(basename(b)) : da.localeCompare(db);
1511
+ });
1512
+ }
1513
+ function truncate(s, n) {
1514
+ return s.length <= n ? s : `${s.slice(0, n - 1)}\u2026`;
1515
+ }
1516
+
1517
+ // src/improvement/rollout-policy.ts
1518
+ var ROLLOUT_POLICY_EXTENSION = "structural-rollout";
1519
+ var ROLLOUT_POLICY_BOUNDS = {
1520
+ k: { min: 1, max: 10, step: 2 },
1521
+ repairRounds: { min: 0, max: 3, step: 1 },
1522
+ testgen: { min: 0, max: 10, step: 3 }
1523
+ };
1524
+ var MAX_CANDIDATES_PER_GENERATION = 4;
1525
+ var clamp = (v, min, max) => Math.min(max, Math.max(min, v));
1526
+ var isBoundedInt = (v, min) => typeof v === "number" && Number.isInteger(v) && v >= min;
1527
+ function parseRolloutPolicy(surface) {
1528
+ if (typeof surface !== "string" || surface.trim().length === 0) return void 0;
1529
+ let raw;
1530
+ try {
1531
+ raw = JSON.parse(surface);
1532
+ } catch {
1533
+ return void 0;
1534
+ }
1535
+ return normalizeRolloutPolicy(raw);
1536
+ }
1537
+ function normalizeRolloutPolicy(raw) {
1538
+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return void 0;
1539
+ const bag = raw;
1540
+ const k = bag.k ?? defaultStructuralRolloutPolicy.k;
1541
+ const repairRounds = bag.repairRounds ?? defaultStructuralRolloutPolicy.repairRounds;
1542
+ const testgen = bag.testgen ?? defaultStructuralRolloutPolicy.testgen;
1543
+ if (!isBoundedInt(k, 1) || !isBoundedInt(repairRounds, 0) || !isBoundedInt(testgen, 0)) {
1544
+ return void 0;
1545
+ }
1546
+ return {
1547
+ k,
1548
+ repairRounds,
1549
+ testgen,
1550
+ ...typeof bag.diverse === "boolean" ? { diverse: bag.diverse } : {},
1551
+ ...typeof bag.temperature === "number" ? { temperature: bag.temperature } : {}
1552
+ };
1553
+ }
1554
+ function serializeRolloutPolicy(policy) {
1555
+ return JSON.stringify({
1556
+ k: policy.k,
1557
+ repairRounds: policy.repairRounds,
1558
+ testgen: policy.testgen,
1559
+ ...policy.diverse !== void 0 ? { diverse: policy.diverse } : {},
1560
+ ...policy.temperature !== void 0 ? { temperature: policy.temperature } : {}
1561
+ });
1562
+ }
1563
+ function structuralRolloutPolicyFromProfile(profile) {
1564
+ const bag = profile.extensions?.[ROLLOUT_POLICY_EXTENSION];
1565
+ if (bag === void 0) return void 0;
1566
+ return normalizeRolloutPolicy(bag);
1567
+ }
1568
+ function applyRolloutPolicyToProfile(profile, policy) {
1569
+ const bag = {
1570
+ k: policy.k,
1571
+ repairRounds: policy.repairRounds,
1572
+ testgen: policy.testgen,
1573
+ ...policy.diverse !== void 0 ? { diverse: policy.diverse } : {},
1574
+ ...policy.temperature !== void 0 ? { temperature: policy.temperature } : {}
1575
+ };
1576
+ return {
1577
+ ...profile,
1578
+ extensions: { ...profile.extensions, [ROLLOUT_POLICY_EXTENSION]: bag }
1579
+ };
1580
+ }
1581
+ function enumerateNeighborPolicies(policy) {
1582
+ const moves = [
1583
+ { dial: "k", delta: 1 },
1584
+ { dial: "k", delta: -1 },
1585
+ { dial: "repairRounds", delta: 1 },
1586
+ { dial: "repairRounds", delta: -1 },
1587
+ { dial: "testgen", delta: 1 },
1588
+ { dial: "testgen", delta: -1 }
1589
+ ];
1590
+ const seen = /* @__PURE__ */ new Set([serializeRolloutPolicy(policy)]);
1591
+ const neighbors = [];
1592
+ for (const move of moves) {
1593
+ const bounds = ROLLOUT_POLICY_BOUNDS[move.dial];
1594
+ const next = clamp(policy[move.dial] + move.delta * bounds.step, bounds.min, bounds.max);
1595
+ const candidate = { ...policy, [move.dial]: next };
1596
+ const key = serializeRolloutPolicy(candidate);
1597
+ if (seen.has(key)) continue;
1598
+ seen.add(key);
1599
+ neighbors.push(candidate);
1600
+ }
1601
+ return neighbors;
1602
+ }
1603
+ function candidateLabel(base, next) {
1604
+ for (const dial of ["k", "repairRounds", "testgen"]) {
1605
+ if (next[dial] !== base[dial]) return `${dial} ${base[dial]}\u2192${next[dial]}`;
1606
+ }
1607
+ return "unchanged";
1608
+ }
1609
+ function rolloutPolicyProposer() {
1610
+ return {
1611
+ kind: "rollout-policy",
1612
+ async propose(ctx) {
1613
+ const policy = parseRolloutPolicy(ctx.currentSurface);
1614
+ if (!policy) return [];
1615
+ const neighbors = enumerateNeighborPolicies(policy);
1616
+ if (neighbors.length === 0) return [];
1617
+ const cap = Math.max(1, Math.min(ctx.populationSize, MAX_CANDIDATES_PER_GENERATION));
1618
+ const start = ctx.generation * cap % neighbors.length;
1619
+ const window = [];
1620
+ for (let i = 0; i < Math.min(cap, neighbors.length); i += 1) {
1621
+ window.push(neighbors[(start + i) % neighbors.length]);
1622
+ }
1623
+ return window.map((candidate) => ({
1624
+ surface: serializeRolloutPolicy(candidate),
1625
+ label: candidateLabel(policy, candidate),
1626
+ rationale: "bounded single-dial neighbor of the current structuralRollout policy; the held-out gate decides (deterministic enumeration \u2014 the dial space is tiny and prompt-style reflective proposals are a measured zero here)"
1627
+ }));
1628
+ }
1629
+ };
1630
+ }
1631
+
1632
+ // src/improvement/improve.ts
1279
1633
  var defaultReflectionModel = "deepseek-v4-flash";
1280
1634
  function llmClientOptions(llm) {
1281
1635
  return { baseUrl: llm?.baseUrl, apiKey: llm?.apiKey };
@@ -1287,26 +1641,76 @@ function defaultGeneratorFor(surface, llm) {
1287
1641
  return gepaProposer({ llm: llmClientOptions(llm), model, target: "agent system prompt" });
1288
1642
  case "skills":
1289
1643
  return skillOptProposer({ llm: llmClientOptions(llm), model, target: "agent skill document" });
1644
+ case "rollout-policy":
1645
+ return rolloutPolicyProposer();
1290
1646
  default:
1291
1647
  return void 0;
1292
1648
  }
1293
1649
  }
1294
- function baselineSurfaceFor(profile, surface) {
1650
+ function baselineSurfaceFor(profile, surface, skills) {
1295
1651
  switch (surface) {
1296
1652
  case "prompt":
1297
1653
  return profile.prompt?.systemPrompt ?? "";
1298
1654
  case "skills":
1299
- return JSON.stringify(profile.resources?.skills ?? []);
1655
+ return skills?.document ?? JSON.stringify(profile.resources?.skills ?? []);
1300
1656
  case "tools":
1301
1657
  return JSON.stringify(profile.tools ?? {});
1302
1658
  case "mcp":
1303
1659
  return JSON.stringify(profile.mcp ?? {});
1304
1660
  case "hooks":
1305
1661
  return JSON.stringify(profile.hooks ?? {});
1662
+ case "rollout-policy": {
1663
+ const policy = structuralRolloutPolicyFromProfile(profile);
1664
+ return policy ? serializeRolloutPolicy(policy) : "";
1665
+ }
1306
1666
  case "code":
1307
1667
  return "";
1308
1668
  }
1309
1669
  }
1670
+ function generationFailureDistiller(staticFindings) {
1671
+ const CAP = 12;
1672
+ return async (input) => {
1673
+ const failures = [];
1674
+ for (const candidate of input.candidates) {
1675
+ for (const rawCell of candidate.campaign.cells) {
1676
+ const cell = rawCell;
1677
+ const scenario = String(cell.scenarioId ?? "unknown");
1678
+ const error = typeof cell.error === "string" ? cell.error : void 0;
1679
+ const judgeScores = cell.judgeScores && typeof cell.judgeScores === "object" ? Object.values(
1680
+ cell.judgeScores
1681
+ ) : [];
1682
+ const composite = judgeScores.length === 0 ? 0 : judgeScores.reduce((sum, j) => sum + (j.composite ?? 0), 0) / judgeScores.length;
1683
+ if (!error && composite >= 0.999) continue;
1684
+ const notes = judgeScores.map((j) => j.notes).filter((n) => typeof n === "string" && n.length > 0).join("; ").slice(0, 400);
1685
+ failures.push({
1686
+ scenario,
1687
+ composite: Number(composite.toFixed(3)),
1688
+ notes,
1689
+ ...error ? { error: error.slice(0, 200) } : {}
1690
+ });
1691
+ }
1692
+ }
1693
+ if (failures.length === 0) return staticFindings;
1694
+ failures.sort((a, b) => a.composite - b.composite);
1695
+ return failures.slice(0, CAP);
1696
+ };
1697
+ }
1698
+ function codeProposerFor(surface, code) {
1699
+ if (surface !== "code" || !code) return void 0;
1700
+ const generator = code.generator ?? agenticGenerator({
1701
+ ...code.harness ? { harness: code.harness } : {},
1702
+ ...code.verify ? { verify: code.verify } : {},
1703
+ ...code.timeoutMs ? { timeoutMs: code.timeoutMs } : {}
1704
+ });
1705
+ return improvementDriver({
1706
+ worktree: gitWorktreeAdapter({
1707
+ repoRoot: code.repoRoot,
1708
+ ...code.worktreeDir ? { worktreeDir: code.worktreeDir } : {}
1709
+ }),
1710
+ generator,
1711
+ ...code.baseRef ? { baseRef: code.baseRef } : {}
1712
+ });
1713
+ }
1310
1714
  function parseWinnerJson(winner, surface) {
1311
1715
  try {
1312
1716
  return JSON.parse(winner);
@@ -1332,6 +1736,15 @@ function applyWinnerToProfile(profile, surface, winner) {
1332
1736
  return { ...profile, mcp: parseWinnerJson(winner, surface) };
1333
1737
  case "hooks":
1334
1738
  return { ...profile, hooks: parseWinnerJson(winner, surface) };
1739
+ case "rollout-policy": {
1740
+ const policy = normalizeRolloutPolicy(parseWinnerJson(winner, surface));
1741
+ if (!policy) {
1742
+ throw new ConfigError(
1743
+ `improve(): the shipped 'rollout-policy' winner is not a valid StructuralRolloutPolicy (integer k >= 1, repairRounds >= 0, testgen >= 0), so it cannot be applied: ${winner}`
1744
+ );
1745
+ }
1746
+ return applyRolloutPolicyToProfile(profile, policy);
1747
+ }
1335
1748
  case "code":
1336
1749
  return profile;
1337
1750
  }
@@ -1340,10 +1753,10 @@ async function improve(profile, findings, opts) {
1340
1753
  const surface = opts.surface ?? "prompt";
1341
1754
  const gate = opts.gate ?? "holdout";
1342
1755
  assertModelAllowed(opts.llm?.model ?? defaultReflectionModel, opts.allowedModels);
1343
- const proposer = opts.generator ?? defaultGeneratorFor(surface, opts.llm);
1756
+ const proposer = opts.generator ?? defaultGeneratorFor(surface, opts.llm) ?? codeProposerFor(surface, opts.code);
1344
1757
  if (!proposer) {
1345
1758
  throw new ConfigError(
1346
- `improve(): surface '${surface}' has no default generator \u2014 pass opts.generator (a SurfaceProposer) explicitly`
1759
+ surface === "code" ? `improve(): surface 'code' needs either opts.generator or opts.code ({ repoRoot, ... }) \u2014 there is no safe zero-config repo to invent` : `improve(): surface '${surface}' has no default generator \u2014 pass opts.generator (a SurfaceProposer) explicitly`
1347
1760
  );
1348
1761
  }
1349
1762
  const budget = gate === "none" ? { ...opts.budget, generations: 0 } : { ...opts.budget };
@@ -1351,63 +1764,24 @@ async function improve(profile, findings, opts) {
1351
1764
  agent: opts.agent,
1352
1765
  scenarios: opts.scenarios,
1353
1766
  judge: opts.judge,
1354
- baselineSurface: baselineSurfaceFor(profile, surface),
1767
+ baselineSurface: baselineSurfaceFor(profile, surface, opts.skills),
1355
1768
  proposer,
1356
1769
  budget,
1357
1770
  llm: opts.llm,
1358
- findings
1771
+ findings,
1772
+ ...opts.runDir !== void 0 ? { runDir: opts.runDir } : {},
1773
+ ...opts.storage !== void 0 ? { storage: opts.storage } : {},
1774
+ ...opts.analyzeGeneration === null ? {} : {
1775
+ analyzeGeneration: opts.analyzeGeneration ?? (opts.rawTraceContext ? rawTraceDistiller({ fallbackFindings: findings }) : generationFailureDistiller(findings))
1776
+ }
1359
1777
  });
1360
1778
  const shipped = raw.gateDecision === "ship";
1361
- const nextProfile = shipped ? applyWinnerToProfile(profile, surface, raw.winner.surface) : profile;
1362
- return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw };
1363
- }
1364
-
1365
- // src/improvement/improvement-driver.ts
1366
- function improvementDriver(opts) {
1367
- const baseRef = opts.baseRef ?? "main";
1368
- return {
1369
- kind: `improvement:${opts.generator.kind}`,
1370
- async propose(ctx) {
1371
- const findings = resolveFindings(ctx);
1372
- if (findings.length === 0 && ctx.report === void 0) return [];
1373
- const surfaces = [];
1374
- for (let i = 0; i < ctx.populationSize; i++) {
1375
- if (ctx.signal.aborted) break;
1376
- const wt = await opts.worktree.create({
1377
- baseRef,
1378
- label: `${opts.generator.kind}-gen${ctx.generation}-cand${i}`
1379
- });
1380
- try {
1381
- const { applied, summary } = await opts.generator.generate({
1382
- worktreePath: wt.path,
1383
- report: ctx.report,
1384
- findings,
1385
- dataset: ctx.dataset,
1386
- maxShots: ctx.maxImprovementShots ?? 1,
1387
- signal: ctx.signal
1388
- });
1389
- if (!applied) {
1390
- await opts.worktree.discard(wt);
1391
- continue;
1392
- }
1393
- surfaces.push(await opts.worktree.finalize(wt, summary));
1394
- } catch (err) {
1395
- await opts.worktree.discard(wt).catch(() => {
1396
- });
1397
- throw err;
1398
- }
1399
- }
1400
- return surfaces;
1401
- }
1402
- };
1403
- }
1404
- function resolveFindings(ctx) {
1405
- const report = ctx.report;
1406
- if (report && typeof report === "object" && "findings" in report) {
1407
- const f = report.findings;
1408
- if (Array.isArray(f) && f.length > 0) return f;
1779
+ const usedSkillDocument = surface === "skills" && opts.skills !== void 0;
1780
+ if (shipped && usedSkillDocument && typeof raw.winner.surface === "string") {
1781
+ opts.skills?.writeBack?.(raw.winner.surface);
1409
1782
  }
1410
- return ctx.findings;
1783
+ const nextProfile = shipped && !usedSkillDocument ? applyWinnerToProfile(profile, surface, raw.winner.surface) : profile;
1784
+ return { profile: nextProfile, shipped, lift: raw.lift, gateDecision: raw.gateDecision, raw };
1411
1785
  }
1412
1786
 
1413
1787
  // src/improvement/reflective-generator.ts
@@ -2888,10 +3262,14 @@ export {
2888
3262
  JudgeError,
2889
3263
  NotFoundError,
2890
3264
  PlannerError,
3265
+ RESEARCH_SUPERVISOR_SYSTEM_PROMPT,
3266
+ ROLLOUT_POLICY_BOUNDS,
3267
+ ROLLOUT_POLICY_EXTENSION,
2891
3268
  RuntimeRunStateError,
2892
3269
  SqlConversationJournal,
2893
3270
  ValidationError,
2894
3271
  agenticGenerator,
3272
+ applyRolloutPolicyToProfile,
2895
3273
  applyRunRecordDefaults,
2896
3274
  auditLoopRunner,
2897
3275
  buildForwardHeaders,
@@ -2901,6 +3279,7 @@ export {
2901
3279
  commandVerifier,
2902
3280
  composeRuntimeHooks,
2903
3281
  computeBackoff,
3282
+ createAgentKnowledgeReadinessCheck,
2904
3283
  createConversationBackend,
2905
3284
  createIterableBackend,
2906
3285
  createOpenAICompatibleBackend,
@@ -2908,28 +3287,35 @@ export {
2908
3287
  createRuntimeEventCollector,
2909
3288
  createRuntimeStreamEventCollector,
2910
3289
  createSandboxPromptBackend,
3290
+ createSupervisedKnowledgeUpdater,
2911
3291
  d1ToSqlAdapter,
2912
3292
  decideKnowledgeReadiness,
2913
3293
  defaultIsRetryable,
2914
3294
  defineConversation,
2915
3295
  defineRuntimeHooks,
2916
3296
  deriveExecutionId,
3297
+ enumerateNeighborPolicies,
2917
3298
  exportEvalRuns,
3299
+ formatSupervisedKnowledgeTask,
2918
3300
  getModels,
2919
3301
  handleChatTurn,
2920
3302
  improve,
2921
3303
  improvementDriver,
2922
3304
  isDelegatedLoopMode,
2923
3305
  isDepthExceeded,
3306
+ knowledgeReadinessDeliverable,
2924
3307
  loopEventToOtelSpan,
2925
3308
  makePerAttemptSignal,
2926
3309
  mcpBuildPrompt,
2927
3310
  mcpServeVerifier,
2928
3311
  mcpToolsForRuntimeMcp,
2929
3312
  mcpToolsForRuntimeMcpSubset,
3313
+ normalizeRolloutPolicy,
2930
3314
  notifyRuntimeDecisionPoint,
2931
3315
  notifyRuntimeHookEvent,
2932
3316
  parseLoopRunnerArgv,
3317
+ parseRolloutPolicy,
3318
+ rawTraceDistiller,
2933
3319
  readDepth,
2934
3320
  readinessServerSentEvent,
2935
3321
  reflectiveGenerator,
@@ -2937,24 +3323,29 @@ export {
2937
3323
  resolveAgentBackend,
2938
3324
  resolveChatModel,
2939
3325
  resolveRouterBaseUrl,
3326
+ rolloutPolicyProposer,
2940
3327
  runAgentTask,
2941
3328
  runAgentTaskStream,
2942
3329
  runConversation,
2943
3330
  runConversationStream,
2944
3331
  runDelegatedLoop,
3332
+ runKnowledgeImprovementJob,
2945
3333
  runLoopRunnerCli,
2946
3334
  runPersonaConversation,
2947
3335
  runPersonaDispatch,
3336
+ runSupervisedKnowledgeUpdate,
2948
3337
  runToolLoop,
2949
3338
  runtimeStreamServerSentEvent,
2950
3339
  sanitizeAgentRuntimeEvent,
2951
3340
  sanitizeKnowledgeReadinessReport,
2952
3341
  sanitizeRuntimeStreamEvent,
2953
3342
  selfImproveLoopRunner,
3343
+ serializeRolloutPolicy,
2954
3344
  sleep,
2955
3345
  slugifySpeaker,
2956
3346
  startRuntimeRun,
2957
3347
  streamToolLoop,
3348
+ structuralRolloutPolicyFromProfile,
2958
3349
  toolBuildPrompt,
2959
3350
  turnId,
2960
3351
  validateChatModelId,