@pasko70/pibo 1.9.13 → 1.10.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 (163) hide show
  1. package/README.md +183 -183
  2. package/context/codex-base-prompt.md +148 -148
  3. package/context/compute-worker.md +23 -23
  4. package/context/pibo-compaction-prompt.md +100 -100
  5. package/context/pibo-native-tooling.md +18 -18
  6. package/context/pibo-system-prompt.md +77 -77
  7. package/dist/apps/chat/agent-profiles.js +2 -2
  8. package/dist/apps/chat/agent-store.js +263 -250
  9. package/dist/apps/chat/chat-request-normalizers.js +17 -0
  10. package/dist/apps/chat/data/chat-data-mappers.js +2 -0
  11. package/dist/apps/chat/data/project-service.js +168 -168
  12. package/dist/apps/chat/data/read-state-service.js +18 -18
  13. package/dist/apps/chat/data/session-query-service.js +25 -25
  14. package/dist/apps/chat/data/timeline-query-service.js +19 -19
  15. package/dist/apps/chat/loop-api.js +181 -0
  16. package/dist/apps/chat/static-assets.js +854 -854
  17. package/dist/apps/chat/web-app.js +36 -16
  18. package/dist/apps/chat/workflow-manual-trigger-runtime.js +149 -46
  19. package/dist/apps/chat/workflow-persistence.js +255 -255
  20. package/dist/apps/chat-ui/assets/{dist-BZ2eTC4f.js → dist-3Sts0Afa.js} +1 -1
  21. package/dist/apps/chat-ui/assets/{dist-BHa-kcGl.js → dist-4NlLjLs7.js} +1 -1
  22. package/dist/apps/chat-ui/assets/{dist-yCYNNb5d.js → dist-BA6mhAec.js} +1 -1
  23. package/dist/apps/chat-ui/assets/{dist-D811wJeV.js → dist-BPl-fzRB.js} +1 -1
  24. package/dist/apps/chat-ui/assets/{dist-Dq4GxJi3.js → dist-BPnn9e2B.js} +1 -1
  25. package/dist/apps/chat-ui/assets/{dist-CzE6k3F3.js → dist-BpfBSMzK.js} +1 -1
  26. package/dist/apps/chat-ui/assets/{dist-CnVsqwSG.js → dist-Cvx5M97R.js} +1 -1
  27. package/dist/apps/chat-ui/assets/{dist-WyXdYl-w.js → dist-DnXWNQRm.js} +1 -1
  28. package/dist/apps/chat-ui/assets/{dist-BNMu92bb.js → dist-hU-2oAb6.js} +1 -1
  29. package/dist/apps/chat-ui/assets/{dist-BCB6zezO.js → dist-r31x5Fcc.js} +1 -1
  30. package/dist/apps/chat-ui/assets/{dist-HqTN67dc.js → dist-uF6UXzI7.js} +1 -1
  31. package/dist/apps/chat-ui/assets/index-CaTGYBOS.js +173 -0
  32. package/dist/apps/chat-ui/assets/{index-C0x9nEcf.css → index-al8DeEjA.css} +1 -1
  33. package/dist/apps/chat-ui/index.html +18 -18
  34. package/dist/apps/chat-ui/manifest.webmanifest +25 -25
  35. package/dist/apps/chat-ui/sw.js +47 -47
  36. package/dist/apps/chat-vscode-web/assets/index-CK4SMZuu.js +41 -0
  37. package/dist/apps/chat-vscode-web/index.html +13 -13
  38. package/dist/apps/cli-ui/cliSessionsCommand.js +23 -23
  39. package/dist/apps/context-files-ui/index.html +11 -11
  40. package/dist/cli-session/localSessionSource.js +34 -12
  41. package/dist/cli.js +61 -44
  42. package/dist/compute/cli.js +54 -54
  43. package/dist/compute/resource-health.js +35 -2
  44. package/dist/core/events.js +6 -1
  45. package/dist/core/routed-session.js +97 -5
  46. package/dist/core/runtime.js +6 -1
  47. package/dist/core/session-router.js +27 -8
  48. package/dist/cron/cli.js +15 -15
  49. package/dist/cron/store.js +49 -49
  50. package/dist/data/cli.js +23 -23
  51. package/dist/data/event-log.js +23 -23
  52. package/dist/data/ingest-service.js +3 -1
  53. package/dist/data/message-store.js +27 -27
  54. package/dist/data/navigation-store.js +9 -9
  55. package/dist/data/observation-store.js +4 -4
  56. package/dist/data/payload-store.js +17 -17
  57. package/dist/data/schema.js +433 -433
  58. package/dist/data/session-store.js +4 -4
  59. package/dist/data/telemetry-queries.js +54 -54
  60. package/dist/data/telemetry.js +197 -197
  61. package/dist/debug/events.js +12 -12
  62. package/dist/debug/failures.js +6 -6
  63. package/dist/debug/index.js +231 -227
  64. package/dist/debug/messages.js +6 -6
  65. package/dist/debug/pty.js +124 -124
  66. package/dist/debug/session.js +29 -29
  67. package/dist/debug/tools.js +5 -5
  68. package/dist/debug/trace.js +42 -7
  69. package/dist/debug/web-snapshot-browser-scripts.js +294 -294
  70. package/dist/debug/web-streaming-browser-library.js +925 -925
  71. package/dist/debug/web-streaming-browser-scripts.js +232 -232
  72. package/dist/debug/web-streaming-provider-telemetry.js +4 -4
  73. package/dist/debug/web.js +93 -93
  74. package/dist/gateway/cli.js +19 -19
  75. package/dist/gateway/server.js +4 -2
  76. package/dist/gateway/web.js +2 -2
  77. package/dist/index.js +1 -0
  78. package/dist/loops/accounting.js +19 -0
  79. package/dist/loops/channel.js +8 -0
  80. package/dist/loops/cli.js +224 -0
  81. package/dist/loops/plugin.js +16 -0
  82. package/dist/loops/prompts.js +86 -0
  83. package/dist/loops/service.js +446 -0
  84. package/dist/loops/stopping.js +170 -0
  85. package/dist/loops/store.js +642 -0
  86. package/dist/loops/templates.js +232 -0
  87. package/dist/loops/tools.js +184 -0
  88. package/dist/loops/types.js +1 -0
  89. package/dist/mcp/config-command.js +53 -53
  90. package/dist/mcp/index.js +21 -21
  91. package/dist/mcp/registry.js +11 -11
  92. package/dist/pi-packages/cli.js +11 -11
  93. package/dist/plugins/builtin.js +8 -0
  94. package/dist/plugins/context-files-store.js +110 -110
  95. package/dist/plugins/context-files.js +4 -4
  96. package/dist/plugins/registry.js +23 -12
  97. package/dist/ralph/cli.js +18 -18
  98. package/dist/ralph/templates.js +140 -140
  99. package/dist/reliability/store.js +256 -229
  100. package/dist/runs/lifecycle.js +59 -0
  101. package/dist/runs/registry.js +47 -1
  102. package/dist/runs/tools.js +31 -13
  103. package/dist/session-ui/terminalRows.js +66 -2
  104. package/dist/sessions/pibo-data-store.js +16 -16
  105. package/dist/sessions/sqlite-store.js +53 -53
  106. package/dist/setup/cli.js +58 -58
  107. package/dist/shared/trace-async-agent-runs.js +4 -4
  108. package/dist/shared/trace-event-projection.js +59 -19
  109. package/dist/shared/trace-nodes.js +5 -0
  110. package/dist/shared/trace-page-merge.js +15 -0
  111. package/dist/shared/trace-run-notifications.js +3 -1
  112. package/dist/signals/projector.js +6 -2
  113. package/dist/tools/agent-browser-wrapper.js +80 -80
  114. package/dist/tools/browser-pool.js +50 -0
  115. package/dist/tools/browser-use-cdp.js +12 -12
  116. package/dist/tools/browser-use-leases.js +12 -8
  117. package/dist/tools/browser-use-wrapper.js +762 -762
  118. package/dist/tools/guides.js +596 -538
  119. package/dist/tools/index.js +123 -99
  120. package/dist/tools/registry.js +21 -3
  121. package/dist/tools/runtime/node-worker-source.js +205 -205
  122. package/dist/tools/runtime/python-worker-source.js +177 -177
  123. package/dist/vscode/cli.js +9 -9
  124. package/dist/web-annotations/cdp.js +900 -900
  125. package/dist/web-annotations/store.js +96 -96
  126. package/docs/README.md +23 -23
  127. package/docs/ops/install-developer-host.md +112 -112
  128. package/docs/ops/install-user-host.md +96 -96
  129. package/docs/ops/upgrade-user-to-developer-host.md +69 -69
  130. package/docs/ops/vscode-extension-release.md +160 -160
  131. package/package.json +99 -95
  132. package/skills/builtin/graphify/SKILL.md +52 -52
  133. package/skills/builtin/loop/SKILL.md +78 -0
  134. package/skills/builtin/pi-agent-harness/SKILL.md +319 -319
  135. package/skills/builtin/pi-agent-harness/agents/openai.yaml +4 -4
  136. package/skills/builtin/pibo-docker-system/SKILL.md +170 -170
  137. package/skills/builtin/pibo-spec-writing/SKILL.md +330 -330
  138. package/skills/builtin/prd/SKILL.md +143 -143
  139. package/skills/builtin/ralph-loop/SKILL.md +361 -359
  140. package/skills/builtin/ralph-prd-json/SKILL.md +123 -123
  141. package/skills/builtin/skill-creator/LICENSE.txt +201 -201
  142. package/skills/builtin/skill-creator/SKILL.md +513 -513
  143. package/skills/builtin/skill-creator/agents/analyzer.md +274 -274
  144. package/skills/builtin/skill-creator/agents/comparator.md +202 -202
  145. package/skills/builtin/skill-creator/agents/grader.md +223 -223
  146. package/skills/builtin/skill-creator/assets/eval_review.html +146 -146
  147. package/skills/builtin/skill-creator/eval-viewer/generate_review.py +471 -471
  148. package/skills/builtin/skill-creator/eval-viewer/viewer.html +1325 -1325
  149. package/skills/builtin/skill-creator/references/schemas.md +430 -430
  150. package/skills/builtin/skill-creator/scripts/aggregate_benchmark.py +401 -401
  151. package/skills/builtin/skill-creator/scripts/generate_report.py +326 -326
  152. package/skills/builtin/skill-creator/scripts/improve_description.py +247 -247
  153. package/skills/builtin/skill-creator/scripts/package_skill.py +136 -136
  154. package/skills/builtin/skill-creator/scripts/quick_validate.py +102 -102
  155. package/skills/builtin/skill-creator/scripts/run_eval.py +310 -310
  156. package/skills/builtin/skill-creator/scripts/run_loop.py +328 -328
  157. package/skills/builtin/skill-creator/scripts/utils.py +47 -47
  158. package/skills/builtin/web-annotations/SKILL.md +93 -93
  159. package/src/mcp/LICENSE.mcp-cli +21 -21
  160. package/dist/apps/chat-ui/assets/index-DwHJfmiF.js +0 -173
  161. package/dist/apps/chat-vscode-web/assets/index-BAMxIaI_.js +0 -41
  162. package/dist/apps/vscode-artifacts/latest.vsix +0 -0
  163. package/dist/apps/vscode-artifacts/pibo-vscode-ext-1.9.13.vsix +0 -0
