@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,247 +1,247 @@
1
- #!/usr/bin/env python3
2
- """Improve a skill description based on eval results.
3
-
4
- Takes eval results (from run_eval.py) and generates an improved description
5
- by calling `claude -p` as a subprocess (same auth pattern as run_eval.py —
6
- uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed).
7
- """
8
-
9
- import argparse
10
- import json
11
- import os
12
- import re
13
- import subprocess
14
- import sys
15
- from pathlib import Path
16
-
17
- from scripts.utils import parse_skill_md
18
-
19
-
20
- def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:
21
- """Run `claude -p` with the prompt on stdin and return the text response.
22
-
23
- Prompt goes over stdin (not argv) because it embeds the full SKILL.md
24
- body and can easily exceed comfortable argv length.
25
- """
26
- cmd = ["claude", "-p", "--output-format", "text"]
27
- if model:
28
- cmd.extend(["--model", model])
29
-
30
- # Remove CLAUDECODE env var to allow nesting claude -p inside a
31
- # Claude Code session. The guard is for interactive terminal conflicts;
32
- # programmatic subprocess usage is safe. Same pattern as run_eval.py.
33
- env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
34
-
35
- result = subprocess.run(
36
- cmd,
37
- input=prompt,
38
- capture_output=True,
39
- text=True,
40
- env=env,
41
- timeout=timeout,
42
- )
43
- if result.returncode != 0:
44
- raise RuntimeError(
45
- f"claude -p exited {result.returncode}\nstderr: {result.stderr}"
46
- )
47
- return result.stdout
48
-
49
-
50
- def improve_description(
51
- skill_name: str,
52
- skill_content: str,
53
- current_description: str,
54
- eval_results: dict,
55
- history: list[dict],
56
- model: str,
57
- test_results: dict | None = None,
58
- log_dir: Path | None = None,
59
- iteration: int | None = None,
60
- ) -> str:
61
- """Call Claude to improve the description based on eval results."""
62
- failed_triggers = [
63
- r for r in eval_results["results"]
64
- if r["should_trigger"] and not r["pass"]
65
- ]
66
- false_triggers = [
67
- r for r in eval_results["results"]
68
- if not r["should_trigger"] and not r["pass"]
69
- ]
70
-
71
- # Build scores summary
72
- train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}"
73
- if test_results:
74
- test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}"
75
- scores_summary = f"Train: {train_score}, Test: {test_score}"
76
- else:
77
- scores_summary = f"Train: {train_score}"
78
-
79
- prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.
80
-
81
- The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.
82
-
83
- Here's the current description:
84
- <current_description>
85
- "{current_description}"
86
- </current_description>
87
-
88
- Current scores ({scores_summary}):
89
- <scores_summary>
90
- """
91
- if failed_triggers:
92
- prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n"
93
- for r in failed_triggers:
94
- prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
95
- prompt += "\n"
96
-
97
- if false_triggers:
98
- prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n"
99
- for r in false_triggers:
100
- prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
101
- prompt += "\n"
102
-
103
- if history:
104
- prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n"
105
- for h in history:
106
- train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}"
107
- test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None
108
- score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "")
109
- prompt += f'<attempt {score_str}>\n'
110
- prompt += f'Description: "{h["description"]}"\n'
111
- if "results" in h:
112
- prompt += "Train results:\n"
113
- for r in h["results"]:
114
- status = "PASS" if r["pass"] else "FAIL"
115
- prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n'
116
- if h.get("note"):
117
- prompt += f'Note: {h["note"]}\n'
118
- prompt += "</attempt>\n\n"
119
-
120
- prompt += f"""</scores_summary>
121
-
122
- Skill content (for context on what the skill does):
123
- <skill_content>
124
- {skill_content}
125
- </skill_content>
126
-
127
- Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:
128
-
129
- 1. Avoid overfitting
130
- 2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.
131
-
132
- Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it.
133
-
134
- Here are some tips that we've found to work well in writing these descriptions:
135
- - The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does"
136
- - The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.
137
- - The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.
138
- - If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.
139
-
140
- I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end.
141
-
142
- Please respond with only the new description text in <new_description> tags, nothing else."""
143
-
144
- text = _call_claude(prompt, model)
145
-
146
- match = re.search(r"<new_description>(.*?)</new_description>", text, re.DOTALL)
147
- description = match.group(1).strip().strip('"') if match else text.strip().strip('"')
148
-
149
- transcript: dict = {
150
- "iteration": iteration,
151
- "prompt": prompt,
152
- "response": text,
153
- "parsed_description": description,
154
- "char_count": len(description),
155
- "over_limit": len(description) > 1024,
156
- }
157
-
158
- # Safety net: the prompt already states the 1024-char hard limit, but if
159
- # the model blew past it anyway, make one fresh single-turn call that
160
- # quotes the too-long version and asks for a shorter rewrite. (The old
161
- # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we
162
- # inline the prior output into the new prompt instead.)
163
- if len(description) > 1024:
164
- shorten_prompt = (
165
- f"{prompt}\n\n"
166
- f"---\n\n"
167
- f"A previous attempt produced this description, which at "
168
- f"{len(description)} characters is over the 1024-character hard limit:\n\n"
169
- f'"{description}"\n\n'
170
- f"Rewrite it to be under 1024 characters while keeping the most "
171
- f"important trigger words and intent coverage. Respond with only "
172
- f"the new description in <new_description> tags."
173
- )
174
- shorten_text = _call_claude(shorten_prompt, model)
175
- match = re.search(r"<new_description>(.*?)</new_description>", shorten_text, re.DOTALL)
176
- shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"')
177
-
178
- transcript["rewrite_prompt"] = shorten_prompt
179
- transcript["rewrite_response"] = shorten_text
180
- transcript["rewrite_description"] = shortened
181
- transcript["rewrite_char_count"] = len(shortened)
182
- description = shortened
183
-
184
- transcript["final_description"] = description
185
-
186
- if log_dir:
187
- log_dir.mkdir(parents=True, exist_ok=True)
188
- log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json"
189
- log_file.write_text(json.dumps(transcript, indent=2))
190
-
191
- return description
192
-
193
-
194
- def main():
195
- parser = argparse.ArgumentParser(description="Improve a skill description based on eval results")
196
- parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)")
197
- parser.add_argument("--skill-path", required=True, help="Path to skill directory")
198
- parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)")
199
- parser.add_argument("--model", required=True, help="Model for improvement")
200
- parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr")
201
- args = parser.parse_args()
202
-
203
- skill_path = Path(args.skill_path)
204
- if not (skill_path / "SKILL.md").exists():
205
- print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
206
- sys.exit(1)
207
-
208
- eval_results = json.loads(Path(args.eval_results).read_text())
209
- history = []
210
- if args.history:
211
- history = json.loads(Path(args.history).read_text())
212
-
213
- name, _, content = parse_skill_md(skill_path)
214
- current_description = eval_results["description"]
215
-
216
- if args.verbose:
217
- print(f"Current: {current_description}", file=sys.stderr)
218
- print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr)
219
-
220
- new_description = improve_description(
221
- skill_name=name,
222
- skill_content=content,
223
- current_description=current_description,
224
- eval_results=eval_results,
225
- history=history,
226
- model=args.model,
227
- )
228
-
229
- if args.verbose:
230
- print(f"Improved: {new_description}", file=sys.stderr)
231
-
232
- # Output as JSON with both the new description and updated history
233
- output = {
234
- "description": new_description,
235
- "history": history + [{
236
- "description": current_description,
237
- "passed": eval_results["summary"]["passed"],
238
- "failed": eval_results["summary"]["failed"],
239
- "total": eval_results["summary"]["total"],
240
- "results": eval_results["results"],
241
- }],
242
- }
243
- print(json.dumps(output, indent=2))
244
-
245
-
246
- if __name__ == "__main__":
247
- main()
1
+ #!/usr/bin/env python3
2
+ """Improve a skill description based on eval results.
3
+
4
+ Takes eval results (from run_eval.py) and generates an improved description
5
+ by calling `claude -p` as a subprocess (same auth pattern as run_eval.py —
6
+ uses the session's Claude Code auth, no separate ANTHROPIC_API_KEY needed).
7
+ """
8
+
9
+ import argparse
10
+ import json
11
+ import os
12
+ import re
13
+ import subprocess
14
+ import sys
15
+ from pathlib import Path
16
+
17
+ from scripts.utils import parse_skill_md
18
+
19
+
20
+ def _call_claude(prompt: str, model: str | None, timeout: int = 300) -> str:
21
+ """Run `claude -p` with the prompt on stdin and return the text response.
22
+
23
+ Prompt goes over stdin (not argv) because it embeds the full SKILL.md
24
+ body and can easily exceed comfortable argv length.
25
+ """
26
+ cmd = ["claude", "-p", "--output-format", "text"]
27
+ if model:
28
+ cmd.extend(["--model", model])
29
+
30
+ # Remove CLAUDECODE env var to allow nesting claude -p inside a
31
+ # Claude Code session. The guard is for interactive terminal conflicts;
32
+ # programmatic subprocess usage is safe. Same pattern as run_eval.py.
33
+ env = {k: v for k, v in os.environ.items() if k != "CLAUDECODE"}
34
+
35
+ result = subprocess.run(
36
+ cmd,
37
+ input=prompt,
38
+ capture_output=True,
39
+ text=True,
40
+ env=env,
41
+ timeout=timeout,
42
+ )
43
+ if result.returncode != 0:
44
+ raise RuntimeError(
45
+ f"claude -p exited {result.returncode}\nstderr: {result.stderr}"
46
+ )
47
+ return result.stdout
48
+
49
+
50
+ def improve_description(
51
+ skill_name: str,
52
+ skill_content: str,
53
+ current_description: str,
54
+ eval_results: dict,
55
+ history: list[dict],
56
+ model: str,
57
+ test_results: dict | None = None,
58
+ log_dir: Path | None = None,
59
+ iteration: int | None = None,
60
+ ) -> str:
61
+ """Call Claude to improve the description based on eval results."""
62
+ failed_triggers = [
63
+ r for r in eval_results["results"]
64
+ if r["should_trigger"] and not r["pass"]
65
+ ]
66
+ false_triggers = [
67
+ r for r in eval_results["results"]
68
+ if not r["should_trigger"] and not r["pass"]
69
+ ]
70
+
71
+ # Build scores summary
72
+ train_score = f"{eval_results['summary']['passed']}/{eval_results['summary']['total']}"
73
+ if test_results:
74
+ test_score = f"{test_results['summary']['passed']}/{test_results['summary']['total']}"
75
+ scores_summary = f"Train: {train_score}, Test: {test_score}"
76
+ else:
77
+ scores_summary = f"Train: {train_score}"
78
+
79
+ prompt = f"""You are optimizing a skill description for a Claude Code skill called "{skill_name}". A "skill" is sort of like a prompt, but with progressive disclosure -- there's a title and description that Claude sees when deciding whether to use the skill, and then if it does use the skill, it reads the .md file which has lots more details and potentially links to other resources in the skill folder like helper files and scripts and additional documentation or examples.
80
+
81
+ The description appears in Claude's "available_skills" list. When a user sends a query, Claude decides whether to invoke the skill based solely on the title and on this description. Your goal is to write a description that triggers for relevant queries, and doesn't trigger for irrelevant ones.
82
+
83
+ Here's the current description:
84
+ <current_description>
85
+ "{current_description}"
86
+ </current_description>
87
+
88
+ Current scores ({scores_summary}):
89
+ <scores_summary>
90
+ """
91
+ if failed_triggers:
92
+ prompt += "FAILED TO TRIGGER (should have triggered but didn't):\n"
93
+ for r in failed_triggers:
94
+ prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
95
+ prompt += "\n"
96
+
97
+ if false_triggers:
98
+ prompt += "FALSE TRIGGERS (triggered but shouldn't have):\n"
99
+ for r in false_triggers:
100
+ prompt += f' - "{r["query"]}" (triggered {r["triggers"]}/{r["runs"]} times)\n'
101
+ prompt += "\n"
102
+
103
+ if history:
104
+ prompt += "PREVIOUS ATTEMPTS (do NOT repeat these — try something structurally different):\n\n"
105
+ for h in history:
106
+ train_s = f"{h.get('train_passed', h.get('passed', 0))}/{h.get('train_total', h.get('total', 0))}"
107
+ test_s = f"{h.get('test_passed', '?')}/{h.get('test_total', '?')}" if h.get('test_passed') is not None else None
108
+ score_str = f"train={train_s}" + (f", test={test_s}" if test_s else "")
109
+ prompt += f'<attempt {score_str}>\n'
110
+ prompt += f'Description: "{h["description"]}"\n'
111
+ if "results" in h:
112
+ prompt += "Train results:\n"
113
+ for r in h["results"]:
114
+ status = "PASS" if r["pass"] else "FAIL"
115
+ prompt += f' [{status}] "{r["query"][:80]}" (triggered {r["triggers"]}/{r["runs"]})\n'
116
+ if h.get("note"):
117
+ prompt += f'Note: {h["note"]}\n'
118
+ prompt += "</attempt>\n\n"
119
+
120
+ prompt += f"""</scores_summary>
121
+
122
+ Skill content (for context on what the skill does):
123
+ <skill_content>
124
+ {skill_content}
125
+ </skill_content>
126
+
127
+ Based on the failures, write a new and improved description that is more likely to trigger correctly. When I say "based on the failures", it's a bit of a tricky line to walk because we don't want to overfit to the specific cases you're seeing. So what I DON'T want you to do is produce an ever-expanding list of specific queries that this skill should or shouldn't trigger for. Instead, try to generalize from the failures to broader categories of user intent and situations where this skill would be useful or not useful. The reason for this is twofold:
128
+
129
+ 1. Avoid overfitting
130
+ 2. The list might get loooong and it's injected into ALL queries and there might be a lot of skills, so we don't want to blow too much space on any given description.
131
+
132
+ Concretely, your description should not be more than about 100-200 words, even if that comes at the cost of accuracy. There is a hard limit of 1024 characters — descriptions over that will be truncated, so stay comfortably under it.
133
+
134
+ Here are some tips that we've found to work well in writing these descriptions:
135
+ - The skill should be phrased in the imperative -- "Use this skill for" rather than "this skill does"
136
+ - The skill description should focus on the user's intent, what they are trying to achieve, vs. the implementation details of how the skill works.
137
+ - The description competes with other skills for Claude's attention — make it distinctive and immediately recognizable.
138
+ - If you're getting lots of failures after repeated attempts, change things up. Try different sentence structures or wordings.
139
+
140
+ I'd encourage you to be creative and mix up the style in different iterations since you'll have multiple opportunities to try different approaches and we'll just grab the highest-scoring one at the end.
141
+
142
+ Please respond with only the new description text in <new_description> tags, nothing else."""
143
+
144
+ text = _call_claude(prompt, model)
145
+
146
+ match = re.search(r"<new_description>(.*?)</new_description>", text, re.DOTALL)
147
+ description = match.group(1).strip().strip('"') if match else text.strip().strip('"')
148
+
149
+ transcript: dict = {
150
+ "iteration": iteration,
151
+ "prompt": prompt,
152
+ "response": text,
153
+ "parsed_description": description,
154
+ "char_count": len(description),
155
+ "over_limit": len(description) > 1024,
156
+ }
157
+
158
+ # Safety net: the prompt already states the 1024-char hard limit, but if
159
+ # the model blew past it anyway, make one fresh single-turn call that
160
+ # quotes the too-long version and asks for a shorter rewrite. (The old
161
+ # SDK path did this as a true multi-turn; `claude -p` is one-shot, so we
162
+ # inline the prior output into the new prompt instead.)
163
+ if len(description) > 1024:
164
+ shorten_prompt = (
165
+ f"{prompt}\n\n"
166
+ f"---\n\n"
167
+ f"A previous attempt produced this description, which at "
168
+ f"{len(description)} characters is over the 1024-character hard limit:\n\n"
169
+ f'"{description}"\n\n'
170
+ f"Rewrite it to be under 1024 characters while keeping the most "
171
+ f"important trigger words and intent coverage. Respond with only "
172
+ f"the new description in <new_description> tags."
173
+ )
174
+ shorten_text = _call_claude(shorten_prompt, model)
175
+ match = re.search(r"<new_description>(.*?)</new_description>", shorten_text, re.DOTALL)
176
+ shortened = match.group(1).strip().strip('"') if match else shorten_text.strip().strip('"')
177
+
178
+ transcript["rewrite_prompt"] = shorten_prompt
179
+ transcript["rewrite_response"] = shorten_text
180
+ transcript["rewrite_description"] = shortened
181
+ transcript["rewrite_char_count"] = len(shortened)
182
+ description = shortened
183
+
184
+ transcript["final_description"] = description
185
+
186
+ if log_dir:
187
+ log_dir.mkdir(parents=True, exist_ok=True)
188
+ log_file = log_dir / f"improve_iter_{iteration or 'unknown'}.json"
189
+ log_file.write_text(json.dumps(transcript, indent=2))
190
+
191
+ return description
192
+
193
+
194
+ def main():
195
+ parser = argparse.ArgumentParser(description="Improve a skill description based on eval results")
196
+ parser.add_argument("--eval-results", required=True, help="Path to eval results JSON (from run_eval.py)")
197
+ parser.add_argument("--skill-path", required=True, help="Path to skill directory")
198
+ parser.add_argument("--history", default=None, help="Path to history JSON (previous attempts)")
199
+ parser.add_argument("--model", required=True, help="Model for improvement")
200
+ parser.add_argument("--verbose", action="store_true", help="Print thinking to stderr")
201
+ args = parser.parse_args()
202
+
203
+ skill_path = Path(args.skill_path)
204
+ if not (skill_path / "SKILL.md").exists():
205
+ print(f"Error: No SKILL.md found at {skill_path}", file=sys.stderr)
206
+ sys.exit(1)
207
+
208
+ eval_results = json.loads(Path(args.eval_results).read_text())
209
+ history = []
210
+ if args.history:
211
+ history = json.loads(Path(args.history).read_text())
212
+
213
+ name, _, content = parse_skill_md(skill_path)
214
+ current_description = eval_results["description"]
215
+
216
+ if args.verbose:
217
+ print(f"Current: {current_description}", file=sys.stderr)
218
+ print(f"Score: {eval_results['summary']['passed']}/{eval_results['summary']['total']}", file=sys.stderr)
219
+
220
+ new_description = improve_description(
221
+ skill_name=name,
222
+ skill_content=content,
223
+ current_description=current_description,
224
+ eval_results=eval_results,
225
+ history=history,
226
+ model=args.model,
227
+ )
228
+
229
+ if args.verbose:
230
+ print(f"Improved: {new_description}", file=sys.stderr)
231
+
232
+ # Output as JSON with both the new description and updated history
233
+ output = {
234
+ "description": new_description,
235
+ "history": history + [{
236
+ "description": current_description,
237
+ "passed": eval_results["summary"]["passed"],
238
+ "failed": eval_results["summary"]["failed"],
239
+ "total": eval_results["summary"]["total"],
240
+ "results": eval_results["results"],
241
+ }],
242
+ }
243
+ print(json.dumps(output, indent=2))
244
+
245
+
246
+ if __name__ == "__main__":
247
+ main()