@@ -1,328 +1,328 @@
1
- #!/usr/bin/env python3
2
- """Run the eval + improve loop until all pass or max iterations reached.
3
-
4
- Combines run_eval.py and improve_description.py in a loop, tracking history
5
- and returning the best description found. Supports train/test split to prevent
6
- overfitting.
7
- """
8
-
9
- import argparse
10
- import json
11
- import random
12
- import sys
13
- import tempfile
14
- import time
15
- import webbrowser
16
- from pathlib import Path
17
-
18
- from scripts.generate_report import generate_html
19
- from scripts.improve_description import improve_description
20
- from scripts.run_eval import find_project_root, run_eval
21
- from scripts.utils import parse_skill_md
22
-
23
-
24
- def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
25
- """Split eval set into train and test sets, stratified by should_trigger."""
26
- random.seed(seed)
27
-
28
- # Separate by should_trigger
29
- trigger = [e for e in eval_set if e["should_trigger"]]
30
- no_trigger = [e for e in eval_set if not e["should_trigger"]]
31
-
32
- # Shuffle each group
33
- random.shuffle(trigger)
34
- random.shuffle(no_trigger)
35
-
36
- # Calculate split points
37
- n_trigger_test = max(1, int(len(trigger) * holdout))
38
- n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
39
-
40
- # Split
41
- test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
42
- train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
43
-
44
- return train_set, test_set
45
-
46
-
47
- def run_loop(
48
- eval_set: list[dict],
49
- skill_path: Path,
50
- description_override: str | None,
51
- num_workers: int,
52
- timeout: int,
53
- max_iterations: int,
54
- runs_per_query: int,
55
- trigger_threshold: float,
56
- holdout: float,
57
- model: str,
58
- verbose: bool,
59
- live_report_path: Path | None = None,
60
- log_dir: Path | None = None,
61
- ) -> dict:
62
- """Run the eval + improvement loop."""
63
- project_root = find_project_root()
64
- name, original_description, content = parse_skill_md(skill_path)
65
- current_description = description_override or original_description
66
-
67
- # Split into train/test if holdout > 0
68
- if holdout > 0:
69
- train_set, test_set = split_eval_set(eval_set, holdout)
70
- if verbose:
71
- print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
72
- else:
73
- train_set = eval_set
74
- test_set = []
75
-
76
- history = []
77
- exit_reason = "unknown"
78
-
79
- for iteration in range(1, max_iterations + 1):
80
- if verbose:
81
- print(f"\n{'='*60}", file=sys.stderr)
82
- print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
83
- print(f"Description: {current_description}", file=sys.stderr)
84
- print(f"{'='*60}", file=sys.stderr)
85
-
86
- # Evaluate train + test together in one batch for parallelism
87
- all_queries = train_set + test_set
88
- t0 = time.time()
89
- all_results = run_eval(
90
- eval_set=all_queries,
91
- skill_name=name,
92
- description=current_description,
93
- num_workers=num_workers,
94
- timeout=timeout,
95
- project_root=project_root,
96
- runs_per_query=runs_per_query,
97
- trigger_threshold=trigger_threshold,
98
- model=model,
99
- )
100
- eval_elapsed = time.time() - t0
101
-
102
- # Split results back into train/test by matching queries
103
- train_queries_set = {q["query"] for q in train_set}
104
- train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
105
- test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
106
-
107
- train_passed = sum(1 for r in train_result_list if r["pass"])
108
- train_total = len(train_result_list)
109
- train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
110
- train_results = {"results": train_result_list, "summary": train_summary}
111
-
112
- if test_set:
113
- test_passed = sum(1 for r in test_result_list if r["pass"])
114
- test_total = len(test_result_list)
115
- test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
116
- test_results = {"results": test_result_list, "summary": test_summary}
117
- else:
118
- test_results = None
119
- test_summary = None
120
-
121
- history.append({
122
- "iteration": iteration,
123
- "description": current_description,
124
- "train_passed": train_summary["passed"],
125
- "train_failed": train_summary["failed"],
126
- "train_total": train_summary["total"],
127
- "train_results": train_results["results"],
128
- "test_passed": test_summary["passed"] if test_summary else None,
129
- "test_failed": test_summary["failed"] if test_summary else None,
130
- "test_total": test_summary["total"] if test_summary else None,
131
- "test_results": test_results["results"] if test_results else None,
132
- # For backward compat with report generator
133
- "passed": train_summary["passed"],
134
- "failed": train_summary["failed"],
135
- "total": train_summary["total"],
136
- "results": train_results["results"],
137
- })
138
-
139
- # Write live report if path provided
140
- if live_report_path:
141
- partial_output = {
142
- "original_description": original_description,
143
- "best_description": current_description,
144
- "best_score": "in progress",
145
- "iterations_run": len(history),
146
- "holdout": holdout,
147
- "train_size": len(train_set),
148
- "test_size": len(test_set),
149
- "history": history,
150
- }
151
- live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
152
-
153
- if verbose:
154
- def print_eval_stats(label, results, elapsed):
155
- pos = [r for r in results if r["should_trigger"]]
156
- neg = [r for r in results if not r["should_trigger"]]
157
- tp = sum(r["triggers"] for r in pos)
158
- pos_runs = sum(r["runs"] for r in pos)
159
- fn = pos_runs - tp
160
- fp = sum(r["triggers"] for r in neg)
161
- neg_runs = sum(r["runs"] for r in neg)
162
- tn = neg_runs - fp
163
- total = tp + tn + fp + fn
164
- precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
165
- recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
166
- accuracy = (tp + tn) / total if total > 0 else 0.0
167
- print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
168
- for r in results:
169
- status = "PASS" if r["pass"] else "FAIL"
170
- rate_str = f"{r['triggers']}/{r['runs']}"
171
- print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
172
-
173
- print_eval_stats("Train", train_results["results"], eval_elapsed)
174
- if test_summary:
175
- print_eval_stats("Test ", test_results["results"], 0)
176
-
177
- if train_summary["failed"] == 0:
178
- exit_reason = f"all_passed (iteration {iteration})"
179
- if verbose:
180
- print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
181
- break
182
-
183
- if iteration == max_iterations:
184
- exit_reason = f"max_iterations ({max_iterations})"
185
- if verbose:
186
- print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
187
- break
188
-
189
- # Improve the description based on train results
190
- if verbose:
191
- print(f"\nImproving description...", file=sys.stderr)
192
-
193
- t0 = time.time()
194
- # Strip test scores from history so improvement model can't see them
195
- blinded_history = [
196
- {k: v for k, v in h.items() if not k.startswith("test_")}
197
- for h in history
198
- ]
199
- new_description = improve_description(
200
- skill_name=name,
201
- skill_content=content,
202
- current_description=current_description,
203
- eval_results=train_results,
204
- history=blinded_history,
205
- model=model,
206
- log_dir=log_dir,
207
- iteration=iteration,
208
- )
209
- improve_elapsed = time.time() - t0
210
-
211
- if verbose:
212
- print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
213
-
214
- current_description = new_description
215
-
216
- # Find the best iteration by TEST score (or train if no test set)
217
- if test_set:
218
- best = max(history, key=lambda h: h["test_passed"] or 0)
219
- best_score = f"{best['test_passed']}/{best['test_total']}"
220
- else:
221
- best = max(history, key=lambda h: h["train_passed"])
222
- best_score = f"{best['train_passed']}/{best['train_total']}"
223
-
224
- if verbose:
225
- print(f"\nExit reason: {exit_reason}", file=sys.stderr)
226
- print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
227
-
228
- return {
229
- "exit_reason": exit_reason,
230
- "original_description": original_description,
231
- "best_description": best["description"],
232
- "best_score": best_score,
233
- "best_train_score": f"{best['train_passed']}/{best['train_total']}",
234
- "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
235
- "final_description": current_description,
236
- "iterations_run": len(history),
237
- "holdout": holdout,
238
- "train_size": len(train_set),
239
- "test_size": len(test_set),
240
- "history": history,
241
- }
242
-
243
-
244
- def main():
245
- parser = argparse.ArgumentParser(description="Run eval + improve loop")
246
- parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
247
- parser.add_argument("--skill-path", required=True, help="Path to skill directory")
248
- parser.add_argument("--description", default=None, help="Override starting description")
249
- parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
250
- parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
251
- parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
252
- parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
253
- parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
254
- parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
255
- parser.add_argument("--model", required=True, help="Model for improvement")
256
- parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
257
- parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
258
- parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
259
- args = parser.parse_args()
260
-
261
- eval_set = json.loads(Path(args.eval_set).read_text())
262
- skill_path = Path(args.skill_path)
263
-
264
- if not (skill_path / "SKILL.md").exists():
265
- print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
266
- sys.exit(1)
267
-
268
- name, _, _ = parse_skill_md(skill_path)
269
-
270
- # Set up live report path
271
- if args.report != "none":
272
- if args.report == "auto":
273
- timestamp = time.strftime("%Y%m%d_%H%M%S")
274
- live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
275
- else:
276
- live_report_path = Path(args.report)
277
- # Open the report immediately so the user can watch
278
- live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
279
- webbrowser.open(str(live_report_path))
280
- else:
281
- live_report_path = None
282
-
283
- # Determine output directory (create before run_loop so logs can be written)
284
- if args.results_dir:
285
- timestamp = time.strftime("%Y-%m-%d_%H%M%S")
286
- results_dir = Path(args.results_dir) / timestamp
287
- results_dir.mkdir(parents=True, exist_ok=True)
288
- else:
289
- results_dir = None
290
-
291
- log_dir = results_dir / "logs" if results_dir else None
292
-
293
- output = run_loop(
294
- eval_set=eval_set,
295
- skill_path=skill_path,
296
- description_override=args.description,
297
- num_workers=args.num_workers,
298
- timeout=args.timeout,
299
- max_iterations=args.max_iterations,
300
- runs_per_query=args.runs_per_query,
301
- trigger_threshold=args.trigger_threshold,
302
- holdout=args.holdout,
303
- model=args.model,
304
- verbose=args.verbose,
305
- live_report_path=live_report_path,
306
- log_dir=log_dir,
307
- )
308
-
309
- # Save JSON output
310
- json_output = json.dumps(output, indent=2)
311
- print(json_output)
312
- if results_dir:
313
- (results_dir / "results.json").write_text(json_output)
314
-
315
- # Write final HTML report (without auto-refresh)
316
- if live_report_path:
317
- live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
318
- print(f"\nReport: {live_report_path}", file=sys.stderr)
319
-
320
- if results_dir and live_report_path:
321
- (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
322
-
323
- if results_dir:
324
- print(f"Results saved to: {results_dir}", file=sys.stderr)
325
-
326
-
327
- if __name__ == "__main__":
328
- main()
1
+ #!/usr/bin/env python3
2
+ """Run the eval + improve loop until all pass or max iterations reached.
3
+
4
+ Combines run_eval.py and improve_description.py in a loop, tracking history
5
+ and returning the best description found. Supports train/test split to prevent
6
+ overfitting.
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import random
12
+ import sys
13
+ import tempfile
14
+ import time
15
+ import webbrowser
16
+ from pathlib import Path
17
+
18
+ from scripts.generate_report import generate_html
19
+ from scripts.improve_description import improve_description
20
+ from scripts.run_eval import find_project_root, run_eval
21
+ from scripts.utils import parse_skill_md
22
+
23
+
24
+ def split_eval_set(eval_set: list[dict], holdout: float, seed: int = 42) -> tuple[list[dict], list[dict]]:
25
+ """Split eval set into train and test sets, stratified by should_trigger."""
26
+ random.seed(seed)
27
+
28
+ # Separate by should_trigger
29
+ trigger = [e for e in eval_set if e["should_trigger"]]
30
+ no_trigger = [e for e in eval_set if not e["should_trigger"]]
31
+
32
+ # Shuffle each group
33
+ random.shuffle(trigger)
34
+ random.shuffle(no_trigger)
35
+
36
+ # Calculate split points
37
+ n_trigger_test = max(1, int(len(trigger) * holdout))
38
+ n_no_trigger_test = max(1, int(len(no_trigger) * holdout))
39
+
40
+ # Split
41
+ test_set = trigger[:n_trigger_test] + no_trigger[:n_no_trigger_test]
42
+ train_set = trigger[n_trigger_test:] + no_trigger[n_no_trigger_test:]
43
+
44
+ return train_set, test_set
45
+
46
+
47
+ def run_loop(
48
+ eval_set: list[dict],
49
+ skill_path: Path,
50
+ description_override: str | None,
51
+ num_workers: int,
52
+ timeout: int,
53
+ max_iterations: int,
54
+ runs_per_query: int,
55
+ trigger_threshold: float,
56
+ holdout: float,
57
+ model: str,
58
+ verbose: bool,
59
+ live_report_path: Path | None = None,
60
+ log_dir: Path | None = None,
61
+ ) -> dict:
62
+ """Run the eval + improvement loop."""
63
+ project_root = find_project_root()
64
+ name, original_description, content = parse_skill_md(skill_path)
65
+ current_description = description_override or original_description
66
+
67
+ # Split into train/test if holdout > 0
68
+ if holdout > 0:
69
+ train_set, test_set = split_eval_set(eval_set, holdout)
70
+ if verbose:
71
+ print(f"Split: {len(train_set)} train, {len(test_set)} test (holdout={holdout})", file=sys.stderr)
72
+ else:
73
+ train_set = eval_set
74
+ test_set = []
75
+
76
+ history = []
77
+ exit_reason = "unknown"
78
+
79
+ for iteration in range(1, max_iterations + 1):
80
+ if verbose:
81
+ print(f"\n{'='*60}", file=sys.stderr)
82
+ print(f"Iteration {iteration}/{max_iterations}", file=sys.stderr)
83
+ print(f"Description: {current_description}", file=sys.stderr)
84
+ print(f"{'='*60}", file=sys.stderr)
85
+
86
+ # Evaluate train + test together in one batch for parallelism
87
+ all_queries = train_set + test_set
88
+ t0 = time.time()
89
+ all_results = run_eval(
90
+ eval_set=all_queries,
91
+ skill_name=name,
92
+ description=current_description,
93
+ num_workers=num_workers,
94
+ timeout=timeout,
95
+ project_root=project_root,
96
+ runs_per_query=runs_per_query,
97
+ trigger_threshold=trigger_threshold,
98
+ model=model,
99
+ )
100
+ eval_elapsed = time.time() - t0
101
+
102
+ # Split results back into train/test by matching queries
103
+ train_queries_set = {q["query"] for q in train_set}
104
+ train_result_list = [r for r in all_results["results"] if r["query"] in train_queries_set]
105
+ test_result_list = [r for r in all_results["results"] if r["query"] not in train_queries_set]
106
+
107
+ train_passed = sum(1 for r in train_result_list if r["pass"])
108
+ train_total = len(train_result_list)
109
+ train_summary = {"passed": train_passed, "failed": train_total - train_passed, "total": train_total}
110
+ train_results = {"results": train_result_list, "summary": train_summary}
111
+
112
+ if test_set:
113
+ test_passed = sum(1 for r in test_result_list if r["pass"])
114
+ test_total = len(test_result_list)
115
+ test_summary = {"passed": test_passed, "failed": test_total - test_passed, "total": test_total}
116
+ test_results = {"results": test_result_list, "summary": test_summary}
117
+ else:
118
+ test_results = None
119
+ test_summary = None
120
+
121
+ history.append({
122
+ "iteration": iteration,
123
+ "description": current_description,
124
+ "train_passed": train_summary["passed"],
125
+ "train_failed": train_summary["failed"],
126
+ "train_total": train_summary["total"],
127
+ "train_results": train_results["results"],
128
+ "test_passed": test_summary["passed"] if test_summary else None,
129
+ "test_failed": test_summary["failed"] if test_summary else None,
130
+ "test_total": test_summary["total"] if test_summary else None,
131
+ "test_results": test_results["results"] if test_results else None,
132
+ # For backward compat with report generator
133
+ "passed": train_summary["passed"],
134
+ "failed": train_summary["failed"],
135
+ "total": train_summary["total"],
136
+ "results": train_results["results"],
137
+ })
138
+
139
+ # Write live report if path provided
140
+ if live_report_path:
141
+ partial_output = {
142
+ "original_description": original_description,
143
+ "best_description": current_description,
144
+ "best_score": "in progress",
145
+ "iterations_run": len(history),
146
+ "holdout": holdout,
147
+ "train_size": len(train_set),
148
+ "test_size": len(test_set),
149
+ "history": history,
150
+ }
151
+ live_report_path.write_text(generate_html(partial_output, auto_refresh=True, skill_name=name))
152
+
153
+ if verbose:
154
+ def print_eval_stats(label, results, elapsed):
155
+ pos = [r for r in results if r["should_trigger"]]
156
+ neg = [r for r in results if not r["should_trigger"]]
157
+ tp = sum(r["triggers"] for r in pos)
158
+ pos_runs = sum(r["runs"] for r in pos)
159
+ fn = pos_runs - tp
160
+ fp = sum(r["triggers"] for r in neg)
161
+ neg_runs = sum(r["runs"] for r in neg)
162
+ tn = neg_runs - fp
163
+ total = tp + tn + fp + fn
164
+ precision = tp / (tp + fp) if (tp + fp) > 0 else 1.0
165
+ recall = tp / (tp + fn) if (tp + fn) > 0 else 1.0
166
+ accuracy = (tp + tn) / total if total > 0 else 0.0
167
+ print(f"{label}: {tp+tn}/{total} correct, precision={precision:.0%} recall={recall:.0%} accuracy={accuracy:.0%} ({elapsed:.1f}s)", file=sys.stderr)
168
+ for r in results:
169
+ status = "PASS" if r["pass"] else "FAIL"
170
+ rate_str = f"{r['triggers']}/{r['runs']}"
171
+ print(f" [{status}] rate={rate_str} expected={r['should_trigger']}: {r['query'][:60]}", file=sys.stderr)
172
+
173
+ print_eval_stats("Train", train_results["results"], eval_elapsed)
174
+ if test_summary:
175
+ print_eval_stats("Test ", test_results["results"], 0)
176
+
177
+ if train_summary["failed"] == 0:
178
+ exit_reason = f"all_passed (iteration {iteration})"
179
+ if verbose:
180
+ print(f"\nAll train queries passed on iteration {iteration}!", file=sys.stderr)
181
+ break
182
+
183
+ if iteration == max_iterations:
184
+ exit_reason = f"max_iterations ({max_iterations})"
185
+ if verbose:
186
+ print(f"\nMax iterations reached ({max_iterations}).", file=sys.stderr)
187
+ break
188
+
189
+ # Improve the description based on train results
190
+ if verbose:
191
+ print(f"\nImproving description...", file=sys.stderr)
192
+
193
+ t0 = time.time()
194
+ # Strip test scores from history so improvement model can't see them
195
+ blinded_history = [
196
+ {k: v for k, v in h.items() if not k.startswith("test_")}
197
+ for h in history
198
+ ]
199
+ new_description = improve_description(
200
+ skill_name=name,
201
+ skill_content=content,
202
+ current_description=current_description,
203
+ eval_results=train_results,
204
+ history=blinded_history,
205
+ model=model,
206
+ log_dir=log_dir,
207
+ iteration=iteration,
208
+ )
209
+ improve_elapsed = time.time() - t0
210
+
211
+ if verbose:
212
+ print(f"Proposed ({improve_elapsed:.1f}s): {new_description}", file=sys.stderr)
213
+
214
+ current_description = new_description
215
+
216
+ # Find the best iteration by TEST score (or train if no test set)
217
+ if test_set:
218
+ best = max(history, key=lambda h: h["test_passed"] or 0)
219
+ best_score = f"{best['test_passed']}/{best['test_total']}"
220
+ else:
221
+ best = max(history, key=lambda h: h["train_passed"])
222
+ best_score = f"{best['train_passed']}/{best['train_total']}"
223
+
224
+ if verbose:
225
+ print(f"\nExit reason: {exit_reason}", file=sys.stderr)
226
+ print(f"Best score: {best_score} (iteration {best['iteration']})", file=sys.stderr)
227
+
228
+ return {
229
+ "exit_reason": exit_reason,
230
+ "original_description": original_description,
231
+ "best_description": best["description"],
232
+ "best_score": best_score,
233
+ "best_train_score": f"{best['train_passed']}/{best['train_total']}",
234
+ "best_test_score": f"{best['test_passed']}/{best['test_total']}" if test_set else None,
235
+ "final_description": current_description,
236
+ "iterations_run": len(history),
237
+ "holdout": holdout,
238
+ "train_size": len(train_set),
239
+ "test_size": len(test_set),
240
+ "history": history,
241
+ }
242
+
243
+
244
+ def main():
245
+ parser = argparse.ArgumentParser(description="Run eval + improve loop")
246
+ parser.add_argument("--eval-set", required=True, help="Path to eval set JSON file")
247
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
248
+ parser.add_argument("--description", default=None, help="Override starting description")
249
+ parser.add_argument("--num-workers", type=int, default=10, help="Number of parallel workers")
250
+ parser.add_argument("--timeout", type=int, default=30, help="Timeout per query in seconds")
251
+ parser.add_argument("--max-iterations", type=int, default=5, help="Max improvement iterations")
252
+ parser.add_argument("--runs-per-query", type=int, default=3, help="Number of runs per query")
253
+ parser.add_argument("--trigger-threshold", type=float, default=0.5, help="Trigger rate threshold")
254
+ parser.add_argument("--holdout", type=float, default=0.4, help="Fraction of eval set to hold out for testing (0 to disable)")
255
+ parser.add_argument("--model", required=True, help="Model for improvement")
256
+ parser.add_argument("--verbose", action="store_true", help="Print progress to stderr")
257
+ parser.add_argument("--report", default="auto", help="Generate HTML report at this path (default: 'auto' for temp file, 'none' to disable)")
258
+ parser.add_argument("--results-dir", default=None, help="Save all outputs (results.json, report.html, log.txt) to a timestamped subdirectory here")
259
+ args = parser.parse_args()
260
+
261
+ eval_set = json.loads(Path(args.eval_set).read_text())
262
+ skill_path = Path(args.skill_path)
263
+
264
+ if not (skill_path / "SKILL.md").exists():
265
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
266
+ sys.exit(1)
267
+
268
+ name, _, _ = parse_skill_md(skill_path)
269
+
270
+ # Set up live report path
271
+ if args.report != "none":
272
+ if args.report == "auto":
273
+ timestamp = time.strftime("%Y%m%d_%H%M%S")
274
+ live_report_path = Path(tempfile.gettempdir()) / f"skill_description_report_{skill_path.name}_{timestamp}.html"
275
+ else:
276
+ live_report_path = Path(args.report)
277
+ # Open the report immediately so the user can watch
278
+ live_report_path.write_text("<html><body><h1>Starting optimization loop...</h1><meta http-equiv='refresh' content='5'></body></html>")
279
+ webbrowser.open(str(live_report_path))
280
+ else:
281
+ live_report_path = None
282
+
283
+ # Determine output directory (create before run_loop so logs can be written)
284
+ if args.results_dir:
285
+ timestamp = time.strftime("%Y-%m-%d_%H%M%S")
286
+ results_dir = Path(args.results_dir) / timestamp
287
+ results_dir.mkdir(parents=True, exist_ok=True)
288
+ else:
289
+ results_dir = None
290
+
291
+ log_dir = results_dir / "logs" if results_dir else None
292
+
293
+ output = run_loop(
294
+ eval_set=eval_set,
295
+ skill_path=skill_path,
296
+ description_override=args.description,
297
+ num_workers=args.num_workers,
298
+ timeout=args.timeout,
299
+ max_iterations=args.max_iterations,
300
+ runs_per_query=args.runs_per_query,
301
+ trigger_threshold=args.trigger_threshold,
302
+ holdout=args.holdout,
303
+ model=args.model,
304
+ verbose=args.verbose,
305
+ live_report_path=live_report_path,
306
+ log_dir=log_dir,
307
+ )
308
+
309
+ # Save JSON output
310
+ json_output = json.dumps(output, indent=2)
311
+ print(json_output)
312
+ if results_dir:
313
+ (results_dir / "results.json").write_text(json_output)
314
+
315
+ # Write final HTML report (without auto-refresh)
316
+ if live_report_path:
317
+ live_report_path.write_text(generate_html(output, auto_refresh=False, skill_name=name))
318
+ print(f"\nReport: {live_report_path}", file=sys.stderr)
319
+
320
+ if results_dir and live_report_path:
321
+ (results_dir / "report.html").write_text(generate_html(output, auto_refresh=False, skill_name=name))
322
+
323
+ if results_dir:
324
+ print(f"Results saved to: {results_dir}", file=sys.stderr)
325
+
326
+
327
+ if __name__ == "__main__":
328
+ main()