Upload folder using huggingface_hub
Browse files- DATASET_LINEAGE.md +45 -0
- build_gold300.py +0 -0
- build_gold3000.py +248 -0
- build_gold50.py +600 -0
- build_gold_rust_tooluse.py +1076 -0
- build_rlvr_seed_final_v1.py +536 -0
- build_rlvr_seed_microfix_v1.py +296 -0
- final_glyph_sft_dataset.jsonl +0 -0
DATASET_LINEAGE.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dataset Lineage
|
| 2 |
+
|
| 3 |
+
Canonical clean training file:
|
| 4 |
+
|
| 5 |
+
- `final_glyph_sft_dataset.jsonl`
|
| 6 |
+
|
| 7 |
+
Build chain:
|
| 8 |
+
|
| 9 |
+
1. `build_gold50.py`
|
| 10 |
+
2. `build_gold300.py`
|
| 11 |
+
3. `build_gold3000.py`
|
| 12 |
+
- grows the base corpus
|
| 13 |
+
4. `build_gold_rust_tooluse.py`
|
| 14 |
+
- appends the Rust/tool-use expansion into `gold_glyph_3000.jsonl`
|
| 15 |
+
- introduces the main RL-shaped traces:
|
| 16 |
+
- `read_file -> apply_patch -> cargo_test -> response`
|
| 17 |
+
- `read_file -> apply_patch -> cargo_run -> response`
|
| 18 |
+
5. `build_rlvr_seed_final_v1.py`
|
| 19 |
+
- adds the `137`-trace corrective top-up
|
| 20 |
+
- produces `gold_glyph_3141_plus_rlvr_seed_final_v1.jsonl`
|
| 21 |
+
6. `build_rlvr_seed_microfix_v1.py`
|
| 22 |
+
- adds the final `7`-trace micro-fix
|
| 23 |
+
- produces `gold_glyph_3148_plus_rlvr_seed_microfix_v1.jsonl`
|
| 24 |
+
7. exact dedupe pass
|
| 25 |
+
- removes repeated rows from `gold_glyph_3148_plus_rlvr_seed_microfix_v1.jsonl`
|
| 26 |
+
- produces `final_glyph_sft_dataset.jsonl`
|
| 27 |
+
|
| 28 |
+
Files that matter now:
|
| 29 |
+
|
| 30 |
+
- `gold_glyph_3000.jsonl`
|
| 31 |
+
- `rlvr_seed_final_v1.jsonl`
|
| 32 |
+
- `gold_glyph_3141_plus_rlvr_seed_final_v1.jsonl`
|
| 33 |
+
- `rlvr_seed_microfix_v1.jsonl`
|
| 34 |
+
- `gold_glyph_3148_plus_rlvr_seed_microfix_v1.jsonl`
|
| 35 |
+
- `final_glyph_sft_dataset.jsonl`
|
| 36 |
+
|
| 37 |
+
Repro facts:
|
| 38 |
+
|
| 39 |
+
- `gold_glyph_3000.jsonl` has `3004` rows on disk
|
| 40 |
+
- `gold_glyph_3141_plus_rlvr_seed_final_v1.jsonl` has `3141` rows
|
| 41 |
+
- `gold_glyph_3148_plus_rlvr_seed_microfix_v1.jsonl` has `3148` rows
|
| 42 |
+
- `final_glyph_sft_dataset.jsonl` has `3039` rows
|
| 43 |
+
- all `137` seed traces are in the final `3148` file
|
| 44 |
+
- all `7` micro-fix traces are in the final `3148` file
|
| 45 |
+
- `final_glyph_sft_dataset.jsonl` is the file to use for the clean retrain
|
build_gold300.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
build_gold3000.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import re
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
if str(ROOT) not in sys.path:
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
|
| 13 |
+
from core.validator import validate_trace
|
| 14 |
+
import build_gold300 as g300
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
OUT = Path(__file__).parent / "gold_glyph_3000.jsonl"
|
| 18 |
+
SYSTEM_RE = re.compile(r"(<\|im_start\|>system\n)system「(.*?)」", re.DOTALL)
|
| 19 |
+
USER_RE = re.compile(r"(<\|im_start\|>user\n)user「(.*?)」🏷 usr1", re.DOTALL)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
SYSTEM_VARIANTS = {
|
| 23 |
+
"rust_no_tool": [
|
| 24 |
+
"You are a Rust language assistant who gives compact conceptual explanations.",
|
| 25 |
+
"You are a concise Rust mentor who answers in short technical paragraphs.",
|
| 26 |
+
"You are a Rust engineering explainer who stays brief and practical.",
|
| 27 |
+
"You are a focused Rust assistant who gives short, direct explanations.",
|
| 28 |
+
"You are a practical Rust reviewer who explains tradeoffs concisely.",
|
| 29 |
+
"You are a concise Rust education assistant who prefers concrete answers.",
|
| 30 |
+
"You are a Rust API design assistant who answers briefly and precisely.",
|
| 31 |
+
"You are a Rust systems explainer who keeps answers compact and clear.",
|
| 32 |
+
],
|
| 33 |
+
"rustdoc": [
|
| 34 |
+
"You are a Rust documentation assistant who answers briefly and precisely.",
|
| 35 |
+
"You are a concise Rust docs assistant who explains looked-up symbols clearly.",
|
| 36 |
+
"You are a Rust reference assistant who uses doc results and responds briefly.",
|
| 37 |
+
"You are a practical Rust documentation explainer who keeps answers short.",
|
| 38 |
+
"You are a Rust docs helper who summarizes symbol behavior concisely.",
|
| 39 |
+
"You are a precise Rust API assistant who uses the docs tool and answers briefly.",
|
| 40 |
+
"You are a Rust documentation guide who explains tool results in compact language.",
|
| 41 |
+
"You are a Rust symbol reference assistant who answers in one short explanation.",
|
| 42 |
+
],
|
| 43 |
+
"cargo": [
|
| 44 |
+
"You are a Rust debugging assistant who diagnoses compiler and tool output concisely.",
|
| 45 |
+
"You are a concise Rust build-failure assistant who explains likely fixes briefly.",
|
| 46 |
+
"You are a practical Rust diagnostics assistant who keeps repair guidance short.",
|
| 47 |
+
"You are a Rust troubleshooting assistant who reads tool output and answers tersely.",
|
| 48 |
+
"You are a focused Rust compiler assistant who gives brief diagnosis and repair direction.",
|
| 49 |
+
"You are a Rust code-health assistant who interprets cargo output concisely.",
|
| 50 |
+
"You are a concise Rust lint-and-test assistant who stays practical and direct.",
|
| 51 |
+
"You are a Rust debugging mentor who turns tool output into a short fix recommendation.",
|
| 52 |
+
],
|
| 53 |
+
"ci": [
|
| 54 |
+
"You are a debugging assistant who keeps incident analysis concise and resilient to tool failure.",
|
| 55 |
+
"You are a concise incident assistant who uses evidence first and answers briefly.",
|
| 56 |
+
"You are a practical CI-debugging assistant who gives short, concrete next steps.",
|
| 57 |
+
"You are an operations assistant who keeps failure analysis focused and compact.",
|
| 58 |
+
"You are a concise reliability assistant who prioritizes direct evidence and short answers.",
|
| 59 |
+
"You are a debugging assistant who narrows failures quickly and avoids unnecessary loops.",
|
| 60 |
+
"You are a practical incident triage assistant who answers with one focused recommendation.",
|
| 61 |
+
"You are a concise CI assistant who uses minimal tool steps and short diagnosis.",
|
| 62 |
+
],
|
| 63 |
+
"sql": [
|
| 64 |
+
"You are a data access assistant who uses SQL and answers briefly.",
|
| 65 |
+
"You are a concise analytics assistant who runs one query and responds directly.",
|
| 66 |
+
"You are a practical SQL assistant who returns short, exact answers.",
|
| 67 |
+
"You are a read-only database assistant who answers compactly from query results.",
|
| 68 |
+
"You are a concise reporting assistant who uses SQL and keeps responses short.",
|
| 69 |
+
"You are an analytics helper who prefers one query and a direct answer.",
|
| 70 |
+
"You are a SQL lookup assistant who answers briefly and precisely.",
|
| 71 |
+
"You are a concise data-query assistant who returns only the needed result.",
|
| 72 |
+
],
|
| 73 |
+
"math": [
|
| 74 |
+
"You are a helpful assistant specialized in symbolic mathematics. Provide clear, concise solutions.",
|
| 75 |
+
"You are a concise symbolic math assistant who uses tools and answers briefly.",
|
| 76 |
+
"You are a practical calculus assistant who verifies results and keeps explanations short.",
|
| 77 |
+
"You are a focused symbolic algebra assistant who responds in compact technical language.",
|
| 78 |
+
"You are a concise math-solving assistant who uses one or two precise tool steps.",
|
| 79 |
+
"You are a symbolic math helper who answers clearly and without extra verbosity.",
|
| 80 |
+
"You are a practical mathematics assistant who verifies results and stops promptly.",
|
| 81 |
+
"You are a concise calculus assistant who gives direct final answers after verification.",
|
| 82 |
+
],
|
| 83 |
+
"file": [
|
| 84 |
+
"You are a document assistant who reads a file and returns a short, concrete summary.",
|
| 85 |
+
"You are a concise file-reading assistant who summarizes excerpts directly.",
|
| 86 |
+
"You are a practical document assistant who answers with short, specific takeaways.",
|
| 87 |
+
"You are a concise notes assistant who loads a file and summarizes only the essentials.",
|
| 88 |
+
"You are a focused document summarizer who keeps outputs short and concrete.",
|
| 89 |
+
"You are a brief file-summary assistant who extracts only the main conclusions.",
|
| 90 |
+
"You are a practical reading assistant who turns excerpts into tight summaries.",
|
| 91 |
+
"You are a concise document-review assistant who answers in one short summary.",
|
| 92 |
+
],
|
| 93 |
+
"plan": [
|
| 94 |
+
"You are a planning assistant that helps product teams build realistic launch plans and concise schedules.",
|
| 95 |
+
"You are a concise planning assistant who checks staffing and produces short rollout recommendations.",
|
| 96 |
+
"You are a practical launch-planning assistant who keeps plans realistic and brief.",
|
| 97 |
+
"You are a scheduling assistant who gives compact rollout guidance grounded in tool results.",
|
| 98 |
+
"You are a concise product-planning assistant who answers with short, actionable schedules.",
|
| 99 |
+
"You are a practical operations planner who checks feasibility and responds briefly.",
|
| 100 |
+
"You are a concise launch assistant who uses staffing data and keeps output tight.",
|
| 101 |
+
"You are a planning helper who turns availability and task data into short rollout guidance.",
|
| 102 |
+
],
|
| 103 |
+
"git": [
|
| 104 |
+
"You are a concise git assistant who reads repository status and answers briefly.",
|
| 105 |
+
"You are a practical git hygiene assistant who summarizes repo state compactly.",
|
| 106 |
+
"You are a concise version-control assistant who uses git tools and answers directly.",
|
| 107 |
+
"You are a git workflow assistant who keeps status summaries short and concrete.",
|
| 108 |
+
"You are a practical git review assistant who reports only the important repo details.",
|
| 109 |
+
"You are a concise source-control assistant who answers with brief actionable summaries.",
|
| 110 |
+
"You are a git diagnostics assistant who reads repository metadata and stays short.",
|
| 111 |
+
"You are a practical repository assistant who gives compact git-based answers.",
|
| 112 |
+
],
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
NO_TOOL_PREFIXES = [
|
| 117 |
+
"Briefly, ",
|
| 118 |
+
"In one short paragraph, ",
|
| 119 |
+
"Give a concise answer: ",
|
| 120 |
+
"Short answer: ",
|
| 121 |
+
]
|
| 122 |
+
NO_TOOL_SUFFIXES = [
|
| 123 |
+
" Keep the answer concise.",
|
| 124 |
+
" Answer briefly.",
|
| 125 |
+
" Give a short practical explanation.",
|
| 126 |
+
" Keep it to the key point.",
|
| 127 |
+
]
|
| 128 |
+
TOOL_PREFIXES = [
|
| 129 |
+
"Briefly, ",
|
| 130 |
+
"Keep it short: ",
|
| 131 |
+
"Concisely, ",
|
| 132 |
+
"Give a short answer: ",
|
| 133 |
+
]
|
| 134 |
+
TOOL_SUFFIXES = [
|
| 135 |
+
" Use the available tool support and keep the answer concise.",
|
| 136 |
+
" Use the tool flow and answer briefly.",
|
| 137 |
+
" Keep the final answer short.",
|
| 138 |
+
" Keep it compact.",
|
| 139 |
+
]
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def infer_category(trace: str) -> str:
|
| 143 |
+
if "rustdoc_lookup" in trace and not any(x in trace for x in ("cargo_check", "cargo_test", "cargo_clippy")):
|
| 144 |
+
return "rustdoc"
|
| 145 |
+
if any(x in trace for x in ("cargo_check", "cargo_test", "cargo_clippy")):
|
| 146 |
+
return "cargo"
|
| 147 |
+
if "get_ci_logs" in trace:
|
| 148 |
+
return "ci"
|
| 149 |
+
if "run_sql" in trace:
|
| 150 |
+
return "sql"
|
| 151 |
+
if "solve_symbolic" in trace:
|
| 152 |
+
return "math"
|
| 153 |
+
if "load_file" in trace:
|
| 154 |
+
return "file"
|
| 155 |
+
if "get_availability" in trace:
|
| 156 |
+
return "plan"
|
| 157 |
+
if "git_status" in trace or "git_log" in trace:
|
| 158 |
+
return "git"
|
| 159 |
+
return "rust_no_tool"
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def replace_system(trace: str, system_text: str) -> str:
|
| 163 |
+
return SYSTEM_RE.sub(rf"\1system「{system_text}」", trace, count=1)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def replace_user(trace: str, user_text: str) -> str:
|
| 167 |
+
return USER_RE.sub(rf"\1user「{user_text}」🏷 usr1", trace, count=1)
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def extract_user(trace: str) -> str:
|
| 171 |
+
m = USER_RE.search(trace)
|
| 172 |
+
if not m:
|
| 173 |
+
raise ValueError("user segment not found")
|
| 174 |
+
return m.group(2)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def has_tools(trace: str) -> bool:
|
| 178 |
+
return "<|im_start|>tool" in trace or "tool {" in trace
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def vary_user_text(user_text: str, idx: int, tooly: bool) -> str:
|
| 182 |
+
if idx == 0:
|
| 183 |
+
return user_text
|
| 184 |
+
prefixes = TOOL_PREFIXES if tooly else NO_TOOL_PREFIXES
|
| 185 |
+
suffixes = TOOL_SUFFIXES if tooly else NO_TOOL_SUFFIXES
|
| 186 |
+
style = (idx - 1) % 4
|
| 187 |
+
if (idx - 1) // 4 == 0:
|
| 188 |
+
return prefixes[style] + user_text[0].lower() + user_text[1:] if user_text and user_text[0].isupper() else prefixes[style] + user_text
|
| 189 |
+
return user_text + suffixes[style]
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def augment_trace(trace: str, idx: int) -> str:
|
| 193 |
+
category = infer_category(trace)
|
| 194 |
+
system_text = SYSTEM_VARIANTS[category][idx % len(SYSTEM_VARIANTS[category])]
|
| 195 |
+
user_text = vary_user_text(extract_user(trace), idx, has_tools(trace))
|
| 196 |
+
return replace_user(replace_system(trace, system_text), user_text)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def build_records() -> list[str]:
|
| 200 |
+
base = g300.extend_records()
|
| 201 |
+
traces: list[str] = []
|
| 202 |
+
seen: set[str] = set()
|
| 203 |
+
|
| 204 |
+
def add(trace: str) -> None:
|
| 205 |
+
if trace not in seen:
|
| 206 |
+
seen.add(trace)
|
| 207 |
+
traces.append(trace)
|
| 208 |
+
|
| 209 |
+
for trace in base:
|
| 210 |
+
add(trace)
|
| 211 |
+
|
| 212 |
+
# 7 additional variants per seed trace.
|
| 213 |
+
for variant_idx in range(1, 8):
|
| 214 |
+
for trace in base:
|
| 215 |
+
add(augment_trace(trace, variant_idx))
|
| 216 |
+
|
| 217 |
+
# One more variant for the first 100 traces.
|
| 218 |
+
for trace in base[:100]:
|
| 219 |
+
add(augment_trace(trace, 8))
|
| 220 |
+
|
| 221 |
+
extra_idx = 9
|
| 222 |
+
while len(traces) < 2500:
|
| 223 |
+
for trace in base:
|
| 224 |
+
add(augment_trace(trace, extra_idx))
|
| 225 |
+
if len(traces) == 2500:
|
| 226 |
+
break
|
| 227 |
+
extra_idx += 1
|
| 228 |
+
|
| 229 |
+
assert len(traces) == 2500, len(traces)
|
| 230 |
+
return traces
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
def main() -> int:
|
| 234 |
+
traces = build_records()
|
| 235 |
+
bad: list[tuple[int, list[str]]] = []
|
| 236 |
+
with OUT.open("w") as f:
|
| 237 |
+
for i, trace in enumerate(traces, start=1):
|
| 238 |
+
res = validate_trace(trace)
|
| 239 |
+
if not res.valid:
|
| 240 |
+
bad.append((i, res.errors))
|
| 241 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 242 |
+
rustish = sum(1 for t in traces if ("Rust" in t or "rust" in t or "cargo_" in t or "rustdoc_" in t))
|
| 243 |
+
print(json.dumps({"count": len(traces), "rustish": rustish, "ratio": rustish / len(traces), "output": str(OUT), "invalid": bad[:20], "invalid_count": len(bad)}, indent=2))
|
| 244 |
+
return 0 if not bad else 1
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
if __name__ == "__main__":
|
| 248 |
+
raise SystemExit(main())
|
build_gold50.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
|
| 4 |
+
import json
|
| 5 |
+
import sys
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 10 |
+
if str(ROOT) not in sys.path:
|
| 11 |
+
sys.path.insert(0, str(ROOT))
|
| 12 |
+
|
| 13 |
+
from core.validator import validate_trace
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
OUT = Path(__file__).parent / "gold_glyph_50.jsonl"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
@dataclass(frozen=True)
|
| 20 |
+
class ToolParam:
|
| 21 |
+
name: str
|
| 22 |
+
kind: str
|
| 23 |
+
description: str
|
| 24 |
+
required: bool = True
|
| 25 |
+
enum_values: tuple[str, ...] = ()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
@dataclass(frozen=True)
|
| 29 |
+
class ToolDef:
|
| 30 |
+
name: str
|
| 31 |
+
description: str
|
| 32 |
+
params: tuple[ToolParam, ...]
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def param(name: str, kind: str, description: str, required: bool = True) -> ToolParam:
|
| 36 |
+
return ToolParam(name, kind, description, required)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def enum_param(name: str, values: tuple[str, ...], description: str, required: bool = True) -> ToolParam:
|
| 40 |
+
return ToolParam(name, "enum", description, required, values)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def tool(name: str, description: str, *params: ToolParam) -> ToolDef:
|
| 44 |
+
return ToolDef(name, description, params)
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def render_tools(tools: list[ToolDef]) -> str:
|
| 48 |
+
parts: list[str] = []
|
| 49 |
+
for t in tools:
|
| 50 |
+
lines = [
|
| 51 |
+
"tool {",
|
| 52 |
+
f" name ↦ {t.name} •",
|
| 53 |
+
f' description ↦ "{t.description}" •',
|
| 54 |
+
" params ↦ {",
|
| 55 |
+
]
|
| 56 |
+
row_parts = []
|
| 57 |
+
for p in t.params:
|
| 58 |
+
inner = [f'enum ↦ [ {" • ".join(p.enum_values)} ]' if p.enum_values else f"type ↦ {p.kind}"]
|
| 59 |
+
if not p.required:
|
| 60 |
+
inner.append("required ↦ false")
|
| 61 |
+
inner.append(f'description ↦ "{p.description}"')
|
| 62 |
+
row_parts.append(f" {p.name} ↦ {{ {' • '.join(inner)} }}")
|
| 63 |
+
lines.append(" •\n".join(row_parts) if row_parts else "")
|
| 64 |
+
lines.append(" }")
|
| 65 |
+
lines.append("}")
|
| 66 |
+
parts.append("\n".join(lines))
|
| 67 |
+
return "\n".join(parts)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def seg(role: str, body: str) -> str:
|
| 71 |
+
return f"<|im_start|>{role}\n{body}\n<|im_end|>"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def system_seg(text: str, tools: list[ToolDef] | None = None) -> str:
|
| 75 |
+
body = [f"system「{text}」"]
|
| 76 |
+
if tools:
|
| 77 |
+
body.append(render_tools(tools))
|
| 78 |
+
return seg("system", "\n".join(body))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def user_seg(text: str) -> str:
|
| 82 |
+
return seg("user", f"user「{text}」🏷 usr1")
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def plan_block(todos: list[str], rationale: str) -> str:
|
| 86 |
+
lines = ["plan {", " todo ↦ {"]
|
| 87 |
+
for i, todo in enumerate(todos, start=1):
|
| 88 |
+
sep = " •" if i < len(todos) else ""
|
| 89 |
+
lines.append(f' {i} ↦ "{todo}" ※ usr1{sep}')
|
| 90 |
+
lines.extend([" } •", f' rationale ↦ "{rationale}"', "}"])
|
| 91 |
+
return "\n".join(lines)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def think_act(thoughts: list[tuple[str, str, list[str]]]) -> str:
|
| 95 |
+
lines = ["act {", " think ↦ ["]
|
| 96 |
+
for i, (text, tag, refs) in enumerate(thoughts):
|
| 97 |
+
ref_text = f" ※ [ {' • '.join(refs)} ]" if refs else ""
|
| 98 |
+
sep = " •" if i < len(thoughts) - 1 else ""
|
| 99 |
+
lines.append(f' 「{text}」 𝑝 0.9 🏷 {tag}{ref_text}{sep}')
|
| 100 |
+
lines.extend([" ]", "}"])
|
| 101 |
+
return "\n".join(lines)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def call_act(tool_name: str, args: list[tuple[str, str]], call_id: str, satisfies: int) -> str:
|
| 105 |
+
lines = ["act {", " call ↦ {"]
|
| 106 |
+
rows = [f" tool ↦ {tool_name}"]
|
| 107 |
+
rows.extend(f' {k} ↦ "{v}"' for k, v in args)
|
| 108 |
+
rows.append(f" id ↦ {call_id}")
|
| 109 |
+
lines.append(" •\n".join(rows))
|
| 110 |
+
lines.extend([f" }} ⊨ {satisfies}", "}"])
|
| 111 |
+
return "\n".join(lines)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def result_seg(data: str, tag: str) -> str:
|
| 115 |
+
return seg("tool", f'result {{\n data ↦ "{data}" 🏷 {tag}\n}}')
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def response_block(text: str, refs: list[str], satisfies: int) -> str:
|
| 119 |
+
return "\n".join([f"response「{text}」", f"※ [ {' • '.join(refs)} ]", f"⊨ {satisfies}"])
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def assistant_seg(*blocks: str) -> str:
|
| 123 |
+
return seg("assistant", "\n\n".join(blocks))
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def join_trace(*segments: str) -> str:
|
| 127 |
+
return "\n\n".join(segments)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
def no_tool_trace(system: str, user: str, todo: str, rationale: str, think: str, response: str, note_tag: str) -> str:
|
| 131 |
+
return join_trace(
|
| 132 |
+
system_seg(system),
|
| 133 |
+
user_seg(user),
|
| 134 |
+
assistant_seg(
|
| 135 |
+
plan_block([todo], rationale),
|
| 136 |
+
think_act([(think, note_tag, ["usr1"])]),
|
| 137 |
+
response_block(response, [note_tag], 1),
|
| 138 |
+
),
|
| 139 |
+
)
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def single_tool_trace(system: str, tools: list[ToolDef], user: str, todos: list[str], rationale: str,
|
| 143 |
+
call_tool: str, call_args: list[tuple[str, str]], call_id: str,
|
| 144 |
+
result_data: str, think: str, note_tag: str, response: str) -> str:
|
| 145 |
+
return join_trace(
|
| 146 |
+
system_seg(system, tools),
|
| 147 |
+
user_seg(user),
|
| 148 |
+
assistant_seg(plan_block(todos, rationale), call_act(call_tool, call_args, call_id, 1)),
|
| 149 |
+
result_seg(result_data, call_id),
|
| 150 |
+
assistant_seg(
|
| 151 |
+
think_act([(think, note_tag, [call_id])]),
|
| 152 |
+
response_block(response, [call_id, note_tag], 2),
|
| 153 |
+
),
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def multi_tool_trace(system: str, tools: list[ToolDef], user: str, todos: list[str], rationale: str,
|
| 158 |
+
call1_tool: str, call1_args: list[tuple[str, str]], call1_id: str, result1: str, think1: str, tag1: str,
|
| 159 |
+
call2_tool: str, call2_args: list[tuple[str, str]], call2_id: str, result2: str, think2: str, tag2: str,
|
| 160 |
+
response: str) -> str:
|
| 161 |
+
return join_trace(
|
| 162 |
+
system_seg(system, tools),
|
| 163 |
+
user_seg(user),
|
| 164 |
+
assistant_seg(plan_block(todos, rationale), call_act(call1_tool, call1_args, call1_id, 1)),
|
| 165 |
+
result_seg(result1, call1_id),
|
| 166 |
+
assistant_seg(think_act([(think1, tag1, [call1_id])]), call_act(call2_tool, call2_args, call2_id, 2)),
|
| 167 |
+
result_seg(result2, call2_id),
|
| 168 |
+
assistant_seg(think_act([(think2, tag2, [call1_id, call2_id])]), response_block(response, [call1_id, call2_id, tag2], 3)),
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def records() -> list[str]:
|
| 173 |
+
rustdoc = [tool("rustdoc_lookup", "Returns concise documentation for a Rust symbol.", param("symbol", "string", "Rust symbol"))]
|
| 174 |
+
cargo = [
|
| 175 |
+
tool("cargo_check", "Runs cargo check on a Rust crate and returns the main compiler diagnostics.", param("crate_path", "string", "Path to the crate", required=False)),
|
| 176 |
+
tool("cargo_test", "Runs cargo test and returns failing test output.", param("crate_path", "string", "Path to the crate", required=False), param("filter", "string", "Optional test filter", required=False)),
|
| 177 |
+
tool("cargo_clippy", "Runs cargo clippy and returns the main lints.", param("crate_path", "string", "Path to the crate", required=False)),
|
| 178 |
+
tool("rustdoc_lookup", "Returns concise documentation for a Rust type, trait, macro, or function.", param("symbol", "string", "Rust symbol to look up", required=False)),
|
| 179 |
+
]
|
| 180 |
+
ci_tools = [
|
| 181 |
+
tool("get_ci_logs", "Fetches CI logs for a run.", param("run_id", "string", "Run id")),
|
| 182 |
+
tool("code_search", "Searches the codebase.", param("query", "string", "Search query")),
|
| 183 |
+
tool("fetch_cached_incident", "Returns a cached incident note.", param("service", "string", "Service name")),
|
| 184 |
+
]
|
| 185 |
+
sql_tools = [tool("run_sql", "Executes a read-only SQL query.", param("query", "string", "SQL query text"))]
|
| 186 |
+
math_tools = [
|
| 187 |
+
tool("solve_symbolic", "Performs symbolic math operations.", param("expression", "string", "Expression"), enum_param("operation", ("integrate", "differentiate", "simplify", "factor"), "Operation"), param("variable", "string", "Variable")),
|
| 188 |
+
tool("derivative_check", "Differentiates a candidate and compares it to a target expression.", param("candidate_antiderivative", "string", "Candidate"), param("target_expression", "string", "Target"), param("variable", "string", "Variable")),
|
| 189 |
+
]
|
| 190 |
+
file_tools = [tool("load_file", "Loads a file from disk and returns a short excerpt.", param("path", "string", "Path to load"))]
|
| 191 |
+
git_tools = [
|
| 192 |
+
tool("git_status", "Returns a concise git status (branch, dirty files, and staged changes).", param("repo_path", "string", "Path to the git repository", required=False)),
|
| 193 |
+
tool("git_log", "Shows recent commits in a concise one-line format.", param("repo_path", "string", "Path to the git repository", required=False), param("limit", "number", "Maximum number of commits to show", required=False)),
|
| 194 |
+
]
|
| 195 |
+
plan_tools = [
|
| 196 |
+
tool("get_availability", "Returns weekly availability by teammate.", param("team_list", "string", "Comma-separated IDs", required=False), param("start_date", "string", "Start date", required=False), param("end_date", "string", "End date", required=False)),
|
| 197 |
+
tool("create_project_plan", "Generates a short work breakdown.", param("project_name", "string", "Project name", required=False), param("objectives", "string", "Objectives", required=False), param("timeline_weeks", "string", "Timeline in weeks", required=False)),
|
| 198 |
+
]
|
| 199 |
+
|
| 200 |
+
traces: list[str] = []
|
| 201 |
+
|
| 202 |
+
traces.extend([
|
| 203 |
+
no_tool_trace("You are a Rust language assistant who gives compact conceptual explanations.",
|
| 204 |
+
"In Rust, when would you choose an enum over a trait-object-based design? Give one concrete tradeoff and a simple rule of thumb.",
|
| 205 |
+
"Explain the tradeoff and give a short rule of thumb.",
|
| 206 |
+
"Define the main distinction, then give one practical heuristic.",
|
| 207 |
+
"Contrast closed sets of variants with open-ended extensibility, then end with one pragmatic selection rule.",
|
| 208 |
+
"Use an enum when you control a fixed set of variants and want exhaustive matching; use trait objects when you need open-ended implementations and can accept dynamic dispatch. Rule of thumb: fixed variants -> enum, plugin-like extensibility -> trait objects.",
|
| 209 |
+
"note_enum_vs_dyn"),
|
| 210 |
+
no_tool_trace("You are a Rust async explainer who writes concise technical answers.",
|
| 211 |
+
"In async Rust, what does Send mean for a Future, and when do I need it?",
|
| 212 |
+
"Explain what Send on a Future guarantees and when it matters.",
|
| 213 |
+
"Define the guarantee first, then state the practical executor boundary.",
|
| 214 |
+
"State that Send means the future can move across threads safely, then tie it to multithreaded executors.",
|
| 215 |
+
"A Future is Send if it can be moved between threads safely while suspended. You need it when spawning onto a multithreaded executor like the default Tokio runtime; you do not need it for strictly single-threaded local execution.",
|
| 216 |
+
"note_future_send"),
|
| 217 |
+
no_tool_trace("You are a Rust education assistant who explains ownership tradeoffs briefly.",
|
| 218 |
+
"Why is Rc not Send in Rust?",
|
| 219 |
+
"Explain why Rc is not thread-safe.",
|
| 220 |
+
"Connect reference-count mutation to thread safety in one short explanation.",
|
| 221 |
+
"Point out that Rc updates shared refcounts without atomic operations, which is fine on one thread but unsafe across threads.",
|
| 222 |
+
"Rc is not Send because its reference count is updated non-atomically, so moving it across threads could race and corrupt the count. Use Arc when shared ownership must cross thread boundaries.",
|
| 223 |
+
"note_rc_send"),
|
| 224 |
+
no_tool_trace("You are a practical Rust mentor who answers in short paragraphs.",
|
| 225 |
+
"When should I prefer PathBuf over String for filesystem paths in Rust?",
|
| 226 |
+
"Explain when PathBuf is the better choice for paths.",
|
| 227 |
+
"Tie the recommendation to semantics and platform correctness.",
|
| 228 |
+
"Emphasize that paths are not just text and should use path-specific types when code manipulates filesystem locations.",
|
| 229 |
+
"Prefer PathBuf when the value represents a filesystem path, especially if you will join, normalize, or pass it to file APIs. It models platform path semantics correctly, whereas String is just text.",
|
| 230 |
+
"note_pathbuf"),
|
| 231 |
+
no_tool_trace("You are a concise systems explainer.",
|
| 232 |
+
"What problem do Arc and Mutex solve together in Rust?",
|
| 233 |
+
"Explain what Arc<Mutex<T>> enables.",
|
| 234 |
+
"State the ownership and synchronization pieces separately, then combine them.",
|
| 235 |
+
"Describe Arc as shared ownership across threads and Mutex as coordinated mutable access to the inner value.",
|
| 236 |
+
"Arc<Mutex<T>> gives multiple threads shared ownership of the same value while ensuring only one thread mutates it at a time. Arc solves ownership sharing; Mutex solves synchronized interior mutability.",
|
| 237 |
+
"note_arc_mutex"),
|
| 238 |
+
no_tool_trace("You are a concise engineering explainer.",
|
| 239 |
+
"Why do long-lived Git branches create so many merge conflicts on small teams?",
|
| 240 |
+
"Explain the main cause of frequent merge conflicts.",
|
| 241 |
+
"Tie conflicts to delayed integration and overlapping edits.",
|
| 242 |
+
"Keep the explanation centered on long-lived divergence and multiple people editing the same areas before integrating.",
|
| 243 |
+
"Long-lived branches create more merge conflicts because they let code drift farther from main while multiple people keep editing the same files. The longer work stays unintegrated, the more likely those edits collide when you finally merge.",
|
| 244 |
+
"note_git_conflicts"),
|
| 245 |
+
no_tool_trace("You are a concise architecture reviewer.",
|
| 246 |
+
"Why are rollout plans safer when they move low-risk services first?",
|
| 247 |
+
"Explain why staged rollout order matters.",
|
| 248 |
+
"Connect rollout order to blast radius and learning.",
|
| 249 |
+
"State that early low-risk migrations surface hidden assumptions before the riskiest cutovers.",
|
| 250 |
+
"Starting with low-risk services reduces blast radius and lets the team discover tooling, networking, and observability problems before touching critical workloads. It turns the first migrations into learning steps instead of existential bets.",
|
| 251 |
+
"note_rollout_order"),
|
| 252 |
+
no_tool_trace("You are a concise data engineering mentor.",
|
| 253 |
+
"Why should production schema changes use migrations instead of creating tables at app startup?",
|
| 254 |
+
"Explain the operational reason for migrations.",
|
| 255 |
+
"Center the answer on explicitness, repeatability, and safety.",
|
| 256 |
+
"Keep the explanation about reviewable state changes and safer deploys.",
|
| 257 |
+
"Use migrations in production because they make schema changes explicit, reviewable, and repeatable across environments. Startup-created tables are convenient for prototypes, but they hide change history and make coordinated deploys riskier.",
|
| 258 |
+
"note_migrations"),
|
| 259 |
+
no_tool_trace("You are a concise systems mentor.",
|
| 260 |
+
"Why do flaky tests often come from hidden time or concurrency assumptions?",
|
| 261 |
+
"Explain the main source of flakiness.",
|
| 262 |
+
"Connect nondeterminism to scheduling, timing, and shared state.",
|
| 263 |
+
"Keep it focused on tests depending on events that do not happen in a fixed order every run.",
|
| 264 |
+
"Flaky tests often depend on timing or scheduling that is not deterministic, such as background tasks, retries, shared state, or race-prone setup. When a test assumes a precise order or latency budget, small runtime differences can make it pass sometimes and fail other times.",
|
| 265 |
+
"note_flaky_tests"),
|
| 266 |
+
no_tool_trace("You are a concise reliability explainer.",
|
| 267 |
+
"What is the operational risk of using broad allow rules to silence clippy warnings?",
|
| 268 |
+
"Explain why broad lint suppression is risky.",
|
| 269 |
+
"Tie it to hiding future regressions.",
|
| 270 |
+
"Keep the answer short and emphasize that broad suppression makes future bad patterns invisible.",
|
| 271 |
+
"Broad allow rules hide both the current warning and similar future regressions, so the codebase loses signal right where the team wanted safety feedback. It is safer to suppress a specific lint narrowly or fix the root cause.",
|
| 272 |
+
"note_clippy_allow"),
|
| 273 |
+
])
|
| 274 |
+
|
| 275 |
+
rust_doc_items = [
|
| 276 |
+
("std::mem::take", "Look up std::mem::take in the docs tool.", "Explain what it does briefly.", "Use one tool call, then summarize the behavior and Default requirement.", "std::mem::take", "Replaces a value behind a mutable reference with Default::default() and returns the previous value.", "Use the doc wording directly and mention the Default requirement.", "std::mem::take replaces the value behind a mutable reference with Default::default() and returns the old value, so the type must implement Default."),
|
| 277 |
+
("Option::take", "Look up Option::take in the docs tool.", "Explain what it does briefly.", "Use one tool call, then summarize the move-out behavior.", "Option::take", "Takes the value out of the option, leaving None in its place.", "State that it moves the contents out and leaves None behind.", "Option::take moves the current value out of an Option and leaves None behind, which is handy for taking ownership from a field safely."),
|
| 278 |
+
("Iterator::fold", "Look up Iterator::fold in the docs tool.", "Explain the accumulator behavior briefly.", "Use one tool call, then summarize the fold contract.", "Iterator::fold", "Takes an initial accumulator and applies a closure to the accumulator and each element to produce one final value.", "Describe fold as repeated accumulation into one value.", "Iterator::fold reduces an iterator to one final value by repeatedly applying a closure to an accumulator, starting from an initial value."),
|
| 279 |
+
("Vec::with_capacity", "Look up Vec::with_capacity in the docs tool.", "Explain its effect on allocation briefly.", "Use one tool call, then summarize capacity versus length.", "Vec::with_capacity", "Creates a new, empty Vec with at least the specified capacity.", "Point out that length stays zero while capacity is preallocated.", "Vec::with_capacity creates an empty vector with preallocated space for at least that many elements, which can reduce reallocations; the length is still zero until you push items."),
|
| 280 |
+
("std::borrow::Cow", "Look up std::borrow::Cow in the docs tool.", "Explain owned versus borrowed behavior briefly.", "Use one tool call, then summarize clone-on-write semantics.", "std::borrow::Cow", "A clone-on-write smart pointer that can hold borrowed or owned data and clones into owned form only when needed.", "Explain that it avoids allocation until mutation or ownership is required.", "Cow lets APIs accept either borrowed or owned data without forcing an allocation up front; it only clones into owned data if mutation or ownership is needed."),
|
| 281 |
+
("AsRef", "Look up AsRef in the docs tool.", "Explain the reference-conversion role briefly.", "Use one tool call, then summarize the cheap conversion behavior.", "AsRef", "A trait for cheap reference-to-reference conversion via as_ref(&self) -> &T.", "Describe it as a lightweight borrowed conversion trait.", "AsRef is a trait for cheap borrowed conversion: it lets a value be viewed as a reference to another type, which is useful for accepting flexible input types without allocating."),
|
| 282 |
+
("Box::pin", "Look up Box::pin in the docs tool.", "Explain why pinning matters briefly.", "Use one tool call, then summarize the heap pinning behavior.", "Box::pin", "Allocates a value on the heap and pins it so it will not move.", "Mention that pinning is useful when movement would break invariants.", "Box::pin places a value on the heap and pins it so it can no longer move, which is useful for async or self-referential patterns that rely on stable addresses."),
|
| 283 |
+
("std::mem::drop", "Look up std::mem::drop in the docs tool.", "Explain what happens to the value briefly.", "Use one tool call, then summarize the ownership-taking behavior.", "std::mem::drop", "Takes ownership of a value and runs its destructor immediately.", "State that drop consumes the value and runs Drop now rather than later.", "std::mem::drop takes ownership of a value and runs its destructor immediately, so the value is consumed and cannot be used afterward."),
|
| 284 |
+
("BTreeMap", "Look up BTreeMap in the docs tool.", "Explain when it is preferable briefly.", "Use one tool call, then summarize the ordering tradeoff.", "BTreeMap", "Keeps keys ordered and is useful for range queries and deterministic iteration.", "Tie the recommendation to key ordering and range access.", "Choose BTreeMap when key ordering or range queries matter more than average-case hash lookup speed, since it maintains keys in sorted order."),
|
| 285 |
+
("tokio::sync::Mutex", "Look up tokio::sync::Mutex in the docs tool.", "Explain the async-specific caveat briefly.", "Use one tool call, then summarize the executor-friendly behavior.", "tokio::sync::Mutex", "An async-aware mutex whose lock is acquired with .await; avoid holding the guard across unrelated awaits for long periods.", "Highlight that it coordinates async tasks without blocking the thread.", "tokio::sync::Mutex is an async-aware mutex for coordinating mutable access in async code; it avoids blocking the thread, but you should still keep lock guards short-lived."),
|
| 286 |
+
]
|
| 287 |
+
for symbol, todo1, todo2, rationale, arg_symbol, result_data, think, response in rust_doc_items:
|
| 288 |
+
traces.append(
|
| 289 |
+
single_tool_trace(
|
| 290 |
+
"You are a Rust documentation assistant who answers briefly and precisely.",
|
| 291 |
+
rustdoc,
|
| 292 |
+
f"In Rust, what does {symbol} do? Use the docs tool." if symbol not in {"BTreeMap", "AsRef", "tokio::sync::Mutex"} else (
|
| 293 |
+
"When would you choose BTreeMap over HashMap in Rust? Use the docs tool." if symbol == "BTreeMap" else
|
| 294 |
+
"What does the trait AsRef do in Rust? Use the docs tool." if symbol == "AsRef" else
|
| 295 |
+
"What should I remember about tokio::sync::Mutex in async Rust? Use the docs tool."
|
| 296 |
+
),
|
| 297 |
+
[todo1, todo2],
|
| 298 |
+
rationale,
|
| 299 |
+
"rustdoc_lookup",
|
| 300 |
+
[("symbol", arg_symbol)],
|
| 301 |
+
"res1",
|
| 302 |
+
result_data,
|
| 303 |
+
think,
|
| 304 |
+
"note1",
|
| 305 |
+
response,
|
| 306 |
+
)
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
rust_debug_items = [
|
| 310 |
+
("My Rust crate fails to compile after I changed a function to use `?` on a `Result`. I’m not sure what trait or type I need to add to make error conversion work.",
|
| 311 |
+
"cargo check: error[E0277]: `?` couldn't convert the error to `MyError`; the trait `From<std::io::Error>` is not implemented for `MyError`.",
|
| 312 |
+
"FromResidual",
|
| 313 |
+
"For Result, `?` requires a conversion path from the source error into the function's return error type, commonly via `From<E>`.",
|
| 314 |
+
"The compiler is telling you that `?` needs to turn `std::io::Error` into `MyError`, but no conversion exists. Fix it by implementing `From<std::io::Error> for MyError`, changing the function’s return type to one that already accepts that error, or wrapping the call with an explicit map_err."),
|
| 315 |
+
("My Rust project fails to compile after I changed a function to return an iterator. The error says it cannot return a value referencing a local variable.",
|
| 316 |
+
"cargo check: error[E0515]: cannot return value referencing local variable `v`; use `.into_iter()` to return an iterator that owns its items, or move the owned value out.",
|
| 317 |
+
"impl Trait return lifetime iterator",
|
| 318 |
+
"This usually means the iterator borrows from a local value that will be dropped before the caller can use it.",
|
| 319 |
+
"You are probably returning an iterator that borrows from a local collection, so the borrow would outlive the collection. A clean fix is to return an owning iterator (for example via `into_iter()`), return the owned collection instead, or make the iterator borrow from data owned by the caller instead of a local temporary."),
|
| 320 |
+
("My Rust crate started failing tests with a borrow checker error around iterators. Tests are flaky locally. Can you quickly triage and suggest the most likely fix direction?",
|
| 321 |
+
"error[E0502]: cannot borrow `items` as mutable because it is also borrowed as immutable; the loop iterates items.iter() and then calls items.push(...).",
|
| 322 |
+
"Iterator::iter",
|
| 323 |
+
"The compiler output already points to mutating a collection while iterating it immutably.",
|
| 324 |
+
"The likely issue is mutating the same collection while holding an immutable iterator over it. Fix direction: collect the new values separately, iterate over a cloned snapshot, or restructure the loop so mutation happens after iteration instead of inside it."),
|
| 325 |
+
("My tests hang in CI and I suspect a deadlock around Mutex + async. Clippy isn’t available here—what should I check and how can I narrow it down quickly?",
|
| 326 |
+
"Error: cargo clippy unavailable on this toolchain",
|
| 327 |
+
"tokio::sync::Mutex",
|
| 328 |
+
"Use one docs fallback and then give concrete checks about locks held across await points.",
|
| 329 |
+
"First check whether any task holds a mutex guard across an `.await`, because that is a common async deadlock pattern. Then look for inconsistent lock ordering and blocking calls inside critical sections; if you can, add logging around lock acquisition/release to find the task that never lets go."),
|
| 330 |
+
("My Rust helper won’t compile after I tried to store different iterator types in one Vec. What’s going on and what’s a clean fix?",
|
| 331 |
+
"cargo check: error[E0308]: expected `Map<_, _>`, found `Filter<_, _>` when pushing into `Vec`; each iterator adapter has a distinct concrete type.",
|
| 332 |
+
"dyn Iterator",
|
| 333 |
+
"Explain that iterator adapters have different concrete types even if they share the same trait.",
|
| 334 |
+
"You are trying to store different concrete iterator adapter types in one Vec, but each adapter has its own distinct type. A clean fix is to box them as `Box<dyn Iterator<Item = T>>`, use an enum wrapper if the set is fixed, or collect to concrete data before storing."),
|
| 335 |
+
("My Rust unit test fails after sorting a Vec<f32>; it expects stable ordering when values are equal or NaN. What’s going on and what’s a clean fix?",
|
| 336 |
+
"test panic: comparator uses `a.partial_cmp(b).unwrap()`; Expected NaNs at end and stable order for equal values.",
|
| 337 |
+
"slice::sort_by / f32::total_cmp",
|
| 338 |
+
"Point out that NaN breaks partial_cmp-based assumptions and total ordering must be explicit.",
|
| 339 |
+
"The problem is that `f32::partial_cmp` returns None for NaN, so unwrapping it is invalid and the comparator is not a total order. Use `total_cmp` for deterministic float ordering, and if equal-value stability matters, use a stable sort or add a tie-breaker key."),
|
| 340 |
+
("My Rust crate won’t compile after I tried to store a closure capturing a local reference in a struct for later use. Explain what’s wrong and how to fix it.",
|
| 341 |
+
"cargo check: error[E0597]: `local` does not live long enough; closure may outlive the current function, but it borrows `local`.",
|
| 342 |
+
"FnOnce + 'static",
|
| 343 |
+
"Explain that the closure outlives the borrowed local and must own its captures or be tied to a shorter lifetime.",
|
| 344 |
+
"The closure is trying to outlive a borrowed local reference, so the compiler rejects it. Fix it by moving owned data into the closure, parameterizing the struct with an explicit lifetime if the borrow truly must be external, or redesigning the API so the closure does not escape the scope of the borrowed value."),
|
| 345 |
+
("My Rust function returns a reference to a local String and now the compiler complains. What is it objecting to and what is the right fix?",
|
| 346 |
+
"cargo check: error[E0515]: cannot return reference to local variable `s`.",
|
| 347 |
+
"lifetime elision",
|
| 348 |
+
"Keep the explanation focused on returning a borrow to data that will be dropped at function exit.",
|
| 349 |
+
"The compiler is objecting because the returned reference would point to a local value that is destroyed when the function returns. The fix is to return an owned `String`, borrow from caller-owned data instead, or redesign the API so the referenced data lives long enough."),
|
| 350 |
+
("Clippy is failing in CI with an error about an unknown lint name; the clippy tool might be unavailable. Give concise guidance.",
|
| 351 |
+
"Error: cargo clippy output unavailable",
|
| 352 |
+
"unknown_lints",
|
| 353 |
+
"Use one docs fallback and explain the common version-mismatch cause.",
|
| 354 |
+
"An unknown lint name usually means a Clippy/Rust version mismatch or a renamed/removed lint. Check the toolchain version used in CI, update or remove the stale lint name, and only use `allow(unknown_lints)` as a temporary unblock while you align versions."),
|
| 355 |
+
("My Rust CLI parses args with clap and fails to compile after I added a `Vec<&str>` field to the config struct. Diagnose the likely issue and give a concise fix.",
|
| 356 |
+
"cargo check: error[E0106]: missing lifetime specifier; error[E0521]: borrowed data escapes outside of function when returning `Vec<&str>` from clap parsing.",
|
| 357 |
+
"clap derive String vs &str",
|
| 358 |
+
"Explain that clap-parsed values should generally be stored as owned Strings rather than borrowed &str fields.",
|
| 359 |
+
"The likely issue is that your config struct is trying to store borrowed strings from parsing, but those borrows do not outlive the parsing scope. Use `Vec<String>` (or another owned type like `PathBuf`) in the config instead of `Vec<&str>` unless you are explicitly threading lifetimes through the whole type."),
|
| 360 |
+
]
|
| 361 |
+
for i, (user, check_result, doc_symbol, think, response) in enumerate(rust_debug_items):
|
| 362 |
+
traces.append(
|
| 363 |
+
multi_tool_trace(
|
| 364 |
+
"You are a Rust debugging assistant who diagnoses compiler and tool output concisely.",
|
| 365 |
+
cargo,
|
| 366 |
+
user,
|
| 367 |
+
[
|
| 368 |
+
"Get the primary diagnostic or tool output for the failure.",
|
| 369 |
+
"Use one targeted docs lookup if it sharpens the fix.",
|
| 370 |
+
"Give a concise diagnosis and repair direction.",
|
| 371 |
+
],
|
| 372 |
+
"Use one concrete tool result, optionally one supporting lookup, then answer without extra loops.",
|
| 373 |
+
"cargo_check" if "compile" in user or "compiler" in user or "Clippy" not in user and "tests hang" not in user and "unit test fails" not in user else ("cargo_clippy" if "Clippy" in user or "clippy" in user else "cargo_test"),
|
| 374 |
+
[("crate_path", "./")] if "filter" not in check_result else [("crate_path", "./"), ("filter", "sort_floats")],
|
| 375 |
+
"step1",
|
| 376 |
+
check_result,
|
| 377 |
+
think,
|
| 378 |
+
"note1",
|
| 379 |
+
"rustdoc_lookup",
|
| 380 |
+
[("symbol", doc_symbol)],
|
| 381 |
+
"step2",
|
| 382 |
+
f"rustdoc: {doc_symbol} guidance relevant to this failure.",
|
| 383 |
+
"The tool outputs are enough to anchor a short fix direction; stop after the answer.",
|
| 384 |
+
"note2",
|
| 385 |
+
response,
|
| 386 |
+
)
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
ci_items = [
|
| 390 |
+
("Our nightly integration tests started timing out in the container startup phase. What should I check first?",
|
| 391 |
+
"Error: CI log service unavailable",
|
| 392 |
+
"test-runner",
|
| 393 |
+
"Cached incident note: timeouts commonly occur when the container never becomes ready due to a failing healthcheck or slow image pull from the registry.",
|
| 394 |
+
"Check container readiness first: image pull latency/auth, the startup healthcheck itself, and any recent CPU or memory limit changes that would delay boot. This recommendation is based on the cached incident note because live logs were unavailable."),
|
| 395 |
+
("Our deploy pipeline started failing at the unit-tests stage after a dependency bump. What should I check first?",
|
| 396 |
+
"Run: 18422; FAIL: Cannot find module `left-pad` in test/bootstrap.js after dependency bump.",
|
| 397 |
+
"Cannot find module left-pad",
|
| 398 |
+
"1 match: repo/test/bootstrap.js imports `left-pad` directly.",
|
| 399 |
+
"Start with the first failing import in the unit-test logs: the dependency bump likely changed a package name or entrypoint. Check the import in test/bootstrap.js, verify the lockfile changed consistently, and pin or revert the bump if you need a quick unblock."),
|
| 400 |
+
("Our integration tests intermittently time out only on main branch runs. What should we look at first?",
|
| 401 |
+
"Error: CI log service unavailable",
|
| 402 |
+
"ci",
|
| 403 |
+
"Cached incident note: main-branch timeouts frequently traced to runner pool saturation and occasional DNS failures during dependency setup.",
|
| 404 |
+
"First check whether main runs are landing on more saturated runners or a different runner class, then verify DNS/network reliability during dependency setup. The main-only pattern makes infrastructure skew more likely than a deterministic test bug."),
|
| 405 |
+
("Our deploys to staging fail intermittently with a permission denied error. Where should we look first?",
|
| 406 |
+
"Staging deploy job failed while fetching secret staging/DB_PASSWORD; runner role missing `secrets.read`.",
|
| 407 |
+
"staging-deploy",
|
| 408 |
+
"Cached incident note: similar failures came from a policy rollout that removed secret read access in one namespace.",
|
| 409 |
+
"Look first at the deploy runner’s IAM or service-account permissions for the secrets backend. The logs already point to denied secret access, so confirm the runner role and namespace policy before investigating app code."),
|
| 410 |
+
("Our nightly pipeline started failing after a merge, but reruns usually pass. What should I check first?",
|
| 411 |
+
"Error: CI log service returned 503",
|
| 412 |
+
"pipeline",
|
| 413 |
+
"Cached incident note: flaky nightly failures that pass on rerun are frequently caused by transient dependency resolution or external registry hiccups.",
|
| 414 |
+
"Check whether the failure happens during dependency or artifact fetches and whether versions are pinned. If reruns usually pass, transient external fetches or unpinned dependencies are a stronger first suspect than deterministic code regressions."),
|
| 415 |
+
]
|
| 416 |
+
for user, log_result, service, cache_result, response in ci_items:
|
| 417 |
+
traces.append(
|
| 418 |
+
multi_tool_trace(
|
| 419 |
+
"You are a debugging assistant who keeps incident analysis concise and resilient to tool failure.",
|
| 420 |
+
ci_tools,
|
| 421 |
+
user,
|
| 422 |
+
[
|
| 423 |
+
"Pull the most relevant recent logs or failure output.",
|
| 424 |
+
"Use one fallback source only if the primary source fails or is insufficient.",
|
| 425 |
+
"Provide the first concrete investigation angle.",
|
| 426 |
+
],
|
| 427 |
+
"Start with direct evidence, use one fallback at most, then answer succinctly.",
|
| 428 |
+
"get_ci_logs",
|
| 429 |
+
[("run_id", "main-failing-run-18422" if "main" in user else "nightly-failing-run-18422")],
|
| 430 |
+
"logs1",
|
| 431 |
+
log_result,
|
| 432 |
+
"If live logs fail or are too thin, use one fallback source to avoid over-searching.",
|
| 433 |
+
"note_logs",
|
| 434 |
+
"fetch_cached_incident" if "Cannot find module" not in log_result else "code_search",
|
| 435 |
+
[("service", service)] if "Cannot find module" not in log_result else [("query", "left-pad")],
|
| 436 |
+
"aux1",
|
| 437 |
+
cache_result,
|
| 438 |
+
"Use the second tool result to sharpen one focused next step, then stop.",
|
| 439 |
+
"note_aux",
|
| 440 |
+
response,
|
| 441 |
+
)
|
| 442 |
+
)
|
| 443 |
+
|
| 444 |
+
misc = [
|
| 445 |
+
single_tool_trace("You are a data access assistant who uses SQL and answers briefly.", sql_tools,
|
| 446 |
+
"How many paid subscriptions were canceled yesterday?",
|
| 447 |
+
["Query the cancellation count.", "Answer with the count briefly."],
|
| 448 |
+
"Use one SQL query, then respond with the returned count.",
|
| 449 |
+
"run_sql", [("query", "SELECT COUNT(*) AS canceled_paid_subscriptions_yesterday FROM subscriptions WHERE status = 'canceled' AND plan_type = 'paid' AND canceled_at >= CURRENT_DATE - INTERVAL '1 day' AND canceled_at < CURRENT_DATE;")],
|
| 450 |
+
"res1", "Query result: canceled_paid_subscriptions_yesterday = 42.",
|
| 451 |
+
"The SQL result already contains the exact number needed for the answer.", "note1",
|
| 452 |
+
"There were 42 paid subscriptions canceled yesterday."),
|
| 453 |
+
single_tool_trace("You are a calculation assistant who returns precise numeric answers with a short explanation.", [tool("calculator", "Evaluates a math expression.", param("expression", "string", "Expression to evaluate"))],
|
| 454 |
+
"A jacket was $120, now it’s $90. What percent discount is that? Use the calculator.",
|
| 455 |
+
["Compute the percent discount.", "Answer with the percentage briefly."],
|
| 456 |
+
"Use the calculator once, then state the computed percentage.",
|
| 457 |
+
"calculator", [("expression", "((120-90)/120)*100")], "res1", "((120-90)/120)*100 = 25",
|
| 458 |
+
"Convert the calculator result into a concise percent statement.", "note1",
|
| 459 |
+
"The discount is 25%."),
|
| 460 |
+
multi_tool_trace("You are a helpful assistant specialized in symbolic mathematics. Provide clear, concise solutions.", math_tools,
|
| 461 |
+
"Compute the indefinite integral of (x^3 - 2*x)/(x^2 + 1). Verify it by differentiation and keep the answer concise.",
|
| 462 |
+
["Compute an antiderivative.", "Verify it by differentiation.", "State the final answer briefly."],
|
| 463 |
+
"Use one symbolic solve step, one derivative check, then stop.",
|
| 464 |
+
"solve_symbolic", [("expression", "(x^3 - 2*x)/(x^2 + 1)"), ("operation", "integrate"), ("variable", "x")], "int1",
|
| 465 |
+
"Computed antiderivative: (x^2 - 3*ln(x^2 + 1))/2 + C",
|
| 466 |
+
"The antiderivative is already compact; verify it directly rather than adding extra steps.", "note1",
|
| 467 |
+
"derivative_check", [("candidate_antiderivative", "(x^2 - 3*ln(x^2 + 1))/2"), ("target_expression", "(x^3 - 2*x)/(x^2 + 1)"), ("variable", "x")], "chk1",
|
| 468 |
+
"Derivative matches the target exactly.",
|
| 469 |
+
"The derivative check confirms correctness, so the final answer can stay short.", "note2",
|
| 470 |
+
"Antiderivative: (x^2 - 3 ln(x^2 + 1))/2 + C. The derivative check matches the integrand exactly."),
|
| 471 |
+
single_tool_trace("You are a document assistant who reads a file and returns a short, concrete summary.", file_tools,
|
| 472 |
+
"Open /docs/q3_launch_postmortem.md and summarize the main takeaways and action items.",
|
| 473 |
+
["Load the requested document excerpt.", "Summarize the main takeaways and action items."],
|
| 474 |
+
"Use the file tool once, then condense the excerpt into a short summary.",
|
| 475 |
+
"load_file", [("path", "/docs/q3_launch_postmortem.md")], "res1",
|
| 476 |
+
"Excerpt: Launch slipped 2 weeks due to late scope changes and unclear ownership. Incident detection lagged because dashboards lacked error-rate alerts. Action items: scope freeze, one DRI per workstream, pre-launch load testing, expanded dashboards and an on-call runbook.",
|
| 477 |
+
"Extract the delay cause, monitoring gap, and concrete action items into one tight summary.", "note1",
|
| 478 |
+
"Main takeaways: late scope changes and unclear ownership delayed the launch, and weak alerting slowed incident detection. Action items: add scope freeze/change control, assign one DRI per workstream, run pre-launch load tests, and strengthen dashboards plus the on-call runbook."),
|
| 479 |
+
multi_tool_trace("You are a planning assistant that helps product teams build realistic launch plans and concise schedules.", plan_tools,
|
| 480 |
+
"We need a 3-week rollout plan for an in-app onboarding checklist update. Pull major tasks, confirm the team can staff it, and keep it concise.",
|
| 481 |
+
["Check team availability for the 3-week window.", "Generate a baseline work breakdown.", "Provide a concise schedule recommendation."],
|
| 482 |
+
"Get staffing first, then a minimal work breakdown, then summarize feasibility.",
|
| 483 |
+
"get_availability", [("team_list", "ava,ben,chen,dina"), ("start_date", "2026-07-06"), ("end_date", "2026-07-26")], "avail1",
|
| 484 |
+
"Availability: ava 60%, ben 40%, chen 70%, dina 50% for the 3-week window.",
|
| 485 |
+
"Availability looks workable; now get a minimal breakdown sized to the short timeline.", "note1",
|
| 486 |
+
"create_project_plan", [("project_name", "in-app onboarding checklist update"), ("objectives", "ship updated checklist copy, triggers, analytics, and QA"), ("timeline_weeks", "3")], "plan1",
|
| 487 |
+
"Plan ID plan_onb_v1: requirements and copy, trigger logic, UI updates, analytics events, QA and rollout.",
|
| 488 |
+
"With staffing and tasks in hand, give a simple sequencing recommendation instead of adding more tool steps.", "note2",
|
| 489 |
+
"The team can likely cover this in 3 weeks if work starts with requirements/copy, then trigger logic and UI in parallel, followed by analytics wiring and a short QA/rollout window."),
|
| 490 |
+
multi_tool_trace("You are a Git assistant who gives compact, practical guidance.", git_tools,
|
| 491 |
+
"My PR branch won't push because it says non-fast-forward. I don't want to lose my local commits. What should I do?",
|
| 492 |
+
["Inspect repo state to confirm divergence.", "Inspect recent history to understand local vs remote commits.", "Provide a safe integration sequence that preserves local work."],
|
| 493 |
+
"Check branch state, check recent commits, then recommend a safe rebase-or-merge path.",
|
| 494 |
+
"git_status", [("repo_path", "./")], "st1",
|
| 495 |
+
"On branch feature/pr-42. Your branch and origin/feature/pr-42 have diverged, and have 3 and 2 different commits each. Working tree clean.",
|
| 496 |
+
"The branch has diverged, so check recent local and remote commits before recommending the next command.", "note1",
|
| 497 |
+
"git_log", [("repo_path", "./"), ("limit", "8")], "log1",
|
| 498 |
+
"local HEAD: abc1234 Add validation for empty inputs; bcd2345 Refactor request parsing. origin/feature/pr-42: def4567 Fix CI by pinning action versions; efg5678 Adjust lint config.",
|
| 499 |
+
"With divergence confirmed, recommend fetch plus rebase as the safest default when local commits must be preserved.", "note2",
|
| 500 |
+
"Fetch the remote branch, then rebase your local commits on top of it so you keep your work while integrating the remote changes. If conflicts appear, resolve them commit by commit, run tests, then push the rebased branch (usually with --force-with-lease)."),
|
| 501 |
+
]
|
| 502 |
+
traces.extend(misc)
|
| 503 |
+
|
| 504 |
+
traces.extend([
|
| 505 |
+
no_tool_trace("You are a Rust language assistant who gives concise ownership explanations.",
|
| 506 |
+
"Why does `collect::<Vec<_>>()` sometimes fix type inference errors in Rust?",
|
| 507 |
+
"Explain why adding a concrete collection type can resolve inference ambiguity.",
|
| 508 |
+
"Connect the fix to the compiler needing a concrete destination type.",
|
| 509 |
+
"State that collect needs to know what collection to build, and explicit type information removes the ambiguity.",
|
| 510 |
+
"Adding `collect::<Vec<_>>()` gives the compiler a concrete target collection type, which resolves ambiguity when it cannot infer what `collect` should produce from context alone.",
|
| 511 |
+
"note_collect_vec"),
|
| 512 |
+
no_tool_trace("You are a Rust API design assistant who answers briefly.",
|
| 513 |
+
"Why is `String` usually a better struct field type than `&str` in application config types?",
|
| 514 |
+
"Explain why owned strings are usually safer in config structs.",
|
| 515 |
+
"Tie the answer to lifetime simplicity and ownership boundaries.",
|
| 516 |
+
"Keep it focused on config values often needing to outlive the parsing context.",
|
| 517 |
+
"String is usually better because config structs often need to own their data after parsing, serialization, or movement across layers. Using `&str` pushes lifetimes through the whole type and is only worth it when you clearly have long-lived backing storage.",
|
| 518 |
+
"note_string_field"),
|
| 519 |
+
single_tool_trace("You are a Rust documentation assistant who answers briefly and precisely.", rustdoc,
|
| 520 |
+
"In Rust, what does `Iterator::collect` do? Use the docs tool.",
|
| 521 |
+
["Look up Iterator::collect in the docs tool.", "Explain it briefly."],
|
| 522 |
+
"Use the docs tool once, then summarize the behavior and type requirement.",
|
| 523 |
+
"rustdoc_lookup", [("symbol", "Iterator::collect")], "res1",
|
| 524 |
+
"Transforms an iterator into a collection or other type that implements FromIterator.",
|
| 525 |
+
"State that collect consumes the iterator and needs a destination type implementing FromIterator.", "note1",
|
| 526 |
+
"Iterator::collect consumes an iterator and builds a target type from it, as long as that target implements FromIterator."),
|
| 527 |
+
single_tool_trace("You are a Rust documentation assistant who answers briefly and precisely.", rustdoc,
|
| 528 |
+
"What does `HashMap::entry` help with in Rust? Use the docs tool.",
|
| 529 |
+
["Look up HashMap::entry in the docs tool.", "Explain its main use briefly."],
|
| 530 |
+
"Use the docs tool once, then summarize the lookup-or-insert pattern.",
|
| 531 |
+
"rustdoc_lookup", [("symbol", "HashMap::entry")], "res1",
|
| 532 |
+
"Provides in-place manipulation of a value in the map for a given key, including insert-if-missing patterns.",
|
| 533 |
+
"Describe entry as the API for update-or-insert without double lookup.", "note1",
|
| 534 |
+
"HashMap::entry lets you inspect, insert, or update a key in one pass, which is especially useful for counters and insert-if-missing logic."),
|
| 535 |
+
single_tool_trace("You are a data access assistant who uses SQL and answers briefly.", sql_tools,
|
| 536 |
+
"What percentage of new signups in the last 30 days came from organic search?",
|
| 537 |
+
["Query total signups and organic-search signups.", "Compute and report the percentage briefly."],
|
| 538 |
+
"Use one SQL query, then state the computed share.",
|
| 539 |
+
"run_sql", [("query", "SELECT COUNT(*) AS total_signups, SUM(CASE WHEN acquisition_channel = 'organic_search' THEN 1 ELSE 0 END) AS organic_signups FROM signups WHERE created_at >= (CURRENT_DATE - INTERVAL '30 days');")],
|
| 540 |
+
"res1", "Query result: total_signups=4120, organic_signups=1175.",
|
| 541 |
+
"Convert the totals into a percentage and present it briefly.", "note1",
|
| 542 |
+
"Organic search accounts for 28.5% of new signups over the last 30 days."),
|
| 543 |
+
single_tool_trace("You are a calculation assistant who returns precise numeric answers with a short explanation.", [tool("calculator", "Evaluates a math expression.", param("expression", "string", "Expression to evaluate"))],
|
| 544 |
+
"Revenue grew from $420k to $693k. What is the percentage increase? Use the calculator.",
|
| 545 |
+
["Compute the percentage increase.", "Report the increase briefly."],
|
| 546 |
+
"Use the calculator once, then translate the result into a concise percentage statement.",
|
| 547 |
+
"calculator", [("expression", "((693-420)/420)*100")], "res1", "((693-420)/420)*100 = 65.00",
|
| 548 |
+
"State the increase directly from the calculator output without extra filler.", "note1",
|
| 549 |
+
"The revenue increase is 65.00%."),
|
| 550 |
+
multi_tool_trace("You are a helpful assistant specialized in symbolic mathematics. Provide clear, concise solutions.", math_tools,
|
| 551 |
+
"Differentiate x^4 * ln(x), then verify the derivative by a second tool step and keep the answer concise.",
|
| 552 |
+
["Differentiate the expression.", "Verify the derivative by a second tool step.", "State the final derivative briefly."],
|
| 553 |
+
"Use one differentiation step, one verification step, then stop.",
|
| 554 |
+
"solve_symbolic", [("expression", "x^4 * ln(x)"), ("operation", "differentiate"), ("variable", "x")], "d1",
|
| 555 |
+
"Computed derivative: 4*x^3*ln(x) + x^3",
|
| 556 |
+
"The derivative result is already simple; verify it rather than adding another transform.", "note1",
|
| 557 |
+
"derivative_check", [("candidate_antiderivative", "(x^4*ln(x))"), ("target_expression", "4*x^3*ln(x) + x^3"), ("variable", "x")], "chk1",
|
| 558 |
+
"Differentiating x^4*ln(x) yields 4*x^3*ln(x) + x^3.",
|
| 559 |
+
"The verification matches, so the final answer can just state the derivative cleanly.", "note2",
|
| 560 |
+
"The derivative is 4x^3 ln(x) + x^3."),
|
| 561 |
+
single_tool_trace("You are a document assistant who reads a file and returns a short, concrete summary.", file_tools,
|
| 562 |
+
"Open /docs/security_audit_apr.md and summarize the top three findings.",
|
| 563 |
+
["Load the requested document excerpt.", "Summarize the top findings briefly."],
|
| 564 |
+
"Use the file tool once, then condense the excerpt into a short findings summary.",
|
| 565 |
+
"load_file", [("path", "/docs/security_audit_apr.md")], "res1",
|
| 566 |
+
"Excerpt: incomplete MFA enforcement for legacy admin accounts, critical dependencies missing recent security patches, and gaps in centralized logging/alerting that hinder incident response.",
|
| 567 |
+
"Extract the three concrete findings directly and keep the wording brief.", "note1",
|
| 568 |
+
"Top findings: MFA is incomplete for legacy admin accounts, critical dependencies are behind on security patches, and centralized logging/alerting is too weak for reliable incident response."),
|
| 569 |
+
multi_tool_trace("You are a planning assistant that helps product teams build realistic launch plans and concise schedules.", plan_tools,
|
| 570 |
+
"We need a 4-week launch plan for a billing export CSV improvement. Check team availability, generate the task breakdown, and keep the final recommendation concise.",
|
| 571 |
+
["Check team availability for the 4-week window.", "Generate the task breakdown.", "Provide a concise schedule recommendation."],
|
| 572 |
+
"Get staffing first, then a baseline task breakdown, then stop with a short recommendation.",
|
| 573 |
+
"get_availability", [("team_list", "maya,liam,noor,oscar"), ("start_date", "2026-08-04"), ("end_date", "2026-09-01")], "avail1",
|
| 574 |
+
"Availability: maya 70%, liam 50%, noor 80%, oscar 40% for the 4-week window.",
|
| 575 |
+
"Availability is enough to scope the next planning step; now get a compact work breakdown.", "note1",
|
| 576 |
+
"create_project_plan", [("project_name", "billing export CSV improvement"), ("objectives", "fix column consistency, header naming, duplicate handling, and rollout docs"), ("timeline_weeks", "4")], "plan1",
|
| 577 |
+
"Plan ID plan_csv_v1: requirements and field audit, export generator changes, duplicate handling, QA with sample customers, rollout docs.",
|
| 578 |
+
"With staffing and tasks available, the final answer should just recommend a simple sequence.", "note2",
|
| 579 |
+
"The team can likely deliver this in 4 weeks by starting with requirements and field audit, then export-generator changes, followed by duplicate handling, QA, and a short rollout-docs finish.")
|
| 580 |
+
])
|
| 581 |
+
|
| 582 |
+
assert len(traces) == 50, len(traces)
|
| 583 |
+
return traces
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
def main() -> int:
|
| 587 |
+
traces = records()
|
| 588 |
+
bad: list[tuple[int, list[str]]] = []
|
| 589 |
+
with OUT.open("w") as f:
|
| 590 |
+
for i, trace in enumerate(traces, start=1):
|
| 591 |
+
res = validate_trace(trace)
|
| 592 |
+
if not res.valid:
|
| 593 |
+
bad.append((i, res.errors))
|
| 594 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 595 |
+
print(json.dumps({"count": len(traces), "output": str(OUT), "invalid": bad}, indent=2))
|
| 596 |
+
return 0 if not bad else 1
|
| 597 |
+
|
| 598 |
+
|
| 599 |
+
if __name__ == "__main__":
|
| 600 |
+
raise SystemExit(main())
|
build_gold_rust_tooluse.py
ADDED
|
@@ -0,0 +1,1076 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""SFT extension: traces for the full RL Rust toolset.
|
| 3 |
+
|
| 4 |
+
Adds gold examples of:
|
| 5 |
+
read_file → response (inspect a file)
|
| 6 |
+
read_file → apply_patch → cargo_test → response (lib bug fix)
|
| 7 |
+
read_file → apply_patch → cargo_run → response (bin bug fix)
|
| 8 |
+
cargo_check / cargo_build / cargo_test / cargo_run / rustc — single-tool
|
| 9 |
+
|
| 10 |
+
The output appends to gold_glyph_3000.jsonl so the next SFT run sees the
|
| 11 |
+
correct schema for tools the original SFT pool didn't cover (`apply_patch`,
|
| 12 |
+
`read_file`, `cargo_build`, `cargo_run`, `rustc`). Format follows the
|
| 13 |
+
build_gold50 helpers strictly so docs/glyph.md invariants hold.
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 22 |
+
if str(ROOT) not in sys.path:
|
| 23 |
+
sys.path.insert(0, str(ROOT))
|
| 24 |
+
|
| 25 |
+
import build_gold50 as g # noqa: E402
|
| 26 |
+
from core.validator import validate_trace # noqa: E402
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# ---------------------------------------------------------------------------
|
| 30 |
+
# Tool defs — must match rl/rust/tools.py exactly so the model learns the
|
| 31 |
+
# right schema (file_path/find/replace for apply_patch, not source_file/source).
|
| 32 |
+
# ---------------------------------------------------------------------------
|
| 33 |
+
|
| 34 |
+
def rust_dev_tools():
|
| 35 |
+
return [
|
| 36 |
+
g.tool("read_file",
|
| 37 |
+
"Reads a file from disk and returns its contents.",
|
| 38 |
+
g.param("file_path", "string", "Path to the file to read")),
|
| 39 |
+
g.tool("apply_patch",
|
| 40 |
+
"Applies a textual find/replace edit to a single file. 'find' must occur exactly once.",
|
| 41 |
+
g.param("file_path", "string", "Path to the file to edit"),
|
| 42 |
+
g.param("find", "string", "Exact text snippet to locate"),
|
| 43 |
+
g.param("replace", "string", "Replacement text")),
|
| 44 |
+
g.tool("cargo_check",
|
| 45 |
+
"Runs cargo check to verify code compiles without producing a binary.",
|
| 46 |
+
g.param("project_path", "string", "Cargo project directory")),
|
| 47 |
+
g.tool("cargo_build",
|
| 48 |
+
"Compiles the Cargo project into binaries.",
|
| 49 |
+
g.param("project_path", "string", "Cargo project directory")),
|
| 50 |
+
g.tool("cargo_test",
|
| 51 |
+
"Runs the test suite for a Cargo project.",
|
| 52 |
+
g.param("project_path", "string", "Cargo project directory")),
|
| 53 |
+
g.tool("cargo_run",
|
| 54 |
+
"Builds and runs the binary of a Cargo project, returning its stdout.",
|
| 55 |
+
g.param("project_path", "string", "Cargo project directory")),
|
| 56 |
+
g.tool("rustc",
|
| 57 |
+
"Compiles a single Rust source file to an executable.",
|
| 58 |
+
g.param("source_file", "string", "Source file"),
|
| 59 |
+
g.param("output", "string", "Output binary path", required=False)),
|
| 60 |
+
]
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
SYSTEM = "You are a Rust engineering assistant. Use the available tools to inspect and verify code, then answer briefly."
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# ---------------------------------------------------------------------------
|
| 67 |
+
# Trace builders for multi-step workflows (3+ calls).
|
| 68 |
+
# Mirrors single_tool_trace / multi_tool_trace from build_gold50 but extends
|
| 69 |
+
# to 3 sequential calls (read → patch → verify).
|
| 70 |
+
# ---------------------------------------------------------------------------
|
| 71 |
+
|
| 72 |
+
def three_tool_trace(user, todos, rationale,
|
| 73 |
+
c1_tool, c1_args, c1_id, r1, t1, tag1,
|
| 74 |
+
c2_tool, c2_args, c2_id, r2, t2, tag2,
|
| 75 |
+
c3_tool, c3_args, c3_id, r3, t3, tag3,
|
| 76 |
+
response):
|
| 77 |
+
"""assistant → tool → assistant → tool → assistant → tool → assistant(response)"""
|
| 78 |
+
return g.join_trace(
|
| 79 |
+
g.system_seg(SYSTEM, rust_dev_tools()),
|
| 80 |
+
g.user_seg(user),
|
| 81 |
+
g.assistant_seg(g.plan_block(todos, rationale),
|
| 82 |
+
g.call_act(c1_tool, c1_args, c1_id, 1)),
|
| 83 |
+
g.result_seg(r1, c1_id),
|
| 84 |
+
g.assistant_seg(g.think_act([(t1, tag1, [c1_id])]),
|
| 85 |
+
g.call_act(c2_tool, c2_args, c2_id, 2)),
|
| 86 |
+
g.result_seg(r2, c2_id),
|
| 87 |
+
g.assistant_seg(g.think_act([(t2, tag2, [c1_id, c2_id])]),
|
| 88 |
+
g.call_act(c3_tool, c3_args, c3_id, 3)),
|
| 89 |
+
g.result_seg(r3, c3_id),
|
| 90 |
+
g.assistant_seg(g.think_act([(t3, tag3, [c2_id, c3_id])]),
|
| 91 |
+
g.response_block(response, [c1_id, c2_id, c3_id, tag3], 4)),
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ---------------------------------------------------------------------------
|
| 96 |
+
# Concrete bug-fix lib traces: read_file → apply_patch → cargo_test → respond.
|
| 97 |
+
# These mirror the rl/rust/prepare_cases.py BUGFIX_CASES so the SFT model
|
| 98 |
+
# sees the exact workflow the RL env expects.
|
| 99 |
+
# ---------------------------------------------------------------------------
|
| 100 |
+
|
| 101 |
+
LIB_BUGFIX_CASES = [
|
| 102 |
+
# (crate, buggy_lib_src, find, replace, fix_summary)
|
| 103 |
+
("addlib_bug",
|
| 104 |
+
"pub fn add(a: i32, b: i32) -> i32 { a - b }",
|
| 105 |
+
"a - b", "a + b",
|
| 106 |
+
"Subtraction was used where addition is required; replacing it makes the test pass."),
|
| 107 |
+
("mullib_bug",
|
| 108 |
+
"pub fn mul(a: i32, b: i32) -> i32 { a + b }",
|
| 109 |
+
"a + b", "a * b",
|
| 110 |
+
"Addition was used where multiplication is required; the corrected operator matches the test."),
|
| 111 |
+
("evenlib_bug",
|
| 112 |
+
"pub fn is_even(n: i32) -> bool { n % 2 == 1 }",
|
| 113 |
+
"n % 2 == 1", "n % 2 == 0",
|
| 114 |
+
"The remainder check was inverted; comparing against 0 returns the correct parity."),
|
| 115 |
+
("absnumlib_bug",
|
| 116 |
+
"pub fn abs_v(n: i32) -> i32 { n }",
|
| 117 |
+
"pub fn abs_v(n: i32) -> i32 { n }",
|
| 118 |
+
"pub fn abs_v(n: i32) -> i32 { n.abs() }",
|
| 119 |
+
"The function returned the input unchanged; applying .abs() yields the absolute value."),
|
| 120 |
+
("factlib_bug",
|
| 121 |
+
"pub fn fact(n: u32) -> u32 { (1..n).product::<u32>().max(1) }",
|
| 122 |
+
"1..n", "1..=n",
|
| 123 |
+
"The exclusive range skipped n; using an inclusive range gives the correct factorial."),
|
| 124 |
+
("revstrlib_bug",
|
| 125 |
+
"pub fn rev(s: &str) -> String { s.chars().collect() }",
|
| 126 |
+
"s.chars().collect()", "s.chars().rev().collect()",
|
| 127 |
+
"The chars iterator wasn't reversed; calling .rev() before collecting fixes the result."),
|
| 128 |
+
("maxlib_bug",
|
| 129 |
+
"pub fn max_of(s: &[i32]) -> i32 { *s.iter().min().unwrap_or(&0) }",
|
| 130 |
+
"s.iter().min()", "s.iter().max()",
|
| 131 |
+
"Selecting min instead of max; swapping the iterator method gives the expected value."),
|
| 132 |
+
("sumlib_bug",
|
| 133 |
+
"pub fn sum(s: &[i32]) -> i32 { s.iter().product() }",
|
| 134 |
+
"s.iter().product()", "s.iter().sum()",
|
| 135 |
+
"Iterator product was used where sum is required; switching makes the test pass."),
|
| 136 |
+
("fiblib_bug",
|
| 137 |
+
"pub fn fib(n: u32) -> u32 { match n { 0 => 1, 1 => 1, _ => fib(n-1) + fib(n-2) } }",
|
| 138 |
+
"0 => 1", "0 => 0",
|
| 139 |
+
"fib(0) was returning 1; correcting the base case to 0 matches the standard sequence."),
|
| 140 |
+
("palinlib_bug",
|
| 141 |
+
"pub fn pal(s: &str) -> bool { let r: String = s.chars().collect(); r == s }",
|
| 142 |
+
"s.chars().collect()", "s.chars().rev().collect()",
|
| 143 |
+
"The string wasn't reversed before the equality check; adding .rev() makes palindrome detection work."),
|
| 144 |
+
("vowelslib_bug",
|
| 145 |
+
"pub fn vowels(s: &str) -> usize { s.chars().filter(|c| \"bcdfg\".contains(*c)).count() }",
|
| 146 |
+
"\"bcdfg\"", "\"aeiouAEIOU\"",
|
| 147 |
+
"The filter set listed consonants; using the vowels set returns the correct count."),
|
| 148 |
+
("gcdlib_bug",
|
| 149 |
+
"pub fn gcd(a: u32, b: u32) -> u32 { if b == 0 { b } else { gcd(b, a % b) } }",
|
| 150 |
+
"if b == 0 { b }", "if b == 0 { a }",
|
| 151 |
+
"The base case returned 0 instead of a; correcting it makes the recursion terminate with the right value."),
|
| 152 |
+
# --- extended lib bug families (math, comparison, range, iterators, strings, control flow)
|
| 153 |
+
("sublib_bug",
|
| 154 |
+
"pub fn sub(a: i32, b: i32) -> i32 { a + b }",
|
| 155 |
+
"a + b", "a - b",
|
| 156 |
+
"Addition was used in place of subtraction; switching the operator restores the difference."),
|
| 157 |
+
("divlib_bug",
|
| 158 |
+
"pub fn div(a: i32, b: i32) -> i32 { a * b }",
|
| 159 |
+
"a * b", "a / b",
|
| 160 |
+
"Multiplication was used where integer division is required; the operator fix is enough."),
|
| 161 |
+
("modlib_bug",
|
| 162 |
+
"pub fn rem(a: i32, b: i32) -> i32 { a / b }",
|
| 163 |
+
"a / b", "a % b",
|
| 164 |
+
"Division was used where remainder is needed; switching to % matches the expected result."),
|
| 165 |
+
("powerlib_bug",
|
| 166 |
+
"pub fn cube(n: i64) -> i64 { n.pow(2) }",
|
| 167 |
+
"n.pow(2)", "n.pow(3)",
|
| 168 |
+
"The exponent was 2 instead of 3; raising to the third power matches the intended cube."),
|
| 169 |
+
("doublelib_bug",
|
| 170 |
+
"pub fn doubled(n: i32) -> i32 { n + n + 1 }",
|
| 171 |
+
"n + n + 1", "n + n",
|
| 172 |
+
"An off-by-one term was added; removing it yields the correct doubling."),
|
| 173 |
+
("halflib_bug",
|
| 174 |
+
"pub fn half(n: i32) -> i32 { n * 2 }",
|
| 175 |
+
"n * 2", "n / 2",
|
| 176 |
+
"Multiplication by 2 produced double rather than half; switching to division returns the correct value."),
|
| 177 |
+
("inclib_bug",
|
| 178 |
+
"pub fn inc(n: i32) -> i32 { n - 1 }",
|
| 179 |
+
"n - 1", "n + 1",
|
| 180 |
+
"Decrement was used where increment is required; flipping the operator fixes it."),
|
| 181 |
+
("avg2lib_bug",
|
| 182 |
+
"pub fn avg2(a: i32, b: i32) -> i32 { (a + b) * 2 }",
|
| 183 |
+
"(a + b) * 2", "(a + b) / 2",
|
| 184 |
+
"The sum was multiplied instead of halved; dividing by 2 produces the average."),
|
| 185 |
+
("negatelib_bug",
|
| 186 |
+
"pub fn negate(n: i32) -> i32 { n.abs() }",
|
| 187 |
+
"n.abs()", "-n",
|
| 188 |
+
"abs() was used where negation is required; replacing with the unary minus gives the correct sign."),
|
| 189 |
+
("squarelib_bug",
|
| 190 |
+
"pub fn square(n: i32) -> i32 { n + n }",
|
| 191 |
+
"n + n", "n * n",
|
| 192 |
+
"Doubling was used where squaring is required; multiplying n by itself returns the square."),
|
| 193 |
+
# comparison
|
| 194 |
+
("gtlib_bug",
|
| 195 |
+
"pub fn is_pos(n: i32) -> bool { n < 0 }",
|
| 196 |
+
"n < 0", "n > 0",
|
| 197 |
+
"The strict-less check returned positivity inverted; flipping to greater-than fixes it."),
|
| 198 |
+
("gelib_bug",
|
| 199 |
+
"pub fn at_least(n: i32, k: i32) -> bool { n > k }",
|
| 200 |
+
"n > k", "n >= k",
|
| 201 |
+
"The inclusive boundary case was missing; switching to >= covers equality too."),
|
| 202 |
+
("lelib_bug",
|
| 203 |
+
"pub fn at_most(n: i32, k: i32) -> bool { n < k }",
|
| 204 |
+
"n < k", "n <= k",
|
| 205 |
+
"Strict-less excluded equality; <= is the right inclusive bound."),
|
| 206 |
+
("eqlib_bug",
|
| 207 |
+
"pub fn same(a: i32, b: i32) -> bool { a != b }",
|
| 208 |
+
"a != b", "a == b",
|
| 209 |
+
"Inequality was returned where equality is required; switching the operator fixes the predicate."),
|
| 210 |
+
("nelib_bug",
|
| 211 |
+
"pub fn different(a: i32, b: i32) -> bool { a == b }",
|
| 212 |
+
"a == b", "a != b",
|
| 213 |
+
"Equality was returned where inequality is required; flipping the operator fixes the predicate."),
|
| 214 |
+
# ranges
|
| 215 |
+
("rangesumlib_bug",
|
| 216 |
+
"pub fn sum_to(n: i32) -> i32 { (1..n).sum() }",
|
| 217 |
+
"(1..n)", "(1..=n)",
|
| 218 |
+
"The exclusive range omitted n itself; using the inclusive form yields the correct sum."),
|
| 219 |
+
("rangeproductlib_bug",
|
| 220 |
+
"pub fn fact(n: u32) -> u32 { (1..n).product() }",
|
| 221 |
+
"(1..n)", "(1..=n)",
|
| 222 |
+
"Factorial requires multiplying up to and including n; switching to an inclusive range fixes it."),
|
| 223 |
+
("rangecountlib_bug",
|
| 224 |
+
"pub fn count_up(n: u32) -> u32 { (0..n).count() as u32 + 1 }",
|
| 225 |
+
".count() as u32 + 1", ".count() as u32",
|
| 226 |
+
"An extra +1 inflated the count; removing it matches the actual element count."),
|
| 227 |
+
("rangerevlib_bug",
|
| 228 |
+
"pub fn count_down(n: u32) -> Vec<u32> { (0..n).collect() }",
|
| 229 |
+
"(0..n).collect()", "(0..n).rev().collect()",
|
| 230 |
+
"Iteration order was ascending where descending is required; .rev() reverses the sequence."),
|
| 231 |
+
# iterator methods
|
| 232 |
+
("collecttovec_bug",
|
| 233 |
+
"pub fn evens(n: u32) -> Vec<u32> { (0..n).filter(|x| x % 2 == 1).collect() }",
|
| 234 |
+
"x % 2 == 1", "x % 2 == 0",
|
| 235 |
+
"The filter kept odd numbers instead of even; flipping the remainder check returns the right set."),
|
| 236 |
+
("filtermaplib_bug",
|
| 237 |
+
"pub fn nonzero(v: &[i32]) -> Vec<i32> { v.iter().filter(|x| **x == 0).copied().collect() }",
|
| 238 |
+
"**x == 0", "**x != 0",
|
| 239 |
+
"Zero values were kept; inverting the predicate yields the nonzero subset."),
|
| 240 |
+
("foldlib_bug",
|
| 241 |
+
"pub fn product(v: &[i32]) -> i32 { v.iter().fold(0, |acc, x| acc * x) }",
|
| 242 |
+
"fold(0,", "fold(1,",
|
| 243 |
+
"Product folding started from 0 and always produced 0; starting from 1 gives the correct product."),
|
| 244 |
+
("foldsumlib_bug",
|
| 245 |
+
"pub fn sum(v: &[i32]) -> i32 { v.iter().fold(1, |acc, x| acc + x) }",
|
| 246 |
+
"fold(1,", "fold(0,",
|
| 247 |
+
"Summation folding started from 1, off by one; starting from 0 returns the true sum."),
|
| 248 |
+
("minunwraplib_bug",
|
| 249 |
+
"pub fn smallest(v: &[i32]) -> i32 { *v.iter().max().unwrap_or(&0) }",
|
| 250 |
+
".max()", ".min()",
|
| 251 |
+
"max was selected where the smallest element is required; switching iterator methods fixes it."),
|
| 252 |
+
("maxbylib_bug",
|
| 253 |
+
"pub fn longest<'a>(v: &'a [&'a str]) -> &'a str { v.iter().min_by_key(|s| s.len()).copied().unwrap_or(\"\") }",
|
| 254 |
+
".min_by_key", ".max_by_key",
|
| 255 |
+
"min_by_key returned the shortest entry; the spec wants the longest, so max_by_key is correct."),
|
| 256 |
+
("countvslen_bug",
|
| 257 |
+
"pub fn n_items(v: &[i32]) -> usize { v.iter().enumerate().count() + 1 }",
|
| 258 |
+
".count() + 1", ".count()",
|
| 259 |
+
"An off-by-one extra was added to the count; removing it matches the slice length."),
|
| 260 |
+
("enumeratelib_bug",
|
| 261 |
+
"pub fn first_at_index(v: &[i32], k: usize) -> Option<i32> { v.iter().nth(k - 1).copied() }",
|
| 262 |
+
"k - 1", "k",
|
| 263 |
+
"Subtracting 1 from the index was a manual off-by-one; nth already takes a 0-based index."),
|
| 264 |
+
("clonedvscopied_bug",
|
| 265 |
+
"pub fn first_clone(v: &[i32]) -> Option<i32> { v.iter().next().cloned() }",
|
| 266 |
+
".cloned()", ".copied()",
|
| 267 |
+
"i32 is Copy, so .copied() is the canonical (and slightly cheaper) operation here."),
|
| 268 |
+
# string methods
|
| 269 |
+
("uppercaselib_bug",
|
| 270 |
+
"pub fn shout(s: &str) -> String { s.to_lowercase() }",
|
| 271 |
+
"to_lowercase", "to_uppercase",
|
| 272 |
+
"The wrong case method was used; to_uppercase produces the expected SHOUTING output."),
|
| 273 |
+
("trimlib_bug",
|
| 274 |
+
"pub fn trim_input(s: &str) -> &str { s.trim_start() }",
|
| 275 |
+
"trim_start", "trim",
|
| 276 |
+
"trim_start only strips leading whitespace; the spec wants both ends, so trim is right."),
|
| 277 |
+
("startswithlib_bug",
|
| 278 |
+
"pub fn is_prefixed(s: &str, p: &str) -> bool { s.ends_with(p) }",
|
| 279 |
+
"ends_with", "starts_with",
|
| 280 |
+
"ends_with was used instead of starts_with; the prefix check needs the opposite method."),
|
| 281 |
+
("endswithlib_bug",
|
| 282 |
+
"pub fn is_suffixed(s: &str, p: &str) -> bool { s.starts_with(p) }",
|
| 283 |
+
"starts_with", "ends_with",
|
| 284 |
+
"starts_with was used instead of ends_with; the suffix check needs the opposite method."),
|
| 285 |
+
("byteslib_bug",
|
| 286 |
+
"pub fn char_count(s: &str) -> usize { s.len() }",
|
| 287 |
+
"s.len()", "s.chars().count()",
|
| 288 |
+
"Byte length was returned where character count is needed; chars().count() handles multibyte chars."),
|
| 289 |
+
("splitlib_bug",
|
| 290 |
+
"pub fn n_words(s: &str) -> usize { s.split(',').count() }",
|
| 291 |
+
"split(',')", "split_whitespace()",
|
| 292 |
+
"Splitting on commas only counts comma-separated fields; split_whitespace() returns whitespace-delimited word count."),
|
| 293 |
+
("joinlib_bug",
|
| 294 |
+
"pub fn join_dash(parts: &[&str]) -> String { parts.join(\",\") }",
|
| 295 |
+
"\",\"", "\"-\"",
|
| 296 |
+
"The wrong separator was used; replacing the comma with a dash matches the expected output."),
|
| 297 |
+
("replacelib_bug",
|
| 298 |
+
"pub fn shout_oh(s: &str) -> String { s.replace(\"oh\", \"OH\").to_lowercase() }",
|
| 299 |
+
".to_lowercase()", "",
|
| 300 |
+
"The final to_lowercase() undid the replacement uppercasing; removing it preserves the OH."),
|
| 301 |
+
("contiainslib_bug",
|
| 302 |
+
"pub fn has_a(s: &str) -> bool { s.contains(\"b\") }",
|
| 303 |
+
"\"b\"", "\"a\"",
|
| 304 |
+
"The wrong substring was searched for; updating it to 'a' matches the function name."),
|
| 305 |
+
("charcountlib_bug",
|
| 306 |
+
"pub fn count_a(s: &str) -> usize { s.chars().filter(|c| *c == 'b').count() }",
|
| 307 |
+
"*c == 'b'", "*c == 'a'",
|
| 308 |
+
"The filter checked for the wrong letter; switching to 'a' matches the function intent."),
|
| 309 |
+
# control flow
|
| 310 |
+
("boollib_bug",
|
| 311 |
+
"pub fn both(a: bool, b: bool) -> bool { a || b }",
|
| 312 |
+
"a || b", "a && b",
|
| 313 |
+
"Or was used where logical-and is required; switching the operator fixes the predicate."),
|
| 314 |
+
("orlib_bug",
|
| 315 |
+
"pub fn either(a: bool, b: bool) -> bool { a && b }",
|
| 316 |
+
"a && b", "a || b",
|
| 317 |
+
"And was used where or is required; the operator switch matches the spec."),
|
| 318 |
+
("notlib_bug",
|
| 319 |
+
"pub fn is_false(b: bool) -> bool { b }",
|
| 320 |
+
"pub fn is_false(b: bool) -> bool { b }",
|
| 321 |
+
"pub fn is_false(b: bool) -> bool { !b }",
|
| 322 |
+
"The function returned its argument; negating it returns the expected predicate."),
|
| 323 |
+
("matchlib_bug",
|
| 324 |
+
"pub fn sign(n: i32) -> i32 { match n { x if x < 0 => 1, 0 => 0, _ => -1 } }",
|
| 325 |
+
"x < 0 => 1, 0 => 0, _ => -1",
|
| 326 |
+
"x < 0 => -1, 0 => 0, _ => 1",
|
| 327 |
+
"Positive and negative arms were swapped; restoring conventional sign returns -1 for negatives and 1 for positives."),
|
| 328 |
+
("optunwraplib_bug",
|
| 329 |
+
"pub fn or_zero(o: Option<i32>) -> i32 { o.unwrap_or(1) }",
|
| 330 |
+
"o.unwrap_or(1)", "o.unwrap_or(0)",
|
| 331 |
+
"The default was 1 where 0 is required; updating the default fixes the fallback."),
|
| 332 |
+
("optmaplib_bug",
|
| 333 |
+
"pub fn doubled_opt(o: Option<i32>) -> Option<i32> { o.map(|x| x + x) }",
|
| 334 |
+
"x + x", "x * 2",
|
| 335 |
+
"Addition is fine but the spec asks for an explicit multiplication-by-2 expression here."),
|
| 336 |
+
("ifelselib_bug",
|
| 337 |
+
"pub fn pick(b: bool) -> i32 { if b { 0 } else { 1 } }",
|
| 338 |
+
"if b { 0 } else { 1 }", "if b { 1 } else { 0 }",
|
| 339 |
+
"The if-else branches were swapped; restoring them returns 1 on true and 0 on false."),
|
| 340 |
+
("recursionbaselib_bug",
|
| 341 |
+
"pub fn fact_rec(n: u32) -> u32 { if n == 0 { 0 } else { n * fact_rec(n - 1) } }",
|
| 342 |
+
"if n == 0 { 0 }", "if n == 0 { 1 }",
|
| 343 |
+
"The factorial base case returned 0, killing the product; returning 1 makes the recursion work."),
|
| 344 |
+
("whileloopib_bug",
|
| 345 |
+
"pub fn count_to(n: u32) -> u32 { let mut i = 0; while i < n { i += 2; } i }",
|
| 346 |
+
"i += 2", "i += 1",
|
| 347 |
+
"The loop incremented by 2, skipping every other number; stepping by 1 reaches n correctly."),
|
| 348 |
+
("optsomelib_bug",
|
| 349 |
+
"pub fn always_some() -> Option<i32> { None }",
|
| 350 |
+
"None", "Some(0)",
|
| 351 |
+
"None was returned where Some is required; the simplest fix returns Some(0)."),
|
| 352 |
+
("returnvallib_bug",
|
| 353 |
+
"pub fn ten() -> i32 { 100 }",
|
| 354 |
+
"100", "10",
|
| 355 |
+
"The literal was off by a factor of 10; replacing it returns the expected ten."),
|
| 356 |
+
]
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def lib_bug_trace(crate, buggy_src, find, replace, summary):
|
| 360 |
+
project_path = f"/workspace/glyph/runs/rlvr1/rust_cases/{crate}"
|
| 361 |
+
file_path = f"{project_path}/src/lib.rs"
|
| 362 |
+
full_src_for_read = (
|
| 363 |
+
f"{buggy_src}\n\n#[cfg(test)]\nmod tests {{\n use super::*;\n #[test] fn t() {{ /* asserts pass after fix */ }}\n}}\n"
|
| 364 |
+
)
|
| 365 |
+
user = (
|
| 366 |
+
f'The Cargo project at "{project_path}" has a failing test. Read the source at '
|
| 367 |
+
f'"{file_path}" first, then apply a one-line patch and verify with cargo_test.'
|
| 368 |
+
)
|
| 369 |
+
todos = [
|
| 370 |
+
f"Read the source at {file_path} to find the buggy snippet.",
|
| 371 |
+
f"Use apply_patch to replace the buggy text with the correct version.",
|
| 372 |
+
f"Run cargo_test on {project_path} to confirm the fix.",
|
| 373 |
+
]
|
| 374 |
+
rationale = "Inspect the file before patching so the find string exactly matches the source, then verify."
|
| 375 |
+
return three_tool_trace(
|
| 376 |
+
user, todos, rationale,
|
| 377 |
+
"read_file", [("file_path", file_path)], "src1",
|
| 378 |
+
full_src_for_read.replace('"', '\\"'),
|
| 379 |
+
"The buggy line is visible in the source; the targeted snippet matches exactly once.",
|
| 380 |
+
"note_src",
|
| 381 |
+
"apply_patch",
|
| 382 |
+
[("file_path", file_path), ("find", find), ("replace", replace)],
|
| 383 |
+
"patch1",
|
| 384 |
+
"status: success\\nexit_code: 0",
|
| 385 |
+
"Patch applied cleanly; the source now contains the corrected expression.",
|
| 386 |
+
"note_patched",
|
| 387 |
+
"cargo_test", [("project_path", project_path)], "test1",
|
| 388 |
+
"status: success\\nexit_code: 0\\nstdout: test result: ok",
|
| 389 |
+
f"cargo_test passes after the fix. {summary}",
|
| 390 |
+
"note_verified",
|
| 391 |
+
summary,
|
| 392 |
+
)
|
| 393 |
+
|
| 394 |
+
|
| 395 |
+
# ---------------------------------------------------------------------------
|
| 396 |
+
# Bin-crate bug-fix traces: read_file → apply_patch → cargo_run → respond.
|
| 397 |
+
# ---------------------------------------------------------------------------
|
| 398 |
+
|
| 399 |
+
BIN_BUGFIX_CASES = [
|
| 400 |
+
("bugbin_hello",
|
| 401 |
+
'fn main() { println!("goodbye"); }',
|
| 402 |
+
'"goodbye"', '"hello"', "hello",
|
| 403 |
+
"The greeting string was wrong; replacing it produces the expected stdout."),
|
| 404 |
+
("bugbin_sum",
|
| 405 |
+
'fn main() { let v = [1,2,3,4]; let s: i32 = v.iter().product(); println!("{s}"); }',
|
| 406 |
+
"v.iter().product()", "v.iter().sum()", "10",
|
| 407 |
+
"The reducer was product instead of sum; switching gives the expected total."),
|
| 408 |
+
("bugbin_double",
|
| 409 |
+
'fn main() { let x = 7; println!("{}", x + 2); }',
|
| 410 |
+
"x + 2", "x * 2", "14",
|
| 411 |
+
"Addition was used where doubling was required; the multiplication fixes the output."),
|
| 412 |
+
("bugbin_count",
|
| 413 |
+
'fn main() { for n in 1..5 { print!("{n} "); } println!(); }',
|
| 414 |
+
"1..5", "1..=5", "1 2 3 4 5",
|
| 415 |
+
"The exclusive range omitted 5; making it inclusive prints the full sequence."),
|
| 416 |
+
("bugbin_upper",
|
| 417 |
+
'fn main() { println!("{}", "rust".to_lowercase()); }',
|
| 418 |
+
"to_lowercase", "to_uppercase", "RUST",
|
| 419 |
+
"The wrong case method was used; to_uppercase produces the expected output."),
|
| 420 |
+
("bugbin_rev",
|
| 421 |
+
'fn main() { let s = "rust"; let r: String = s.chars().collect(); println!("{r}"); }',
|
| 422 |
+
"s.chars().collect()", "s.chars().rev().collect()", "tsur",
|
| 423 |
+
"The chars iterator wasn't reversed; adding .rev() yields the reversed string."),
|
| 424 |
+
("bugbin_square",
|
| 425 |
+
'fn main() { for n in 1..=4 { print!("{} ", n + n); } println!(); }',
|
| 426 |
+
"n + n", "n * n", "1 4 9 16",
|
| 427 |
+
"The expression doubled rather than squared; multiplying n by itself fixes the output."),
|
| 428 |
+
("bugbin_word",
|
| 429 |
+
'fn main() { let s = "one two three"; println!("{}", s.len()); }',
|
| 430 |
+
"s.len()", "s.split_whitespace().count()", "3",
|
| 431 |
+
"Byte length was returned instead of word count; switching to split_whitespace().count() fixes it."),
|
| 432 |
+
# --- extended bin bugs
|
| 433 |
+
("bugbin_max",
|
| 434 |
+
'fn main() { let v = [3, 1, 5, 2]; println!("{}", v.iter().min().unwrap()); }',
|
| 435 |
+
"v.iter().min()", "v.iter().max()", "5",
|
| 436 |
+
"The program reported the minimum instead of the maximum; switching iterator methods fixes the output."),
|
| 437 |
+
("bugbin_avg",
|
| 438 |
+
'fn main() { let v = [2, 4, 6, 8]; let s: i32 = v.iter().sum(); println!("{}", s); }',
|
| 439 |
+
"println!(\"{}\", s);", "println!(\"{}\", s / v.len() as i32);", "5",
|
| 440 |
+
"The program printed the sum but the spec requires the average; dividing by length fixes it."),
|
| 441 |
+
("bugbin_evens",
|
| 442 |
+
'fn main() { for n in 1..=5 { if n % 2 == 1 { print!("{} ", n); } } println!(); }',
|
| 443 |
+
"n % 2 == 1", "n % 2 == 0", "2 4",
|
| 444 |
+
"The filter kept odd numbers; flipping the condition prints the evens 2 and 4."),
|
| 445 |
+
("bugbin_join",
|
| 446 |
+
'fn main() { let parts = ["a", "b", "c"]; println!("{}", parts.join(",")); }',
|
| 447 |
+
"join(\",\")", "join(\"-\")", "a-b-c",
|
| 448 |
+
"The separator was a comma where the spec asks for a dash; switching joins with the right glue."),
|
| 449 |
+
("bugbin_caps",
|
| 450 |
+
'fn main() { println!("{}", "rust".to_uppercase().to_lowercase()); }',
|
| 451 |
+
".to_lowercase()", "", "RUST",
|
| 452 |
+
"An unnecessary to_lowercase() undid the uppercasing; removing it leaves RUST."),
|
| 453 |
+
("bugbin_neg",
|
| 454 |
+
'fn main() { let x = -42; println!("{}", x); }',
|
| 455 |
+
"let x = -42;", "let x = 42;", "42",
|
| 456 |
+
"The literal was negative; the spec asks for the positive 42."),
|
| 457 |
+
("bugbin_concat",
|
| 458 |
+
'fn main() { let a = "hi"; let b = "there"; println!("{}{}", b, a); }',
|
| 459 |
+
"println!(\"{}{}\", b, a);", "println!(\"{}{}\", a, b);", "hithere",
|
| 460 |
+
"The arguments were in the wrong order; swapping them yields hi-then-there."),
|
| 461 |
+
("bugbin_format",
|
| 462 |
+
'fn main() { let n = 7; println!("{:b}", n); }',
|
| 463 |
+
"{:b}", "{}", "7",
|
| 464 |
+
"Binary formatting was used where decimal is required; removing the format spec prints the integer."),
|
| 465 |
+
("bugbin_starsq",
|
| 466 |
+
'fn main() { for n in 1..=3 { println!("{}", n * 2); } }',
|
| 467 |
+
"n * 2", "n * n", "1\n4\n9",
|
| 468 |
+
"Doubling was used where squaring is required; multiplying n by itself fixes the values."),
|
| 469 |
+
("bugbin_cumsum",
|
| 470 |
+
'fn main() { let v = [1, 2, 3]; let mut s = 0; for x in &v { s = *x; print!("{} ", s); } println!(); }',
|
| 471 |
+
"s = *x;", "s += *x;", "1 3 6",
|
| 472 |
+
"The accumulator was overwritten instead of added to; switching to compound assignment produces the running sum."),
|
| 473 |
+
("bugbin_decrement",
|
| 474 |
+
'fn main() { let mut n = 5; for _ in 0..3 { n += 1; print!("{} ", n); } println!(); }',
|
| 475 |
+
"n += 1", "n -= 1", "4 3 2",
|
| 476 |
+
"The loop incremented; the expected output counts down, so the operator should be decrement."),
|
| 477 |
+
("bugbin_charcount",
|
| 478 |
+
'fn main() { let s = "héllo"; println!("{}", s.len()); }',
|
| 479 |
+
"s.len()", "s.chars().count()", "5",
|
| 480 |
+
"Byte length over-counts multibyte chars; chars().count() returns the visible character count."),
|
| 481 |
+
("bugbin_modpadding",
|
| 482 |
+
'fn main() { for n in 0..5 { let lbl = if n % 2 == 1 { "odd" } else { "even" }; println!("{} {}", n, lbl); } }',
|
| 483 |
+
"n % 2 == 1", "n % 2 == 0", "0 even\n1 odd\n2 even\n3 odd\n4 even",
|
| 484 |
+
"The labels were swapped because the check matched odd instead of even; flipping the equality restores them."),
|
| 485 |
+
("bugbin_substr",
|
| 486 |
+
'fn main() { let s = "abcdef"; println!("{}", &s[0..3]); }',
|
| 487 |
+
"&s[0..3]", "&s[3..6]", "def",
|
| 488 |
+
"The wrong slice was taken; offsetting to 3..6 yields the last three characters."),
|
| 489 |
+
("bugbin_format_decimal",
|
| 490 |
+
'fn main() { let pi: f64 = 3.14159; println!("{}", pi); }',
|
| 491 |
+
"println!(\"{}\", pi);", "println!(\"{:.2}\", pi);", "3.14",
|
| 492 |
+
"Default formatting prints too many digits; the {:.2} spec rounds to two decimals."),
|
| 493 |
+
("bugbin_indexing",
|
| 494 |
+
'fn main() { let v = vec![10, 20, 30]; println!("{}", v[0]); }',
|
| 495 |
+
"v[0]", "v[2]", "30",
|
| 496 |
+
"The wrong index was used; reading v[2] returns the last element 30."),
|
| 497 |
+
("bugbin_min",
|
| 498 |
+
'fn main() { let v = [3, 1, 5, 2]; println!("{}", v.iter().max().unwrap()); }',
|
| 499 |
+
"v.iter().max()", "v.iter().min()", "1",
|
| 500 |
+
"The program reported the maximum where the minimum is required; switching iterator methods fixes the output."),
|
| 501 |
+
("bugbin_filteralpha",
|
| 502 |
+
'fn main() { let s = "abc123"; let r: String = s.chars().filter(|c| c.is_alphabetic()).collect(); println!("{}", r); }',
|
| 503 |
+
"is_alphabetic", "is_numeric", "123",
|
| 504 |
+
"The filter kept letters where the spec asks for digits; switching to is_numeric returns the numeric substring."),
|
| 505 |
+
("bugbin_loopprint",
|
| 506 |
+
'fn main() { for i in (1..=5).rev() { print!("{} ", i); } println!(); }',
|
| 507 |
+
"(1..=5).rev()", "(1..=5)", "1 2 3 4 5",
|
| 508 |
+
"The sequence was emitted in reverse; removing .rev() prints ascending values."),
|
| 509 |
+
("bugbin_assign",
|
| 510 |
+
'fn main() { let mut x = 0; x = x + 1; x = x + 1; println!("{}", x); }',
|
| 511 |
+
"let mut x = 0;", "let mut x = 3;", "5",
|
| 512 |
+
"The starting value was 0; setting it to 3 makes the two increments land on 5."),
|
| 513 |
+
("bugbin_pow",
|
| 514 |
+
'fn main() { let n: i32 = 2; println!("{}", n.pow(2)); }',
|
| 515 |
+
"n.pow(2)", "n.pow(8)", "256",
|
| 516 |
+
"The exponent was 2 instead of 8; updating it produces 2^8 = 256."),
|
| 517 |
+
("bugbin_chars",
|
| 518 |
+
'fn main() { let s = "rust"; println!("{}", s.chars().nth(0).unwrap()); }',
|
| 519 |
+
".nth(0)", ".nth(3)", "t",
|
| 520 |
+
"The first character was selected instead of the fourth; nth(3) returns the last char."),
|
| 521 |
+
("bugbin_emptycheck",
|
| 522 |
+
'fn main() { let v: Vec<i32> = vec![]; println!("{}", if v.is_empty() { "no" } else { "yes" }); }',
|
| 523 |
+
"if v.is_empty() { \"no\" } else { \"yes\" }",
|
| 524 |
+
"if v.is_empty() { \"yes\" } else { \"no\" }",
|
| 525 |
+
"yes",
|
| 526 |
+
"The labels were inverted; flipping them lets is_empty() print yes for an empty vector."),
|
| 527 |
+
("bugbin_truthy",
|
| 528 |
+
'fn main() { let x = 10; if x > 0 { println!("non-positive"); } else { println!("positive"); } }',
|
| 529 |
+
"if x > 0 { println!(\"non-positive\"); } else { println!(\"positive\"); }",
|
| 530 |
+
"if x > 0 { println!(\"positive\"); } else { println!(\"non-positive\"); }",
|
| 531 |
+
"positive",
|
| 532 |
+
"The branches' labels were swapped; restoring them prints the right description for x = 10."),
|
| 533 |
+
("bugbin_uppercase_only_first",
|
| 534 |
+
'fn main() { let s = "hello"; let mut chars = s.chars(); let first = chars.next().unwrap().to_lowercase().next().unwrap(); println!("{}{}", first, chars.as_str()); }',
|
| 535 |
+
"to_lowercase()", "to_uppercase()", "Hello",
|
| 536 |
+
"The first character was being lowercased instead of uppercased; the fix produces Hello."),
|
| 537 |
+
("bugbin_collectvecstr",
|
| 538 |
+
'fn main() { let v = vec!["a", "b", "c"]; let s: String = v.into_iter().collect::<Vec<&str>>().concat(); println!("{}", s); }',
|
| 539 |
+
".collect::<Vec<&str>>().concat()", ".collect::<String>()",
|
| 540 |
+
"abc",
|
| 541 |
+
"An intermediate Vec collect-then-concat was used; collecting directly into a String is simpler and produces the same result."),
|
| 542 |
+
("bugbin_truthycheck",
|
| 543 |
+
'fn main() { let n = 5; println!("{}", n == 0); }',
|
| 544 |
+
"n == 0", "n != 0", "true",
|
| 545 |
+
"Equality-with-zero was returned where non-zero is intended; flipping the operator yields true for n = 5."),
|
| 546 |
+
("bugbin_iterpattern",
|
| 547 |
+
'fn main() { let v = [10, 20, 30]; for x in v.iter().rev() { print!("{} ", x); } println!(); }',
|
| 548 |
+
"v.iter().rev()", "v.iter()", "10 20 30",
|
| 549 |
+
"The slice was iterated in reverse; removing .rev() emits the natural order."),
|
| 550 |
+
("bugbin_iterzip",
|
| 551 |
+
'fn main() { let a = [1, 2, 3]; let b = ["x", "y", "z"]; for (x, y) in b.iter().zip(a.iter()) { println!("{}{}", x, y); } }',
|
| 552 |
+
"b.iter().zip(a.iter())",
|
| 553 |
+
"a.iter().zip(b.iter())",
|
| 554 |
+
"1x\n2y\n3z",
|
| 555 |
+
"Zipping order was reversed so the format args came out swapped; placing a first matches the intent."),
|
| 556 |
+
("bugbin_loopaccum",
|
| 557 |
+
'fn main() { let v = [1, 2, 3, 4]; let mut s = 0; for x in v.iter() { s += *x * 2; } println!("{}", s); }',
|
| 558 |
+
"s += *x * 2;", "s += *x;", "10",
|
| 559 |
+
"The accumulator added twice each element; removing the *2 produces the plain sum."),
|
| 560 |
+
("bugbin_optunwrap",
|
| 561 |
+
'fn main() { let o: Option<i32> = Some(7); println!("{}", o.unwrap_or(-1)); }',
|
| 562 |
+
"Some(7)", "None", "-1",
|
| 563 |
+
"The Option carried a value where the spec needs None so the default of -1 prints."),
|
| 564 |
+
("bugbin_resultok",
|
| 565 |
+
'fn main() { let r: Result<i32, &str> = Err("nope"); println!("{}", r.unwrap_or(0)); }',
|
| 566 |
+
"Err(\"nope\")", "Ok(42)", "42",
|
| 567 |
+
"The Result was Err so unwrap_or returned its default; switching to Ok(42) prints the inner value."),
|
| 568 |
+
]
|
| 569 |
+
|
| 570 |
+
|
| 571 |
+
def bin_bug_trace(crate, buggy_src, find, replace, expected_stdout, summary):
|
| 572 |
+
project_path = f"/workspace/glyph/runs/rlvr1/rust_cases/{crate}"
|
| 573 |
+
file_path = f"{project_path}/src/main.rs"
|
| 574 |
+
user = (
|
| 575 |
+
f'The Cargo binary at "{project_path}" prints the wrong output. Read "{file_path}", '
|
| 576 |
+
f'patch it, then verify with cargo_run — expected stdout is "{expected_stdout}".'
|
| 577 |
+
)
|
| 578 |
+
todos = [
|
| 579 |
+
f"Read {file_path} to locate the buggy expression.",
|
| 580 |
+
f"Apply a one-line patch to correct it.",
|
| 581 |
+
f"Run cargo_run on {project_path} and confirm the stdout matches.",
|
| 582 |
+
]
|
| 583 |
+
rationale = "Inspect first so the apply_patch find string matches the source verbatim, then verify by running the binary."
|
| 584 |
+
return three_tool_trace(
|
| 585 |
+
user, todos, rationale,
|
| 586 |
+
"read_file", [("file_path", file_path)], "src1",
|
| 587 |
+
buggy_src.replace('"', '\\"'),
|
| 588 |
+
"The buggy snippet is visible and occurs exactly once in main.rs.",
|
| 589 |
+
"note_src",
|
| 590 |
+
"apply_patch",
|
| 591 |
+
[("file_path", file_path), ("find", find), ("replace", replace)],
|
| 592 |
+
"patch1",
|
| 593 |
+
"status: success\\nexit_code: 0",
|
| 594 |
+
"Patch applied; main.rs now uses the corrected expression.",
|
| 595 |
+
"note_patched",
|
| 596 |
+
"cargo_run", [("project_path", project_path)], "run1",
|
| 597 |
+
f"status: success\\nexit_code: 0\\nstdout: {expected_stdout}",
|
| 598 |
+
f"cargo_run output matches the expected stdout. {summary}",
|
| 599 |
+
"note_verified",
|
| 600 |
+
f"Fixed the source and confirmed by cargo_run; output is \\\"{expected_stdout}\\\". {summary}",
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
# ---------------------------------------------------------------------------
|
| 605 |
+
# Single-tool traces for tools missing from the original SFT pool:
|
| 606 |
+
# cargo_build, cargo_run, rustc, plus read_file (info-only).
|
| 607 |
+
# ---------------------------------------------------------------------------
|
| 608 |
+
|
| 609 |
+
def single_call_trace(user, tool_name, args, call_id, result_data, response, fix_summary_thought):
|
| 610 |
+
return g.single_tool_trace(
|
| 611 |
+
SYSTEM, rust_dev_tools(), user,
|
| 612 |
+
[
|
| 613 |
+
f"Run {tool_name} to satisfy the user's request.",
|
| 614 |
+
"Report the outcome briefly.",
|
| 615 |
+
],
|
| 616 |
+
"Use one verifier call, then summarize the outcome.",
|
| 617 |
+
tool_name, args, call_id,
|
| 618 |
+
result_data,
|
| 619 |
+
fix_summary_thought, f"note_{tool_name}",
|
| 620 |
+
response,
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
|
| 624 |
+
SINGLE_TOOL_CASES = [
|
| 625 |
+
# cargo_build
|
| 626 |
+
("Compile the Cargo binary project at \"/workspace/glyph/runs/rlvr1/rust_cases/greeter2\".",
|
| 627 |
+
"cargo_build",
|
| 628 |
+
[("project_path", "/workspace/glyph/runs/rlvr1/rust_cases/greeter2")],
|
| 629 |
+
"build1",
|
| 630 |
+
"status: success\\nexit_code: 0\\nstdout: Compiling greeter2 v0.1.0\\nFinished `dev` profile",
|
| 631 |
+
"cargo_build succeeded; the binary is built in target/debug/.",
|
| 632 |
+
"The build completed; the project compiles cleanly and produces a debug binary."),
|
| 633 |
+
("Build the Cargo project at \"/workspace/glyph/runs/rlvr1/rust_cases/counter2\".",
|
| 634 |
+
"cargo_build",
|
| 635 |
+
[("project_path", "/workspace/glyph/runs/rlvr1/rust_cases/counter2")],
|
| 636 |
+
"build1",
|
| 637 |
+
"status: success\\nexit_code: 0\\nstdout: Compiling counter2 v0.1.0\\nFinished `dev` profile",
|
| 638 |
+
"cargo_build finished without errors; the artifact lives in target/debug/.",
|
| 639 |
+
"The build is green and the binary is ready for execution."),
|
| 640 |
+
# cargo_run
|
| 641 |
+
("Run the Cargo binary at \"/workspace/glyph/runs/rlvr1/rust_cases/greeter2\" and report its stdout.",
|
| 642 |
+
"cargo_run",
|
| 643 |
+
[("project_path", "/workspace/glyph/runs/rlvr1/rust_cases/greeter2")],
|
| 644 |
+
"run1",
|
| 645 |
+
"status: success\\nexit_code: 0\\nstdout: hello",
|
| 646 |
+
"cargo_run printed 'hello'; the binary works as expected.",
|
| 647 |
+
"The program ran successfully and printed: hello."),
|
| 648 |
+
("Execute the Cargo binary at \"/workspace/glyph/runs/rlvr1/rust_cases/counter2\".",
|
| 649 |
+
"cargo_run",
|
| 650 |
+
[("project_path", "/workspace/glyph/runs/rlvr1/rust_cases/counter2")],
|
| 651 |
+
"run1",
|
| 652 |
+
"status: success\\nexit_code: 0\\nstdout: 1\\n2\\n3\\n4\\n5",
|
| 653 |
+
"cargo_run printed the numbers 1..5 one per line.",
|
| 654 |
+
"The program ran successfully and produced the expected sequence 1..5."),
|
| 655 |
+
# cargo_check
|
| 656 |
+
("Run cargo_check on the project at \"/workspace/glyph/runs/rlvr1/rust_cases/mathlib2\".",
|
| 657 |
+
"cargo_check",
|
| 658 |
+
[("project_path", "/workspace/glyph/runs/rlvr1/rust_cases/mathlib2")],
|
| 659 |
+
"chk1",
|
| 660 |
+
"status: success\\nexit_code: 0\\nstdout: Checking mathlib2 v0.1.0\\nFinished",
|
| 661 |
+
"cargo_check passed; no compile errors.",
|
| 662 |
+
"The crate type-checks cleanly."),
|
| 663 |
+
# rustc
|
| 664 |
+
("Compile \"/workspace/glyph/runs/rlvr1/rust_cases/hello2.rs\" to the binary \"/workspace/glyph/runs/rlvr1/rust_cases/hello2_bin\".",
|
| 665 |
+
"rustc",
|
| 666 |
+
[("source_file", "/workspace/glyph/runs/rlvr1/rust_cases/hello2.rs"),
|
| 667 |
+
("output", "/workspace/glyph/runs/rlvr1/rust_cases/hello2_bin")],
|
| 668 |
+
"rc1",
|
| 669 |
+
"status: success\\nexit_code: 0\\nstdout:",
|
| 670 |
+
"rustc compiled the single source file to the requested output path.",
|
| 671 |
+
"The source compiled without errors."),
|
| 672 |
+
# read_file (info-gathering only)
|
| 673 |
+
("Show the contents of \"/workspace/glyph/runs/rlvr1/rust_cases/mathlib2/src/lib.rs\".",
|
| 674 |
+
"read_file",
|
| 675 |
+
[("file_path", "/workspace/glyph/runs/rlvr1/rust_cases/mathlib2/src/lib.rs")],
|
| 676 |
+
"src1",
|
| 677 |
+
"pub fn add(a: i32, b: i32) -> i32 { a + b }",
|
| 678 |
+
"The file defines a single public add function returning the sum of two i32 values.",
|
| 679 |
+
"The file at that path defines `pub fn add(a: i32, b: i32) -> i32 { a + b }`."),
|
| 680 |
+
("Read \"/workspace/glyph/runs/rlvr1/rust_cases/strutils/src/lib.rs\" and tell me what it does.",
|
| 681 |
+
"read_file",
|
| 682 |
+
[("file_path", "/workspace/glyph/runs/rlvr1/rust_cases/strutils/src/lib.rs")],
|
| 683 |
+
"src1",
|
| 684 |
+
"pub fn shout(s: &str) -> String { s.to_uppercase() }",
|
| 685 |
+
"The file exposes one public function that uppercases its &str input.",
|
| 686 |
+
"The file defines `pub fn shout(s: &str) -> String { s.to_uppercase() }`, which uppercases input."),
|
| 687 |
+
]
|
| 688 |
+
|
| 689 |
+
|
| 690 |
+
# Programmatic bulk generators for single-tool examples — varied projects,
|
| 691 |
+
# small phrasing differences, each trace fully formatted.
|
| 692 |
+
BULK_PROJECTS = [
|
| 693 |
+
# (name, kind, src) where kind ∈ {lib, bin}
|
| 694 |
+
("addlib_pos", "lib", "pub fn add(a: i32, b: i32) -> i32 { a + b }"),
|
| 695 |
+
("sublib_pos", "lib", "pub fn sub(a: i32, b: i32) -> i32 { a - b }"),
|
| 696 |
+
("evenlib_pos", "lib", "pub fn is_even(n: i32) -> bool { n % 2 == 0 }"),
|
| 697 |
+
("sumlib_pos", "lib", "pub fn sum(s: &[i32]) -> i32 { s.iter().sum() }"),
|
| 698 |
+
("maxlib_pos", "lib", "pub fn maxv(s: &[i32]) -> i32 { *s.iter().max().unwrap_or(&0) }"),
|
| 699 |
+
("revstrlib_pos", "lib", "pub fn rev(s: &str) -> String { s.chars().rev().collect() }"),
|
| 700 |
+
("strutils2", "lib", "pub fn shout(s: &str) -> String { s.to_uppercase() }"),
|
| 701 |
+
("rangelib_pos", "lib", "pub fn in_range(v: i32, lo: i32, hi: i32) -> bool { v >= lo && v <= hi }"),
|
| 702 |
+
("optionlib_pos", "lib", "pub fn first_or(s: &[i32], d: i32) -> i32 { s.first().copied().unwrap_or(d) }"),
|
| 703 |
+
("dedup_lib", "lib", "pub fn dedup(mut v: Vec<i32>) -> Vec<i32> { v.sort(); v.dedup(); v }"),
|
| 704 |
+
("fizz_lib", "lib", 'pub fn fizz(n: u32) -> String { if n % 15 == 0 { "FizzBuzz".into() } else if n % 3 == 0 { "Fizz".into() } else if n % 5 == 0 { "Buzz".into() } else { n.to_string() } }'),
|
| 705 |
+
("hello_bin", "bin", 'fn main() { println!("hello"); }'),
|
| 706 |
+
("greet_bin", "bin", 'fn main() { let who = "world"; println!("hello, {who}!"); }'),
|
| 707 |
+
("count_bin", "bin", 'fn main() { for v in 1..=5 { println!("{v}"); } }'),
|
| 708 |
+
("square_bin", "bin", 'fn main() { for n in 1..=4 { println!("{}", n * n); } }'),
|
| 709 |
+
("calc_bin", "bin", 'fn main() { let (a, b) = (12, 30); println!("{}", a + b); }'),
|
| 710 |
+
("rev_bin", "bin", 'fn main() { let s = "hello"; let r: String = s.chars().rev().collect(); println!("{r}"); }'),
|
| 711 |
+
("fib_bin", "bin", 'fn main() { let (mut a, mut b) = (0u32, 1u32); for _ in 0..6 { print!("{a} "); let t = a + b; a = b; b = t; } println!(); }'),
|
| 712 |
+
("upper_bin", "bin", 'fn main() { println!("{}", "hello".to_uppercase()); }'),
|
| 713 |
+
("primes_bin", "bin", 'fn main() { for n in 2..15 { if (2..n).all(|d| n % d != 0) { print!("{n} "); } } println!(); }'),
|
| 714 |
+
# extended pool
|
| 715 |
+
("absv_lib", "lib", "pub fn absv(n: i32) -> i32 { n.abs() }"),
|
| 716 |
+
("min_of_lib", "lib", "pub fn min_of(s: &[i32]) -> i32 { *s.iter().min().unwrap_or(&0) }"),
|
| 717 |
+
("avg_lib", "lib", "pub fn avg(s: &[f64]) -> f64 { if s.is_empty() { 0.0 } else { s.iter().sum::<f64>() / s.len() as f64 } }"),
|
| 718 |
+
("palin_lib", "lib", "pub fn pal(s: &str) -> bool { let r: String = s.chars().rev().collect(); r == s }"),
|
| 719 |
+
("vowels_lib", "lib", "pub fn vowels(s: &str) -> usize { s.chars().filter(|c| \"aeiouAEIOU\".contains(*c)).count() }"),
|
| 720 |
+
("wc_lib", "lib", "pub fn wc(s: &str) -> usize { s.split_whitespace().count() }"),
|
| 721 |
+
("cap_lib", "lib", "pub fn cap(s: &str) -> String { let mut c = s.chars(); match c.next() { Some(f) => f.to_uppercase().collect::<String>() + c.as_str(), None => String::new() } }"),
|
| 722 |
+
("clamp_lib", "lib", "pub fn clamp(v: i32, lo: i32, hi: i32) -> i32 { v.max(lo).min(hi) }"),
|
| 723 |
+
("gcd_lib", "lib", "pub fn gcd(a: u32, b: u32) -> u32 { if b == 0 { a } else { gcd(b, a % b) } }"),
|
| 724 |
+
("fact_lib", "lib", "pub fn fact(n: u32) -> u32 { (1..=n).product::<u32>().max(1) }"),
|
| 725 |
+
("fib_lib2", "lib", "pub fn fib(n: u32) -> u32 { match n { 0 => 0, 1 => 1, _ => fib(n-1) + fib(n-2) } }"),
|
| 726 |
+
("pair_lib", "lib", "pub fn pair<T: Clone>(x: T) -> (T, T) { (x.clone(), x) }"),
|
| 727 |
+
("first_word_lib", "lib", "pub fn first_word(s: &str) -> &str { s.split_whitespace().next().unwrap_or(\"\") }"),
|
| 728 |
+
("trim_lib", "lib", "pub fn trim_both(s: &str) -> &str { s.trim() }"),
|
| 729 |
+
("split_lib", "lib", "pub fn split_csv(s: &str) -> Vec<&str> { s.split(',').collect() }"),
|
| 730 |
+
("join_lib", "lib", "pub fn join_dash(parts: &[&str]) -> String { parts.join(\"-\") }"),
|
| 731 |
+
("sorted_lib", "lib", "pub fn sorted(mut v: Vec<i32>) -> Vec<i32> { v.sort(); v }"),
|
| 732 |
+
("minmax_lib", "lib", "pub fn min_max(s: &[i32]) -> Option<(i32, i32)> { Some((*s.iter().min()?, *s.iter().max()?)) }"),
|
| 733 |
+
("pow2_lib", "lib", "pub fn is_pow2(n: u32) -> bool { n > 0 && (n & (n-1)) == 0 }"),
|
| 734 |
+
("cube_lib", "lib", "pub fn cube(n: i64) -> i64 { n * n * n }"),
|
| 735 |
+
("parseu_lib", "lib", "pub fn parse_u(s: &str) -> Result<u32, std::num::ParseIntError> { s.parse() }"),
|
| 736 |
+
("optfirst_lib", "lib", "pub fn maybe_first(s: &[i32]) -> Option<i32> { s.first().copied() }"),
|
| 737 |
+
("hashfreq_lib", "lib", "use std::collections::HashMap; pub fn freq(s: &str) -> HashMap<char, usize> { let mut h = HashMap::new(); for c in s.chars() { *h.entry(c).or_insert(0) += 1; } h }"),
|
| 738 |
+
("area_lib", "lib", "pub enum Shape { Circle(f64), Square(f64) } pub fn area(s: &Shape) -> f64 { match s { Shape::Circle(r) => std::f64::consts::PI * r * r, Shape::Square(a) => a * a } }"),
|
| 739 |
+
("trait_lib", "lib", "pub trait Greet { fn hello(&self) -> String; } pub struct P; impl Greet for P { fn hello(&self) -> String { \"hi\".into() } }"),
|
| 740 |
+
("count_vowels_lib", "lib", "pub fn vow(s: &str) -> usize { s.chars().filter(|c| \"aeiou\".contains(*c)).count() }"),
|
| 741 |
+
("evenodd_bin", "bin", 'fn main() { for n in 1..=6 { println!("{n}: {}", if n % 2 == 0 { "even" } else { "odd" }); } }'),
|
| 742 |
+
("collect_bin", "bin", 'fn main() { let v: Vec<i32> = (1..=5).collect(); println!("{v:?}"); }'),
|
| 743 |
+
("zip_bin", "bin", 'fn main() { for (i, c) in "abcd".chars().enumerate() { println!("{i}: {c}"); } }'),
|
| 744 |
+
("fizzbuzz_bin", "bin", 'fn main() { for n in 1..=15 { match (n%3, n%5) { (0,0)=>println!("FizzBuzz"), (0,_)=>println!("Fizz"), (_,0)=>println!("Buzz"), _=>println!("{n}") } } }'),
|
| 745 |
+
]
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
def _project_path(name: str) -> str:
|
| 749 |
+
return f"/workspace/glyph/runs/rlvr1/rust_cases/{name}"
|
| 750 |
+
|
| 751 |
+
|
| 752 |
+
def _file_path(name: str, kind: str) -> str:
|
| 753 |
+
sub = "src/lib.rs" if kind == "lib" else "src/main.rs"
|
| 754 |
+
return f"{_project_path(name)}/{sub}"
|
| 755 |
+
|
| 756 |
+
|
| 757 |
+
def bulk_read_traces() -> list[str]:
|
| 758 |
+
"""Two read_file → response traces per project — varied phrasings."""
|
| 759 |
+
out = []
|
| 760 |
+
phrasings = [
|
| 761 |
+
'Show me the contents of "{fp}".',
|
| 762 |
+
'Read "{fp}" and summarize what the code does.',
|
| 763 |
+
'Open the source at "{fp}" and describe it briefly.',
|
| 764 |
+
'I need to see "{fp}"; read it and explain the public API in one sentence.',
|
| 765 |
+
]
|
| 766 |
+
for i, (name, kind, src) in enumerate(BULK_PROJECTS):
|
| 767 |
+
fp = _file_path(name, kind)
|
| 768 |
+
result = src.replace('"', '\\"')
|
| 769 |
+
if kind == "lib":
|
| 770 |
+
response = f"The file at `{fp}` defines `{src}`."
|
| 771 |
+
else:
|
| 772 |
+
response = f"The binary's `main.rs` at `{fp}` runs: `{src}`."
|
| 773 |
+
for j in (0, 2):
|
| 774 |
+
user = phrasings[(i + j) % len(phrasings)].format(fp=fp)
|
| 775 |
+
out.append(single_call_trace(
|
| 776 |
+
user, "read_file", [("file_path", fp)], "src1", result,
|
| 777 |
+
f"The file contents are visible; the code exposes a single tight implementation.",
|
| 778 |
+
response,
|
| 779 |
+
))
|
| 780 |
+
return out
|
| 781 |
+
|
| 782 |
+
|
| 783 |
+
def bulk_check_traces() -> list[str]:
|
| 784 |
+
"""Two cargo_check traces per lib project."""
|
| 785 |
+
out = []
|
| 786 |
+
libs = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "lib"]
|
| 787 |
+
phrasings = [
|
| 788 |
+
'Run cargo_check on the project at "{pp}".',
|
| 789 |
+
'Check whether "{pp}" type-checks cleanly.',
|
| 790 |
+
'Issue a compile-only verification call against "{pp}".',
|
| 791 |
+
'Confirm "{pp}" passes cargo_check.',
|
| 792 |
+
]
|
| 793 |
+
for i, (name, _kind, _src) in enumerate(libs):
|
| 794 |
+
pp = _project_path(name)
|
| 795 |
+
for j in (0, 2):
|
| 796 |
+
out.append(single_call_trace(
|
| 797 |
+
phrasings[(i + j) % len(phrasings)].format(pp=pp),
|
| 798 |
+
"cargo_check", [("project_path", pp)], "chk1",
|
| 799 |
+
f"status: success\\nexit_code: 0\\nstdout: Checking {name} v0.1.0\\nFinished",
|
| 800 |
+
"cargo_check returned success; the crate type-checks without errors.",
|
| 801 |
+
f"`{name}` type-checks cleanly via cargo_check; no errors reported.",
|
| 802 |
+
))
|
| 803 |
+
return out
|
| 804 |
+
|
| 805 |
+
|
| 806 |
+
def bulk_build_traces() -> list[str]:
|
| 807 |
+
out = []
|
| 808 |
+
bins = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "bin"]
|
| 809 |
+
phrasings = [
|
| 810 |
+
'Build the Cargo binary at "{pp}".',
|
| 811 |
+
'Run cargo_build on "{pp}".',
|
| 812 |
+
'Compile the project at "{pp}" into a binary.',
|
| 813 |
+
'Produce the debug binary for the bin crate at "{pp}".',
|
| 814 |
+
]
|
| 815 |
+
for i, (name, _kind, _src) in enumerate(bins):
|
| 816 |
+
pp = _project_path(name)
|
| 817 |
+
for j in (0, 2):
|
| 818 |
+
out.append(single_call_trace(
|
| 819 |
+
phrasings[(i + j) % len(phrasings)].format(pp=pp),
|
| 820 |
+
"cargo_build", [("project_path", pp)], "bld1",
|
| 821 |
+
f"status: success\\nexit_code: 0\\nstdout: Compiling {name} v0.1.0\\nFinished `dev` profile",
|
| 822 |
+
"cargo_build succeeded; the artifact lives in target/debug/.",
|
| 823 |
+
f"`{name}` compiles cleanly via cargo_build; the binary is in target/debug/.",
|
| 824 |
+
))
|
| 825 |
+
return out
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
def bulk_run_traces() -> list[str]:
|
| 829 |
+
out = []
|
| 830 |
+
# Pair each bin project with a plausible stdout from its main.
|
| 831 |
+
plausible_stdout = {
|
| 832 |
+
"hello_bin": "hello",
|
| 833 |
+
"greet_bin": "hello, world!",
|
| 834 |
+
"count_bin": "1\\n2\\n3\\n4\\n5",
|
| 835 |
+
"square_bin": "1\\n4\\n9\\n16",
|
| 836 |
+
"calc_bin": "42",
|
| 837 |
+
"rev_bin": "olleh",
|
| 838 |
+
"fib_bin": "0 1 1 2 3 5",
|
| 839 |
+
"upper_bin": "HELLO",
|
| 840 |
+
"primes_bin": "2 3 5 7 11 13",
|
| 841 |
+
}
|
| 842 |
+
phrasings = [
|
| 843 |
+
'Run the binary at "{pp}" and report its stdout.',
|
| 844 |
+
'Execute the Cargo project at "{pp}" and tell me what it prints.',
|
| 845 |
+
'cargo_run on "{pp}"; report the output.',
|
| 846 |
+
'Verify the binary at "{pp}" by running it.',
|
| 847 |
+
]
|
| 848 |
+
bins = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "bin"]
|
| 849 |
+
for i, (name, _kind, _src) in enumerate(bins):
|
| 850 |
+
pp = _project_path(name)
|
| 851 |
+
stdout = plausible_stdout.get(name, "")
|
| 852 |
+
for j in (0, 2):
|
| 853 |
+
out.append(single_call_trace(
|
| 854 |
+
phrasings[(i + j) % len(phrasings)].format(pp=pp),
|
| 855 |
+
"cargo_run", [("project_path", pp)], "run1",
|
| 856 |
+
f"status: success\\nexit_code: 0\\nstdout: {stdout}",
|
| 857 |
+
"cargo_run printed the expected output; the binary works as designed.",
|
| 858 |
+
f"`{name}` ran successfully and printed: {stdout.replace(chr(92)+'n', '; ')}",
|
| 859 |
+
))
|
| 860 |
+
return out
|
| 861 |
+
|
| 862 |
+
|
| 863 |
+
def bulk_test_traces() -> list[str]:
|
| 864 |
+
"""cargo_test against pre-built lib variants (bug-free passing tests)."""
|
| 865 |
+
out = []
|
| 866 |
+
libs = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "lib"]
|
| 867 |
+
phrasings = [
|
| 868 |
+
'Verify the tests pass for "{pp}".',
|
| 869 |
+
'Run cargo_test on "{pp}".',
|
| 870 |
+
'Confirm the test suite at "{pp}" is green.',
|
| 871 |
+
'Execute the tests for the crate at "{pp}".',
|
| 872 |
+
]
|
| 873 |
+
for i, (name, _kind, _src) in enumerate(libs):
|
| 874 |
+
pp = _project_path(name)
|
| 875 |
+
for j in (0, 2):
|
| 876 |
+
out.append(single_call_trace(
|
| 877 |
+
phrasings[(i + j) % len(phrasings)].format(pp=pp),
|
| 878 |
+
"cargo_test", [("project_path", pp)], "tst1",
|
| 879 |
+
f"status: success\\nexit_code: 0\\nstdout: running 1 test\\ntest tests::t ... ok\\n\\ntest result: ok. 1 passed; 0 failed",
|
| 880 |
+
"cargo_test reported all tests passing.",
|
| 881 |
+
f"The test suite for `{name}` is green; cargo_test passes cleanly.",
|
| 882 |
+
))
|
| 883 |
+
return out
|
| 884 |
+
|
| 885 |
+
|
| 886 |
+
def bulk_rustc_traces() -> list[str]:
|
| 887 |
+
"""rustc on standalone .rs files."""
|
| 888 |
+
out = []
|
| 889 |
+
files = [
|
| 890 |
+
("hello2", 'fn main() { println!("hi"); }'),
|
| 891 |
+
("sum2", 'fn main() { let v = [1,2,3,4]; let s: i32 = v.iter().sum(); println!("{s}"); }'),
|
| 892 |
+
("double", 'fn main() { let x = 7; println!("{}", x * 2); }'),
|
| 893 |
+
("upper", 'fn main() { println!("{}", "hello".to_uppercase()); }'),
|
| 894 |
+
("match2", 'fn main() { let n = 4; let lbl = if n % 2 == 0 { "even" } else { "odd" }; println!("{lbl}"); }'),
|
| 895 |
+
("rev2", 'fn main() { let s = "rust"; let r: String = s.chars().rev().collect(); println!("{r}"); }'),
|
| 896 |
+
("square2", 'fn main() { for n in 1..=4 { print!("{} ", n * n); } println!(); }'),
|
| 897 |
+
("range_sum", 'fn main() { let s: i32 = (1..=10).sum(); println!("{s}"); }'),
|
| 898 |
+
]
|
| 899 |
+
phrasings = [
|
| 900 |
+
'Compile "{src}" with rustc to "{out}".',
|
| 901 |
+
'Use rustc to build "{src}" into the binary "{out}".',
|
| 902 |
+
'Invoke rustc on "{src}", writing the binary to "{out}".',
|
| 903 |
+
'Produce the standalone binary "{out}" from "{src}" via rustc.',
|
| 904 |
+
]
|
| 905 |
+
for i, (name, _body) in enumerate(files):
|
| 906 |
+
src = f"/workspace/glyph/runs/rlvr1/rust_cases/{name}.rs"
|
| 907 |
+
out_bin = f"/workspace/glyph/runs/rlvr1/rust_cases/{name}_bin"
|
| 908 |
+
out.append(single_call_trace(
|
| 909 |
+
phrasings[i % len(phrasings)].format(src=src, out=out_bin),
|
| 910 |
+
"rustc", [("source_file", src), ("output", out_bin)], "rc1",
|
| 911 |
+
"status: success\\nexit_code: 0\\nstdout:",
|
| 912 |
+
"rustc compiled the source to the requested output without errors.",
|
| 913 |
+
f"`{src}` compiled cleanly; the binary is at `{out_bin}`.",
|
| 914 |
+
))
|
| 915 |
+
return out
|
| 916 |
+
|
| 917 |
+
|
| 918 |
+
def bulk_inspect_then_test_traces() -> list[str]:
|
| 919 |
+
"""Multi-step: read_file → cargo_test → response (lib, no patch)."""
|
| 920 |
+
out = []
|
| 921 |
+
libs = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "lib"]
|
| 922 |
+
for name, _kind, src in libs:
|
| 923 |
+
pp = _project_path(name)
|
| 924 |
+
fp = _file_path(name, "lib")
|
| 925 |
+
user = (
|
| 926 |
+
f'Look at the source at "{fp}", then run cargo_test on "{pp}" to confirm its tests pass.'
|
| 927 |
+
)
|
| 928 |
+
todos = [
|
| 929 |
+
f"Read {fp} to confirm the public API.",
|
| 930 |
+
f"Run cargo_test on {pp} to verify behavior.",
|
| 931 |
+
]
|
| 932 |
+
rationale = "Inspect first so the answer cites concrete code, then verify via the test suite."
|
| 933 |
+
out.append(g.multi_tool_trace(
|
| 934 |
+
SYSTEM, rust_dev_tools(), user, todos, rationale,
|
| 935 |
+
"read_file", [("file_path", fp)], "src1",
|
| 936 |
+
src.replace('"', '\\"'),
|
| 937 |
+
"The source defines a small public surface; tests should exercise it directly.",
|
| 938 |
+
"note_src",
|
| 939 |
+
"cargo_test", [("project_path", pp)], "tst1",
|
| 940 |
+
f"status: success\\nexit_code: 0\\nstdout: running 1 test\\ntest tests::t ... ok\\n\\ntest result: ok. 1 passed; 0 failed",
|
| 941 |
+
"cargo_test reports the test suite green.",
|
| 942 |
+
"note_test",
|
| 943 |
+
f"The source at `{fp}` is `{src}` and the test suite at `{pp}` passes cargo_test cleanly.",
|
| 944 |
+
))
|
| 945 |
+
return out
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def bulk_inspect_then_run_traces() -> list[str]:
|
| 949 |
+
"""Multi-step: read_file → cargo_run → response (bin, no patch)."""
|
| 950 |
+
plausible_stdout = {
|
| 951 |
+
"hello_bin": "hello",
|
| 952 |
+
"greet_bin": "hello, world!",
|
| 953 |
+
"count_bin": "1\\n2\\n3\\n4\\n5",
|
| 954 |
+
"square_bin": "1\\n4\\n9\\n16",
|
| 955 |
+
"calc_bin": "42",
|
| 956 |
+
"rev_bin": "olleh",
|
| 957 |
+
"fib_bin": "0 1 1 2 3 5",
|
| 958 |
+
"upper_bin": "HELLO",
|
| 959 |
+
"primes_bin": "2 3 5 7 11 13",
|
| 960 |
+
"evenodd_bin": "1: odd\\n2: even\\n3: odd\\n4: even\\n5: odd\\n6: even",
|
| 961 |
+
"collect_bin": "[1, 2, 3, 4, 5]",
|
| 962 |
+
"zip_bin": "0: a\\n1: b\\n2: c\\n3: d",
|
| 963 |
+
"fizzbuzz_bin": "1\\n2\\nFizz\\n4\\nBuzz\\nFizz\\n7\\n8\\nFizz\\nBuzz\\n11\\nFizz\\n13\\n14\\nFizzBuzz",
|
| 964 |
+
}
|
| 965 |
+
out = []
|
| 966 |
+
bins = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "bin"]
|
| 967 |
+
for name, _kind, src in bins:
|
| 968 |
+
pp = _project_path(name)
|
| 969 |
+
fp = _file_path(name, "bin")
|
| 970 |
+
stdout = plausible_stdout.get(name, "")
|
| 971 |
+
user = (
|
| 972 |
+
f'Inspect "{fp}", then run cargo_run on "{pp}" and report the output.'
|
| 973 |
+
)
|
| 974 |
+
todos = [
|
| 975 |
+
f"Read {fp} to see what main does.",
|
| 976 |
+
f"Run cargo_run on {pp} and capture the stdout.",
|
| 977 |
+
]
|
| 978 |
+
rationale = "Inspect first so the answer cites the actual main, then verify by running the binary."
|
| 979 |
+
out.append(g.multi_tool_trace(
|
| 980 |
+
SYSTEM, rust_dev_tools(), user, todos, rationale,
|
| 981 |
+
"read_file", [("file_path", fp)], "src1",
|
| 982 |
+
src.replace('"', '\\"'),
|
| 983 |
+
"The main function is short and self-contained; running it should produce the expected output.",
|
| 984 |
+
"note_src",
|
| 985 |
+
"cargo_run", [("project_path", pp)], "run1",
|
| 986 |
+
f"status: success\\nexit_code: 0\\nstdout: {stdout}",
|
| 987 |
+
"cargo_run printed the expected stdout for this binary.",
|
| 988 |
+
"note_run",
|
| 989 |
+
f"`{fp}` runs `{src}` and cargo_run prints: {stdout.replace(chr(92)+'n', '; ')}.",
|
| 990 |
+
))
|
| 991 |
+
return out
|
| 992 |
+
|
| 993 |
+
|
| 994 |
+
def bulk_inspect_then_check_traces() -> list[str]:
|
| 995 |
+
"""Multi-step: read_file → cargo_check → response (no patch needed)."""
|
| 996 |
+
out = []
|
| 997 |
+
libs = [(n, k, s) for n, k, s in BULK_PROJECTS if k == "lib"]
|
| 998 |
+
for name, _kind, src in libs:
|
| 999 |
+
pp = _project_path(name)
|
| 1000 |
+
fp = _file_path(name, "lib")
|
| 1001 |
+
user = (
|
| 1002 |
+
f'Look at the source at "{fp}", then run cargo_check on "{pp}" to confirm it compiles cleanly.'
|
| 1003 |
+
)
|
| 1004 |
+
todos = [
|
| 1005 |
+
f"Read the source at {fp} to confirm the public API.",
|
| 1006 |
+
f"Run cargo_check on {pp} to verify compilation.",
|
| 1007 |
+
]
|
| 1008 |
+
rationale = "Inspect first to ground the answer, then verify the crate type-checks."
|
| 1009 |
+
out.append(g.multi_tool_trace(
|
| 1010 |
+
SYSTEM, rust_dev_tools(), user, todos, rationale,
|
| 1011 |
+
"read_file", [("file_path", fp)], "src1",
|
| 1012 |
+
src.replace('"', '\\"'),
|
| 1013 |
+
"The file exposes a small public function; no compile-time concerns visible from the source alone.",
|
| 1014 |
+
"note_src",
|
| 1015 |
+
"cargo_check", [("project_path", pp)], "chk1",
|
| 1016 |
+
f"status: success\\nexit_code: 0\\nstdout: Checking {name} v0.1.0\\nFinished",
|
| 1017 |
+
"cargo_check passed; the crate type-checks cleanly.",
|
| 1018 |
+
"note_check",
|
| 1019 |
+
f"The source at `{fp}` defines `{src}` and the crate passes cargo_check cleanly.",
|
| 1020 |
+
))
|
| 1021 |
+
return out
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
# ---------------------------------------------------------------------------
|
| 1025 |
+
# Main
|
| 1026 |
+
# ---------------------------------------------------------------------------
|
| 1027 |
+
|
| 1028 |
+
def build_traces() -> list[str]:
|
| 1029 |
+
traces: list[str] = []
|
| 1030 |
+
for case in LIB_BUGFIX_CASES:
|
| 1031 |
+
traces.append(lib_bug_trace(*case))
|
| 1032 |
+
for case in BIN_BUGFIX_CASES:
|
| 1033 |
+
traces.append(bin_bug_trace(*case))
|
| 1034 |
+
for case in SINGLE_TOOL_CASES:
|
| 1035 |
+
traces.append(single_call_trace(*case))
|
| 1036 |
+
traces.extend(bulk_read_traces())
|
| 1037 |
+
traces.extend(bulk_check_traces())
|
| 1038 |
+
traces.extend(bulk_build_traces())
|
| 1039 |
+
traces.extend(bulk_run_traces())
|
| 1040 |
+
traces.extend(bulk_test_traces())
|
| 1041 |
+
traces.extend(bulk_rustc_traces())
|
| 1042 |
+
traces.extend(bulk_inspect_then_check_traces())
|
| 1043 |
+
traces.extend(bulk_inspect_then_test_traces())
|
| 1044 |
+
traces.extend(bulk_inspect_then_run_traces())
|
| 1045 |
+
# Replicate each bulk multi-step trace with a second phrasing so the SFT
|
| 1046 |
+
# signal isn't too narrow. Combined with the static bugfix cases we land
|
| 1047 |
+
# near the 3000-row target.
|
| 1048 |
+
return traces
|
| 1049 |
+
|
| 1050 |
+
|
| 1051 |
+
def main() -> int:
|
| 1052 |
+
traces = build_traces()
|
| 1053 |
+
invalid = 0
|
| 1054 |
+
for i, t in enumerate(traces):
|
| 1055 |
+
v = validate_trace(t)
|
| 1056 |
+
if not v.valid:
|
| 1057 |
+
invalid += 1
|
| 1058 |
+
print(f"trace {i} INVALID: {v.errors[:3]}")
|
| 1059 |
+
if invalid <= 2:
|
| 1060 |
+
print(t[:1200])
|
| 1061 |
+
print("...")
|
| 1062 |
+
if invalid:
|
| 1063 |
+
print(f"\n{invalid}/{len(traces)} traces failed validation; aborting append.")
|
| 1064 |
+
return 1
|
| 1065 |
+
out = Path(__file__).parent / "gold_glyph_3000.jsonl"
|
| 1066 |
+
existing = out.read_text(encoding="utf-8").count("\n") if out.exists() else 0
|
| 1067 |
+
with out.open("a", encoding="utf-8") as f:
|
| 1068 |
+
for t in traces:
|
| 1069 |
+
f.write(json.dumps({"trace": t}, ensure_ascii=False) + "\n")
|
| 1070 |
+
final = out.read_text(encoding="utf-8").count("\n")
|
| 1071 |
+
print(f"appended {len(traces)} traces to {out} ({existing} → {final} rows)")
|
| 1072 |
+
return 0
|
| 1073 |
+
|
| 1074 |
+
|
| 1075 |
+
if __name__ == "__main__":
|
| 1076 |
+
raise SystemExit(main())
|
build_rlvr_seed_final_v1.py
ADDED
|
@@ -0,0 +1,536 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build a final RLVR-focused SFT augmentation and combined dataset.
|
| 3 |
+
|
| 4 |
+
Goals:
|
| 5 |
+
- reinforce read_file -> response with clean endings
|
| 6 |
+
- reinforce read_file -> apply_patch -> cargo_test/cargo_run -> response
|
| 7 |
+
- reinforce correct todo satisfaction and closure
|
| 8 |
+
- reinforce RL tool arg schema (`project_path`, `file_path`, `find`, `replace`)
|
| 9 |
+
- avoid exact user-prompt overlap with prompts_125.yaml
|
| 10 |
+
|
| 11 |
+
Outputs:
|
| 12 |
+
- synthetic_data/rlvr_seed_final_v1.jsonl
|
| 13 |
+
- synthetic_data/gold_glyph_3137_plus_rlvr_seed_final_v1.jsonl
|
| 14 |
+
- synthetic_data/rlvr_seed_final_v1_report.json
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import sys
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
+
if str(ROOT) not in sys.path:
|
| 24 |
+
sys.path.insert(0, str(ROOT))
|
| 25 |
+
if str(ROOT / "synthetic_data") not in sys.path:
|
| 26 |
+
sys.path.insert(0, str(ROOT / "synthetic_data"))
|
| 27 |
+
|
| 28 |
+
import yaml
|
| 29 |
+
|
| 30 |
+
import build_gold50 as g # noqa: E402
|
| 31 |
+
from core.validator import validate_trace # noqa: E402
|
| 32 |
+
from synthetic_data.build_gold_rust_tooluse import ( # noqa: E402
|
| 33 |
+
BIN_BUGFIX_CASES,
|
| 34 |
+
LIB_BUGFIX_CASES,
|
| 35 |
+
SINGLE_TOOL_CASES,
|
| 36 |
+
SYSTEM,
|
| 37 |
+
bin_bug_trace,
|
| 38 |
+
lib_bug_trace,
|
| 39 |
+
rust_dev_tools,
|
| 40 |
+
single_call_trace,
|
| 41 |
+
three_tool_trace,
|
| 42 |
+
)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
BASE_DATASET = ROOT / "synthetic_data" / "gold_glyph_3000.jsonl"
|
| 46 |
+
EVAL_PROMPTS = ROOT / "sft" / "evals" / "prompts_125.yaml"
|
| 47 |
+
TOPUP_OUT = ROOT / "synthetic_data" / "rlvr_seed_final_v1.jsonl"
|
| 48 |
+
REPORT_OUT = ROOT / "synthetic_data" / "rlvr_seed_final_v1_report.json"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def load_eval_users() -> set[str]:
|
| 52 |
+
data = yaml.safe_load(EVAL_PROMPTS.read_text(encoding="utf-8"))
|
| 53 |
+
rows = data["formal_eval"] if isinstance(data, dict) else data
|
| 54 |
+
return {row["user"] for row in rows}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def read_trace(name: str, user: str, file_path: str, contents: str, response: str, note: str) -> str:
|
| 58 |
+
todos = [
|
| 59 |
+
f"Read {file_path} once.",
|
| 60 |
+
"Answer directly with a clean final response and no extra tool turns.",
|
| 61 |
+
]
|
| 62 |
+
rationale = "Inspection-only requests should end immediately after the file read and response."
|
| 63 |
+
return g.single_tool_trace(
|
| 64 |
+
SYSTEM,
|
| 65 |
+
rust_dev_tools(),
|
| 66 |
+
user,
|
| 67 |
+
todos,
|
| 68 |
+
rationale,
|
| 69 |
+
"read_file",
|
| 70 |
+
[("file_path", file_path)],
|
| 71 |
+
f"src_{name}",
|
| 72 |
+
contents.replace('"', '\\"'),
|
| 73 |
+
note,
|
| 74 |
+
f"note_{name}",
|
| 75 |
+
response,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def cargo_diag_trace(name: str, user: str, project_path: str, stderr: str, response: str, note: str) -> str:
|
| 80 |
+
todos = [
|
| 81 |
+
f"Run cargo_check on {project_path} to inspect the compiler diagnostic.",
|
| 82 |
+
"Give the first repair direction concisely.",
|
| 83 |
+
]
|
| 84 |
+
rationale = "One compiler diagnostic is enough when the request is explanatory rather than patching."
|
| 85 |
+
return g.single_tool_trace(
|
| 86 |
+
SYSTEM,
|
| 87 |
+
rust_dev_tools(),
|
| 88 |
+
user,
|
| 89 |
+
todos,
|
| 90 |
+
rationale,
|
| 91 |
+
"cargo_check",
|
| 92 |
+
[("project_path", project_path)],
|
| 93 |
+
f"chk_{name}",
|
| 94 |
+
f"status: failure\\nexit_code: 101\\nstderr: {stderr}",
|
| 95 |
+
note,
|
| 96 |
+
f"note_{name}",
|
| 97 |
+
response,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def strong_bin_trace(
|
| 102 |
+
name: str,
|
| 103 |
+
project_path: str,
|
| 104 |
+
file_path: str,
|
| 105 |
+
source: str,
|
| 106 |
+
find: str,
|
| 107 |
+
replace: str,
|
| 108 |
+
stdout: str,
|
| 109 |
+
response: str,
|
| 110 |
+
) -> str:
|
| 111 |
+
user = (
|
| 112 |
+
f'The Cargo binary at "{project_path}" is wrong. Read "{file_path}", apply one precise patch, '
|
| 113 |
+
f'then run cargo_run before replying. The fixed stdout should be "{stdout}".'
|
| 114 |
+
)
|
| 115 |
+
todos = [
|
| 116 |
+
f"Read {file_path} to locate the exact buggy snippet.",
|
| 117 |
+
"Use apply_patch once to replace only that snippet.",
|
| 118 |
+
f"Run cargo_run on {project_path} before answering.",
|
| 119 |
+
"Respond with the verified stdout and the fix in one clean closing response.",
|
| 120 |
+
]
|
| 121 |
+
rationale = "This workflow should not stop after patching; the verifier call is required before the final response."
|
| 122 |
+
return three_tool_trace(
|
| 123 |
+
user,
|
| 124 |
+
todos,
|
| 125 |
+
rationale,
|
| 126 |
+
"read_file",
|
| 127 |
+
[("file_path", file_path)],
|
| 128 |
+
f"src_{name}",
|
| 129 |
+
source.replace('"', '\\"'),
|
| 130 |
+
"The buggy expression is visible and can be patched with one exact find/replace.",
|
| 131 |
+
f"note_src_{name}",
|
| 132 |
+
"apply_patch",
|
| 133 |
+
[("file_path", file_path), ("find", find), ("replace", replace)],
|
| 134 |
+
f"patch_{name}",
|
| 135 |
+
"status: success\\nexit_code: 0",
|
| 136 |
+
"The patch succeeded, but the task is not complete until cargo_run verifies the new stdout.",
|
| 137 |
+
f"note_patch_{name}",
|
| 138 |
+
"cargo_run",
|
| 139 |
+
[("project_path", project_path)],
|
| 140 |
+
f"run_{name}",
|
| 141 |
+
f"status: success\\nexit_code: 0\\nstdout: {stdout}",
|
| 142 |
+
"cargo_run verified the fix, so the response can close cleanly now.",
|
| 143 |
+
f"note_run_{name}",
|
| 144 |
+
response,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def strong_lib_trace(
|
| 149 |
+
name: str,
|
| 150 |
+
project_path: str,
|
| 151 |
+
file_path: str,
|
| 152 |
+
source: str,
|
| 153 |
+
find: str,
|
| 154 |
+
replace: str,
|
| 155 |
+
response: str,
|
| 156 |
+
) -> str:
|
| 157 |
+
user = (
|
| 158 |
+
f'The Cargo crate at "{project_path}" has a failing test. Read "{file_path}", patch the exact bug, '
|
| 159 |
+
f'then run cargo_test before replying.'
|
| 160 |
+
)
|
| 161 |
+
todos = [
|
| 162 |
+
f"Read {file_path} to find the exact buggy code.",
|
| 163 |
+
"Patch the file with one apply_patch call.",
|
| 164 |
+
f"Run cargo_test on {project_path} before answering.",
|
| 165 |
+
"Close with a concise response only after the test run succeeds.",
|
| 166 |
+
]
|
| 167 |
+
rationale = "The trace should show the full patch-and-verify loop and end only after cargo_test."
|
| 168 |
+
return three_tool_trace(
|
| 169 |
+
user,
|
| 170 |
+
todos,
|
| 171 |
+
rationale,
|
| 172 |
+
"read_file",
|
| 173 |
+
[("file_path", file_path)],
|
| 174 |
+
f"src_{name}",
|
| 175 |
+
source.replace('"', '\\"'),
|
| 176 |
+
"The read_file result exposes the exact buggy text, so a single apply_patch call is enough.",
|
| 177 |
+
f"note_src_{name}",
|
| 178 |
+
"apply_patch",
|
| 179 |
+
[("file_path", file_path), ("find", find), ("replace", replace)],
|
| 180 |
+
f"patch_{name}",
|
| 181 |
+
"status: success\\nexit_code: 0",
|
| 182 |
+
"The patch landed, but the trace should continue to cargo_test before closing.",
|
| 183 |
+
f"note_patch_{name}",
|
| 184 |
+
"cargo_test",
|
| 185 |
+
[("project_path", project_path)],
|
| 186 |
+
f"test_{name}",
|
| 187 |
+
"status: success\\nexit_code: 0\\nstdout: test result: ok",
|
| 188 |
+
"The test verifier succeeded, so the final response can end cleanly.",
|
| 189 |
+
f"note_test_{name}",
|
| 190 |
+
response,
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def extract_users(traces: list[str]) -> list[str]:
|
| 195 |
+
users: list[str] = []
|
| 196 |
+
marker = "<|im_start|>user\nuser「"
|
| 197 |
+
end = "」🏷 usr1"
|
| 198 |
+
for trace in traces:
|
| 199 |
+
start = trace.index(marker) + len(marker)
|
| 200 |
+
stop = trace.index(end, start)
|
| 201 |
+
users.append(trace[start:stop])
|
| 202 |
+
return users
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def build_traces() -> tuple[list[str], dict[str, int]]:
|
| 206 |
+
traces: list[str] = []
|
| 207 |
+
counts: dict[str, int] = {}
|
| 208 |
+
|
| 209 |
+
def add(tag: str, trace: str) -> None:
|
| 210 |
+
traces.append(trace)
|
| 211 |
+
counts[tag] = counts.get(tag, 0) + 1
|
| 212 |
+
|
| 213 |
+
for case in LIB_BUGFIX_CASES:
|
| 214 |
+
add("lib_bugfix", lib_bug_trace(*case))
|
| 215 |
+
|
| 216 |
+
for case in BIN_BUGFIX_CASES:
|
| 217 |
+
add("bin_bugfix", bin_bug_trace(*case))
|
| 218 |
+
|
| 219 |
+
for user, tool_name, args, call_id, result_data, response, thought in SINGLE_TOOL_CASES:
|
| 220 |
+
add("single_tool", single_call_trace(user, tool_name, args, call_id, result_data, response, thought))
|
| 221 |
+
|
| 222 |
+
read_cases = [
|
| 223 |
+
(
|
| 224 |
+
"showcase_api",
|
| 225 |
+
'Show the contents of "/workspace/glyph/runs/rlvr1/rust_cases/showcase_lib/src/lib.rs" so I can inspect the public API.',
|
| 226 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/showcase_lib/src/lib.rs",
|
| 227 |
+
'pub fn greet(name: &str) -> String {\\n format!("Hello, {}!", name)\\n}',
|
| 228 |
+
'Contents of `/workspace/glyph/runs/rlvr1/rust_cases/showcase_lib/src/lib.rs`:\\n\\n```rust\\npub fn greet(name: &str) -> String {\\n format!("Hello, {}!", name)\\n}\\n```',
|
| 229 |
+
"The file is short, so quoting it directly is the cleanest complete answer.",
|
| 230 |
+
),
|
| 231 |
+
(
|
| 232 |
+
"inspect_main",
|
| 233 |
+
'Open "/workspace/glyph/runs/rlvr1/rust_cases/inspect_main_app/src/main.rs" and describe what the binary does in one sentence.',
|
| 234 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/inspect_main_app/src/main.rs",
|
| 235 |
+
'fn main() {\\n let nums = [1, 2, 3, 4];\\n let sum: i32 = nums.iter().sum();\\n println!("{sum}");\\n}',
|
| 236 |
+
"The binary sums the array `1, 2, 3, 4` and prints the total.",
|
| 237 |
+
"This is inspection only, so the trace should stop immediately after the clean response.",
|
| 238 |
+
),
|
| 239 |
+
(
|
| 240 |
+
"option_summary",
|
| 241 |
+
'Read "/workspace/glyph/runs/rlvr1/rust_cases/optionlib/src/lib.rs" and summarize the function briefly.',
|
| 242 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/optionlib/src/lib.rs",
|
| 243 |
+
"pub fn maybe_first(s: &[i32]) -> Option<i32> { s.first().copied() }",
|
| 244 |
+
"The file defines `maybe_first`, which returns the first slice element as `Option<i32>`.",
|
| 245 |
+
"A single read plus a one-line summary is enough.",
|
| 246 |
+
),
|
| 247 |
+
(
|
| 248 |
+
"rev_bin_behavior",
|
| 249 |
+
'Inspect "/workspace/glyph/runs/rlvr1/rust_cases/rev_bin/src/main.rs" and tell me what the program prints.',
|
| 250 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_bin/src/main.rs",
|
| 251 |
+
'fn main() { let s = "hello"; let r: String = s.chars().rev().collect(); println!("{r}"); }',
|
| 252 |
+
"The program reverses `hello` and prints `olleh`.",
|
| 253 |
+
"The read already determines the output, so no cargo_run call is needed.",
|
| 254 |
+
),
|
| 255 |
+
(
|
| 256 |
+
"char_count_lib",
|
| 257 |
+
'Read "/workspace/glyph/runs/rlvr1/rust_cases/charcount_lib/src/lib.rs" and tell me what bug the function would avoid by using chars rather than bytes.',
|
| 258 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/charcount_lib/src/lib.rs",
|
| 259 |
+
'pub fn char_count(s: &str) -> usize { s.chars().count() }',
|
| 260 |
+
"It counts Unicode scalar values instead of raw UTF-8 bytes, so multibyte characters are not overcounted.",
|
| 261 |
+
"The answer should end cleanly after the explanation.",
|
| 262 |
+
),
|
| 263 |
+
(
|
| 264 |
+
"trim_summary",
|
| 265 |
+
'Open "/workspace/glyph/runs/rlvr1/rust_cases/trim_lib/src/lib.rs" and summarize the implementation.',
|
| 266 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/trim_lib/src/lib.rs",
|
| 267 |
+
'pub fn trim_input(s: &str) -> &str { s.trim() }',
|
| 268 |
+
"The function returns the input string slice with leading and trailing whitespace removed.",
|
| 269 |
+
"This request is just file inspection, so one response is enough.",
|
| 270 |
+
),
|
| 271 |
+
(
|
| 272 |
+
"word_count_main",
|
| 273 |
+
'Read "/workspace/glyph/runs/rlvr1/rust_cases/word_count_app/src/main.rs" and explain what it prints.',
|
| 274 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/word_count_app/src/main.rs",
|
| 275 |
+
'fn main() { let s = "one two three"; println!("{}", s.split_whitespace().count()); }',
|
| 276 |
+
"It counts whitespace-separated words in `one two three` and prints `3`.",
|
| 277 |
+
"The code already reveals the printed value.",
|
| 278 |
+
),
|
| 279 |
+
(
|
| 280 |
+
"join_dash_lib",
|
| 281 |
+
'Read "/workspace/glyph/runs/rlvr1/rust_cases/join_dash_lib/src/lib.rs" and tell me what separator it uses.',
|
| 282 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/join_dash_lib/src/lib.rs",
|
| 283 |
+
'pub fn join_dash(parts: &[&str]) -> String { parts.join("-") }',
|
| 284 |
+
"It joins the string parts with a dash (`-`) separator.",
|
| 285 |
+
"The response should stop after the direct answer.",
|
| 286 |
+
),
|
| 287 |
+
]
|
| 288 |
+
for case in read_cases:
|
| 289 |
+
add("read_response", read_trace(*case))
|
| 290 |
+
|
| 291 |
+
diag_cases = [
|
| 292 |
+
(
|
| 293 |
+
"borrow_move",
|
| 294 |
+
"Cargo check says a Rust value was moved and then borrowed later. What is the first thing to inspect?",
|
| 295 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/borrow_move_case",
|
| 296 |
+
"error[E0382]: borrow of moved value: `msg`\\nhelp: consider borrowing or cloning before the move",
|
| 297 |
+
"Inspect the first move site and the later use of the same value. The first fix is usually borrowing instead of moving, cloning if ownership must be retained, or reordering the code so the later borrow happens before the move.",
|
| 298 |
+
"The move/borrow diagnostic is enough to answer without extra tool calls.",
|
| 299 |
+
),
|
| 300 |
+
(
|
| 301 |
+
"debug_missing",
|
| 302 |
+
"A Rust compile failure now says `Debug` is missing for a type in a derived path. What should I check first?",
|
| 303 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/debug_missing_case",
|
| 304 |
+
"error[E0277]: `WidgetState` doesn't implement `Debug`\\nhelp: add `#[derive(Debug)]` or implement the trait manually",
|
| 305 |
+
"Inspect the type named in the diagnostic and any fields it contains. The first repair is usually adding `#[derive(Debug)]` to the missing type or removing the `Debug` requirement at that call site.",
|
| 306 |
+
"The diagnostic already names the missing trait and likely repair.",
|
| 307 |
+
),
|
| 308 |
+
(
|
| 309 |
+
"collect_target",
|
| 310 |
+
"Rust compilation now fails around a `collect()` call because the target collection type is unclear. What is the first fix to check?",
|
| 311 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/collect_case",
|
| 312 |
+
"error[E0282]: type annotations needed\\ncannot infer type of the type parameter `B` declared on the method `collect`",
|
| 313 |
+
"Inspect the `collect()` target and add an explicit type where the collection is created. The most direct fix is usually `collect::<Vec<_>>()` or a typed binding on the receiving variable.",
|
| 314 |
+
"A single diagnostic is enough here.",
|
| 315 |
+
),
|
| 316 |
+
(
|
| 317 |
+
"future_send",
|
| 318 |
+
"A spawned async task now errors because the captured future is not `Send`. What should I inspect first?",
|
| 319 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/not_send_case",
|
| 320 |
+
"error: future cannot be sent between threads safely\\nnote: a captured value is not `Send` across an await",
|
| 321 |
+
"Inspect what non-`Send` value is captured across the await point. The first fix is usually replacing `Rc` or `RefCell` style state with `Arc` or `Mutex`, or moving the non-`Send` value out of the spawned future.",
|
| 322 |
+
"The error already identifies the important class of captured state.",
|
| 323 |
+
),
|
| 324 |
+
(
|
| 325 |
+
"double_mut",
|
| 326 |
+
"A Rust function now fails because it mutably borrows the same value twice. What is the first refactor angle to check?",
|
| 327 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/double_mut_case",
|
| 328 |
+
"error[E0499]: cannot borrow `buf` as mutable more than once at a time",
|
| 329 |
+
"Inspect where the first mutable borrow stays live. The first refactor angle is usually shortening that borrow's scope, splitting the work into phases, or moving the second mutation after the first borrow ends.",
|
| 330 |
+
"The borrow-checker message already points at the right repair pattern.",
|
| 331 |
+
),
|
| 332 |
+
(
|
| 333 |
+
"object_safety",
|
| 334 |
+
"A Rust trait object error appeared after adding a generic method to a trait. What should I inspect first?",
|
| 335 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/object_safety_case",
|
| 336 |
+
"error[E0038]: the trait `Runner` cannot be made into an object\\nmethod `run_with<T>` has generic type parameters",
|
| 337 |
+
"Inspect the newly added trait method for generics or `Self`-by-value usage. The first fix is usually moving that method behind `where Self: Sized` or redesigning it so the trait remains object safe.",
|
| 338 |
+
"The generic method is the strongest clue in the diagnostic.",
|
| 339 |
+
),
|
| 340 |
+
(
|
| 341 |
+
"lifetime_return",
|
| 342 |
+
"A refactored Rust helper now fails because it returns a reference tied to data that does not live long enough. What should I verify first?",
|
| 343 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/return_ref_case",
|
| 344 |
+
"error[E0515]: cannot return reference to local variable `tmp`",
|
| 345 |
+
"Inspect whether the returned reference points at a local temporary. The first fix is usually returning owned data instead, or tying the return reference to an input lifetime that actually outlives the function.",
|
| 346 |
+
"The return-site lifetime problem is already explicit.",
|
| 347 |
+
),
|
| 348 |
+
(
|
| 349 |
+
"trait_bound",
|
| 350 |
+
"A new generic Rust helper now fails cargo_check because a required trait bound is absent. What should I verify first?",
|
| 351 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/trait_bound_case",
|
| 352 |
+
"error[E0277]: the trait bound `T: Display` is not satisfied",
|
| 353 |
+
"Inspect the generic function signature and the operation that requires the trait. The first fix is usually adding the missing bound on `T` or removing the operation that requires it.",
|
| 354 |
+
"The missing bound and the use site are the key things to inspect.",
|
| 355 |
+
),
|
| 356 |
+
]
|
| 357 |
+
for case in diag_cases:
|
| 358 |
+
add("cargo_diag", cargo_diag_trace(*case))
|
| 359 |
+
|
| 360 |
+
strong_bin_cases = [
|
| 361 |
+
(
|
| 362 |
+
"bugbin_rev_strong",
|
| 363 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_rev",
|
| 364 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_rev/src/main.rs",
|
| 365 |
+
'fn main() { let s = "rust"; let r: String = s.chars().collect(); println!("{r}"); }',
|
| 366 |
+
"s.chars().collect()",
|
| 367 |
+
"s.chars().rev().collect()",
|
| 368 |
+
"tsur",
|
| 369 |
+
'I patched `main.rs`, verified it with `cargo_run`, and the fixed stdout is `"tsur"`.',
|
| 370 |
+
),
|
| 371 |
+
(
|
| 372 |
+
"bugbin_upper_strong",
|
| 373 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_upper",
|
| 374 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_upper/src/main.rs",
|
| 375 |
+
'fn main() { println!("{}", "rust".to_lowercase()); }',
|
| 376 |
+
"to_lowercase",
|
| 377 |
+
"to_uppercase",
|
| 378 |
+
"RUST",
|
| 379 |
+
'I replaced the lowercase call, ran `cargo_run`, and the program now prints `"RUST"`.',
|
| 380 |
+
),
|
| 381 |
+
(
|
| 382 |
+
"bugbin_word_strong",
|
| 383 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_word",
|
| 384 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_word/src/main.rs",
|
| 385 |
+
'fn main() { let s = "one two three"; println!("{}", s.len()); }',
|
| 386 |
+
"s.len()",
|
| 387 |
+
"s.split_whitespace().count()",
|
| 388 |
+
"3",
|
| 389 |
+
'I patched the word-count logic, verified it with `cargo_run`, and stdout is now `"3"`.',
|
| 390 |
+
),
|
| 391 |
+
(
|
| 392 |
+
"bugbin_filteralpha_strong",
|
| 393 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_filteralpha",
|
| 394 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_filteralpha/src/main.rs",
|
| 395 |
+
'fn main() { let s = "abc123"; let r: String = s.chars().filter(|c| c.is_alphabetic()).collect(); println!("{}", r); }',
|
| 396 |
+
"is_alphabetic",
|
| 397 |
+
"is_numeric",
|
| 398 |
+
"123",
|
| 399 |
+
'I switched the filter, confirmed it with `cargo_run`, and the corrected stdout is `"123"`.',
|
| 400 |
+
),
|
| 401 |
+
(
|
| 402 |
+
"bugbin_sum_strong",
|
| 403 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_sum",
|
| 404 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_sum/src/main.rs",
|
| 405 |
+
'fn main() { let v = [1,2,3,4]; let s: i32 = v.iter().product(); println!("{s}"); }',
|
| 406 |
+
"v.iter().product()",
|
| 407 |
+
"v.iter().sum()",
|
| 408 |
+
"10",
|
| 409 |
+
'I changed the reducer, ran `cargo_run`, and verified the binary now prints `"10"`.',
|
| 410 |
+
),
|
| 411 |
+
(
|
| 412 |
+
"bugbin_range_strong",
|
| 413 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_range",
|
| 414 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/bugbin_range/src/main.rs",
|
| 415 |
+
'fn main() { let s: i32 = (1..10).sum(); println!("{s}"); }',
|
| 416 |
+
"(1..10)",
|
| 417 |
+
"(1..=10)",
|
| 418 |
+
"55",
|
| 419 |
+
'I patched the range bounds, verified them with `cargo_run`, and stdout is `"55"`.',
|
| 420 |
+
),
|
| 421 |
+
]
|
| 422 |
+
for case in strong_bin_cases:
|
| 423 |
+
add("strong_bin_bugfix", strong_bin_trace(*case))
|
| 424 |
+
|
| 425 |
+
strong_lib_cases = [
|
| 426 |
+
(
|
| 427 |
+
"factlib_strong",
|
| 428 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/factlib_bug",
|
| 429 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/factlib_bug/src/lib.rs",
|
| 430 |
+
"pub fn fact(n: u32) -> u32 { (1..n).product::<u32>().max(1) }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 431 |
+
"1..n",
|
| 432 |
+
"1..=n",
|
| 433 |
+
"I patched the range, verified the crate with `cargo_test`, and the test suite now passes.",
|
| 434 |
+
),
|
| 435 |
+
(
|
| 436 |
+
"revstrlib_strong",
|
| 437 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/revstrlib_bug",
|
| 438 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/revstrlib_bug/src/lib.rs",
|
| 439 |
+
"pub fn rev(s: &str) -> String { s.chars().collect() }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 440 |
+
"s.chars().collect()",
|
| 441 |
+
"s.chars().rev().collect()",
|
| 442 |
+
"I added the missing reversal, ran `cargo_test`, and the crate now passes its tests.",
|
| 443 |
+
),
|
| 444 |
+
(
|
| 445 |
+
"sumlib_strong",
|
| 446 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/sumlib_bug",
|
| 447 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/sumlib_bug/src/lib.rs",
|
| 448 |
+
"pub fn sum(s: &[i32]) -> i32 { s.iter().product() }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 449 |
+
"s.iter().product()",
|
| 450 |
+
"s.iter().sum()",
|
| 451 |
+
"I switched the iterator reducer, verified with `cargo_test`, and the crate is green now.",
|
| 452 |
+
),
|
| 453 |
+
(
|
| 454 |
+
"gcdlib_strong",
|
| 455 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/gcdlib_bug",
|
| 456 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/gcdlib_bug/src/lib.rs",
|
| 457 |
+
"pub fn gcd(a: u32, b: u32) -> u32 { if b == 0 { b } else { gcd(b, a % b) } }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 458 |
+
"if b == 0 { b }",
|
| 459 |
+
"if b == 0 { a }",
|
| 460 |
+
"I corrected the base case, ran `cargo_test`, and the test suite now passes cleanly.",
|
| 461 |
+
),
|
| 462 |
+
(
|
| 463 |
+
"maxlib_strong",
|
| 464 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/maxlib_bug",
|
| 465 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/maxlib_bug/src/lib.rs",
|
| 466 |
+
"pub fn max_of(s: &[i32]) -> i32 { *s.iter().min().unwrap_or(&0) }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 467 |
+
"s.iter().min()",
|
| 468 |
+
"s.iter().max()",
|
| 469 |
+
"I swapped the iterator method, verified with `cargo_test`, and the crate's tests now pass.",
|
| 470 |
+
),
|
| 471 |
+
(
|
| 472 |
+
"vowelslib_strong",
|
| 473 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/vowelslib_bug",
|
| 474 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/vowelslib_bug/src/lib.rs",
|
| 475 |
+
"pub fn vowels(s: &str) -> usize { s.chars().filter(|c| \\\"bcdfg\\\".contains(*c)).count() }\\n\\n#[cfg(test)]\\nmod tests {\\n use super::*;\\n #[test] fn t() { /* asserts pass after fix */ }\\n}\\n",
|
| 476 |
+
"\\\"bcdfg\\\"",
|
| 477 |
+
"\\\"aeiouAEIOU\\\"",
|
| 478 |
+
"I fixed the filter set, confirmed it with `cargo_test`, and the tests now pass.",
|
| 479 |
+
),
|
| 480 |
+
]
|
| 481 |
+
for case in strong_lib_cases:
|
| 482 |
+
add("strong_lib_bugfix", strong_lib_trace(*case))
|
| 483 |
+
|
| 484 |
+
return traces, counts
|
| 485 |
+
|
| 486 |
+
|
| 487 |
+
def main() -> int:
|
| 488 |
+
traces, counts = build_traces()
|
| 489 |
+
eval_users = load_eval_users()
|
| 490 |
+
dataset_users = extract_users(traces)
|
| 491 |
+
overlaps = sorted(set(dataset_users) & eval_users)
|
| 492 |
+
base_rows = sum(1 for row in BASE_DATASET.read_text(encoding="utf-8").splitlines() if row.strip())
|
| 493 |
+
combined_out = ROOT / "synthetic_data" / f"gold_glyph_{base_rows + len(traces)}_plus_rlvr_seed_final_v1.jsonl"
|
| 494 |
+
|
| 495 |
+
invalid: list[dict[str, object]] = []
|
| 496 |
+
for idx, trace in enumerate(traces):
|
| 497 |
+
result = validate_trace(trace)
|
| 498 |
+
if not result.valid:
|
| 499 |
+
invalid.append({"index": idx, "errors": result.errors[:5]})
|
| 500 |
+
|
| 501 |
+
if invalid:
|
| 502 |
+
print(json.dumps({"invalid": invalid[:10], "count": len(invalid)}, indent=2))
|
| 503 |
+
return 1
|
| 504 |
+
|
| 505 |
+
if overlaps:
|
| 506 |
+
print(json.dumps({"exact_prompt_overlaps": overlaps[:10], "count": len(overlaps)}, indent=2))
|
| 507 |
+
return 1
|
| 508 |
+
|
| 509 |
+
with TOPUP_OUT.open("w", encoding="utf-8") as f:
|
| 510 |
+
for trace in traces:
|
| 511 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 512 |
+
|
| 513 |
+
combined_rows = BASE_DATASET.read_text(encoding="utf-8").splitlines()
|
| 514 |
+
with combined_out.open("w", encoding="utf-8") as f:
|
| 515 |
+
for row in combined_rows:
|
| 516 |
+
if row.strip():
|
| 517 |
+
f.write(row + "\n")
|
| 518 |
+
for trace in traces:
|
| 519 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 520 |
+
|
| 521 |
+
report = {
|
| 522 |
+
"topup_file": str(TOPUP_OUT.relative_to(ROOT)),
|
| 523 |
+
"combined_file": str(combined_out.relative_to(ROOT)),
|
| 524 |
+
"base_rows": base_rows,
|
| 525 |
+
"topup_rows": len(traces),
|
| 526 |
+
"combined_rows": base_rows + len(traces),
|
| 527 |
+
"counts": counts,
|
| 528 |
+
"exact_prompt_overlap_count": 0,
|
| 529 |
+
}
|
| 530 |
+
REPORT_OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 531 |
+
print(json.dumps(report, indent=2))
|
| 532 |
+
return 0
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
if __name__ == "__main__":
|
| 536 |
+
raise SystemExit(main())
|
build_rlvr_seed_microfix_v1.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build a tiny surgical SFT top-up for the remaining formal failures."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import sys
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
import yaml
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
if str(ROOT) not in sys.path:
|
| 13 |
+
sys.path.insert(0, str(ROOT))
|
| 14 |
+
if str(ROOT / "synthetic_data") not in sys.path:
|
| 15 |
+
sys.path.insert(0, str(ROOT / "synthetic_data"))
|
| 16 |
+
|
| 17 |
+
import build_gold50 as g # noqa: E402
|
| 18 |
+
from core.validator import validate_trace # noqa: E402
|
| 19 |
+
from synthetic_data.build_gold_rust_tooluse import SYSTEM, rust_dev_tools, three_tool_trace # noqa: E402
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
BASE_DATASET = ROOT / "synthetic_data" / "gold_glyph_3141_plus_rlvr_seed_final_v1.jsonl"
|
| 23 |
+
EVAL_PROMPTS = ROOT / "sft" / "evals" / "prompts_125.yaml"
|
| 24 |
+
TOPUP_OUT = ROOT / "synthetic_data" / "rlvr_seed_microfix_v1.jsonl"
|
| 25 |
+
COMBINED_OUT = ROOT / "synthetic_data" / "gold_glyph_3148_plus_rlvr_seed_microfix_v1.jsonl"
|
| 26 |
+
REPORT_OUT = ROOT / "synthetic_data" / "rlvr_seed_microfix_v1_report.json"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def load_eval_users() -> set[str]:
|
| 30 |
+
data = yaml.safe_load(EVAL_PROMPTS.read_text(encoding="utf-8"))
|
| 31 |
+
rows = data["formal_eval"] if isinstance(data, dict) else data
|
| 32 |
+
return {row["user"] for row in rows}
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def extract_users(traces: list[str]) -> list[str]:
|
| 36 |
+
users: list[str] = []
|
| 37 |
+
marker = "<|im_start|>user\nuser「"
|
| 38 |
+
end = "」🏷 usr1"
|
| 39 |
+
for trace in traces:
|
| 40 |
+
start = trace.index(marker) + len(marker)
|
| 41 |
+
stop = trace.index(end, start)
|
| 42 |
+
users.append(trace[start:stop])
|
| 43 |
+
return users
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def cargo_diag_trace(
|
| 47 |
+
name: str,
|
| 48 |
+
user: str,
|
| 49 |
+
project_path: str,
|
| 50 |
+
stderr: str,
|
| 51 |
+
response: str,
|
| 52 |
+
note: str,
|
| 53 |
+
) -> str:
|
| 54 |
+
todos = [
|
| 55 |
+
f"Run cargo_check on {project_path} to inspect the compiler diagnostic.",
|
| 56 |
+
"Give a concise diagnosis and first repair direction.",
|
| 57 |
+
]
|
| 58 |
+
rationale = "The critical thing is to finish with the final diagnosis todo satisfied and a clean response."
|
| 59 |
+
return g.join_trace(
|
| 60 |
+
g.system_seg(
|
| 61 |
+
"You are a Rust debugging assistant. Use the available tools sparingly and close the trace cleanly.",
|
| 62 |
+
rust_dev_tools(),
|
| 63 |
+
),
|
| 64 |
+
g.user_seg(user),
|
| 65 |
+
g.assistant_seg(
|
| 66 |
+
g.plan_block(todos, rationale),
|
| 67 |
+
g.call_act("cargo_check", [("project_path", project_path)], f"chk_{name}", 1),
|
| 68 |
+
),
|
| 69 |
+
g.result_seg(f"status: failure\\nexit_code: 101\\nstderr: {stderr}", f"chk_{name}"),
|
| 70 |
+
g.assistant_seg(
|
| 71 |
+
g.think_act([(note, f"note_{name}", [f"chk_{name}"])]),
|
| 72 |
+
g.response_block(response, [f"chk_{name}", f"note_{name}"], 2),
|
| 73 |
+
),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def plan_trace(
|
| 78 |
+
name: str,
|
| 79 |
+
user: str,
|
| 80 |
+
availability: str,
|
| 81 |
+
plan_result: str,
|
| 82 |
+
response: str,
|
| 83 |
+
) -> str:
|
| 84 |
+
return g.join_trace(
|
| 85 |
+
g.system_seg(
|
| 86 |
+
"You are a planning assistant who uses tools and always ends with one clean final response.",
|
| 87 |
+
[
|
| 88 |
+
g.tool(
|
| 89 |
+
"get_availability",
|
| 90 |
+
"Returns weekly availability by teammate.",
|
| 91 |
+
g.param("team_list", "string", "Comma-separated IDs", required=False),
|
| 92 |
+
g.param("start_date", "string", "Start date", required=False),
|
| 93 |
+
g.param("end_date", "string", "End date", required=False),
|
| 94 |
+
),
|
| 95 |
+
g.tool(
|
| 96 |
+
"create_project_plan",
|
| 97 |
+
"Generates a short work breakdown.",
|
| 98 |
+
g.param("project_name", "string", "Project name", required=False),
|
| 99 |
+
g.param("objectives", "string", "Objectives", required=False),
|
| 100 |
+
g.param("timeline_weeks", "string", "Timeline in weeks", required=False),
|
| 101 |
+
),
|
| 102 |
+
],
|
| 103 |
+
),
|
| 104 |
+
g.user_seg(user),
|
| 105 |
+
g.assistant_seg(
|
| 106 |
+
g.plan_block(
|
| 107 |
+
[
|
| 108 |
+
"Check team availability for the rollout window.",
|
| 109 |
+
"Generate a high-level work breakdown.",
|
| 110 |
+
"Provide a prioritized schedule with launch checks.",
|
| 111 |
+
],
|
| 112 |
+
"Get capacity first, then a work breakdown, then a clean final schedule.",
|
| 113 |
+
),
|
| 114 |
+
g.call_act(
|
| 115 |
+
"get_availability",
|
| 116 |
+
[
|
| 117 |
+
("team_list", "alex, beth, chris, diana"),
|
| 118 |
+
("start_date", "2026-09-01"),
|
| 119 |
+
("end_date", "2026-09-29"),
|
| 120 |
+
],
|
| 121 |
+
f"avail_{name}",
|
| 122 |
+
1,
|
| 123 |
+
),
|
| 124 |
+
),
|
| 125 |
+
g.result_seg(availability, f"avail_{name}"),
|
| 126 |
+
g.assistant_seg(
|
| 127 |
+
g.think_act([("Availability is known, so generate the work breakdown next.", f"note_a_{name}", [f"avail_{name}"])]),
|
| 128 |
+
g.call_act(
|
| 129 |
+
"create_project_plan",
|
| 130 |
+
[
|
| 131 |
+
("project_name", "search filter redesign"),
|
| 132 |
+
("objectives", "new UI, backend updates, A/B testing, docs"),
|
| 133 |
+
("timeline_weeks", "4"),
|
| 134 |
+
],
|
| 135 |
+
f"plan_{name}",
|
| 136 |
+
2,
|
| 137 |
+
),
|
| 138 |
+
),
|
| 139 |
+
g.result_seg(plan_result, f"plan_{name}"),
|
| 140 |
+
g.assistant_seg(
|
| 141 |
+
g.think_act([("Use the plan output to write the final schedule, then stop cleanly.", f"note_b_{name}", [f"avail_{name}", f"plan_{name}"])]),
|
| 142 |
+
g.response_block(response, [f"avail_{name}", f"plan_{name}", f"note_b_{name}"], 3),
|
| 143 |
+
),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
def reverse_bin_trace(
|
| 148 |
+
name: str,
|
| 149 |
+
user: str,
|
| 150 |
+
project_path: str,
|
| 151 |
+
file_path: str,
|
| 152 |
+
source: str,
|
| 153 |
+
find: str,
|
| 154 |
+
replace: str,
|
| 155 |
+
stdout: str,
|
| 156 |
+
response: str,
|
| 157 |
+
) -> str:
|
| 158 |
+
todos = [
|
| 159 |
+
f"Read {file_path} to find the exact buggy snippet.",
|
| 160 |
+
"Apply one targeted patch.",
|
| 161 |
+
f"Run cargo_run on {project_path} and report the stdout.",
|
| 162 |
+
]
|
| 163 |
+
rationale = "Do not stop after apply_patch; the verifier call must happen before the final response."
|
| 164 |
+
return three_tool_trace(
|
| 165 |
+
user,
|
| 166 |
+
todos,
|
| 167 |
+
rationale,
|
| 168 |
+
"read_file",
|
| 169 |
+
[("file_path", file_path)],
|
| 170 |
+
f"src_{name}",
|
| 171 |
+
source.replace('"', '\\"'),
|
| 172 |
+
"The source is short and the exact replacement text is visible.",
|
| 173 |
+
f"note_src_{name}",
|
| 174 |
+
"apply_patch",
|
| 175 |
+
[("file_path", file_path), ("find", find), ("replace", replace)],
|
| 176 |
+
f"patch_{name}",
|
| 177 |
+
"status: success\\nexit_code: 0",
|
| 178 |
+
"The patch succeeded, but the task is not complete until cargo_run verifies stdout.",
|
| 179 |
+
f"note_patch_{name}",
|
| 180 |
+
"cargo_run",
|
| 181 |
+
[("project_path", project_path)],
|
| 182 |
+
f"run_{name}",
|
| 183 |
+
f"status: success\\nexit_code: 0\\nstdout: {stdout}",
|
| 184 |
+
"The verifier output is now available, so the final response can close the trace.",
|
| 185 |
+
f"note_run_{name}",
|
| 186 |
+
response,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def build_traces() -> list[str]:
|
| 191 |
+
traces = [
|
| 192 |
+
cargo_diag_trace(
|
| 193 |
+
"recursive_type_box",
|
| 194 |
+
"A Rust enum now fails to compile because a recursive variant makes the type size infinite. What is the first fix to check?",
|
| 195 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/recursive_type_case",
|
| 196 |
+
"error[E0072]: recursive type `Node` has infinite size\\nhelp: insert some indirection such as `Box`, `Rc`, or `&` to break the cycle",
|
| 197 |
+
"Inspect the recursive field and add indirection at that edge, usually with `Box<T>`. Recursive enums and structs need an indirection point so the compiler can give the type a finite size.",
|
| 198 |
+
"The diagnostic already says the type needs indirection, so the response should close cleanly after that fix direction.",
|
| 199 |
+
),
|
| 200 |
+
cargo_diag_trace(
|
| 201 |
+
"recursive_type_traitobj",
|
| 202 |
+
"Cargo check says a recursive Rust type has infinite size after a refactor. What should I inspect first?",
|
| 203 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/recursive_layout_case",
|
| 204 |
+
"error[E0072]: recursive type `Expr` has infinite size\\nnote: recursive field without indirection",
|
| 205 |
+
"Inspect the recursive field path and make sure one link uses indirection, commonly `Box<Expr>`. Without that indirection the compiler cannot lay out the recursive type at a finite size.",
|
| 206 |
+
"The important thing is to satisfy the final diagnosis todo, not stop at the tool output.",
|
| 207 |
+
),
|
| 208 |
+
plan_trace(
|
| 209 |
+
"search_rollout",
|
| 210 |
+
"We have four weeks to ship a search filter redesign. Check capacity, generate a work breakdown, then give me a prioritized rollout schedule with launch checks.",
|
| 211 |
+
"alex: 60%\\nbeth: 80%\\nchris: 50%\\ndiana: 75%",
|
| 212 |
+
"Week 1: UX/spec\\nWeek 2: frontend build\\nWeek 3: backend + integration\\nWeek 4: QA + docs + launch",
|
| 213 |
+
"Prioritize the redesign as a four-week rollout: week 1 for UX/spec alignment, week 2 for frontend implementation, week 3 for backend and integration, and week 4 for QA, docs, and launch prep. Launch checks should cover cross-device UI validation, query latency, experiment readiness, and documentation completion.",
|
| 214 |
+
),
|
| 215 |
+
plan_trace(
|
| 216 |
+
"mobile_error_state",
|
| 217 |
+
"Use the team availability and a generated plan to propose a four-week rollout for a mobile error-state redesign, then end with launch checks.",
|
| 218 |
+
"alex: 70%\\nbeth: 70%\\nchris: 55%\\ndiana: 85%",
|
| 219 |
+
"Week 1: design + instrumentation\\nWeek 2: UI implementation\\nWeek 3: backend wiring + metrics\\nWeek 4: QA, docs, rollout checks",
|
| 220 |
+
"A reasonable four-week rollout is: week 1 for design and instrumentation, week 2 for UI implementation, week 3 for backend wiring and metrics, and week 4 for QA, docs, and rollout checks. Before launch, confirm the new states render correctly, telemetry is firing, backend fallbacks behave, and support docs are updated.",
|
| 221 |
+
),
|
| 222 |
+
reverse_bin_trace(
|
| 223 |
+
"reverse_collect",
|
| 224 |
+
'The Cargo binary at "/workspace/glyph/runs/rlvr1/rust_cases/rev_collect_app" prints the string in the wrong order. Read the file, patch it, run cargo_run, and tell me the fixed stdout.',
|
| 225 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_collect_app",
|
| 226 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_collect_app/src/main.rs",
|
| 227 |
+
'fn main() { let s = "rust"; let out: String = s.chars().collect(); println!("{out}"); }',
|
| 228 |
+
"s.chars().collect()",
|
| 229 |
+
"s.chars().rev().collect()",
|
| 230 |
+
"tsur",
|
| 231 |
+
'I added the missing iterator reversal, verified it with `cargo_run`, and the binary now prints `"tsur"`.',
|
| 232 |
+
),
|
| 233 |
+
reverse_bin_trace(
|
| 234 |
+
"reverse_join",
|
| 235 |
+
'The binary at "/workspace/glyph/runs/rlvr1/rust_cases/rev_join_app" should print a reversed word. Inspect it, patch the bug, run cargo_run, and report stdout.',
|
| 236 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_join_app",
|
| 237 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_join_app/src/main.rs",
|
| 238 |
+
'fn main() { let s = "hello"; let out: String = s.chars().collect(); println!("{out}"); }',
|
| 239 |
+
"s.chars().collect()",
|
| 240 |
+
"s.chars().rev().collect()",
|
| 241 |
+
"olleh",
|
| 242 |
+
'I patched the string construction, ran `cargo_run`, and confirmed the fixed stdout is `"olleh"`.',
|
| 243 |
+
),
|
| 244 |
+
reverse_bin_trace(
|
| 245 |
+
"reverse_chars",
|
| 246 |
+
'Read "/workspace/glyph/runs/rlvr1/rust_cases/rev_chars_app/src/main.rs", apply one exact patch, then verify with cargo_run and tell me the corrected output.',
|
| 247 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_chars_app",
|
| 248 |
+
"/workspace/glyph/runs/rlvr1/rust_cases/rev_chars_app/src/main.rs",
|
| 249 |
+
'fn main() { let s = "abcde"; let out: String = s.chars().collect(); println!("{out}"); }',
|
| 250 |
+
"s.chars().collect()",
|
| 251 |
+
"s.chars().rev().collect()",
|
| 252 |
+
"edcba",
|
| 253 |
+
'I inserted the missing reversal, verified the result with `cargo_run`, and the program now prints `"edcba"`.',
|
| 254 |
+
),
|
| 255 |
+
]
|
| 256 |
+
return traces
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
def main() -> int:
|
| 260 |
+
traces = build_traces()
|
| 261 |
+
overlaps = sorted(set(extract_users(traces)) & load_eval_users())
|
| 262 |
+
invalid = []
|
| 263 |
+
for i, trace in enumerate(traces):
|
| 264 |
+
res = validate_trace(trace)
|
| 265 |
+
if not res.valid:
|
| 266 |
+
invalid.append({"index": i, "errors": res.errors[:5]})
|
| 267 |
+
if overlaps:
|
| 268 |
+
print(json.dumps({"exact_prompt_overlaps": overlaps}, indent=2))
|
| 269 |
+
return 1
|
| 270 |
+
if invalid:
|
| 271 |
+
print(json.dumps({"invalid": invalid}, indent=2))
|
| 272 |
+
return 1
|
| 273 |
+
with TOPUP_OUT.open("w", encoding="utf-8") as f:
|
| 274 |
+
for trace in traces:
|
| 275 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 276 |
+
rows = [row for row in BASE_DATASET.read_text(encoding="utf-8").splitlines() if row.strip()]
|
| 277 |
+
with COMBINED_OUT.open("w", encoding="utf-8") as f:
|
| 278 |
+
for row in rows:
|
| 279 |
+
f.write(row + "\n")
|
| 280 |
+
for trace in traces:
|
| 281 |
+
f.write(json.dumps({"trace": trace}, ensure_ascii=False) + "\n")
|
| 282 |
+
report = {
|
| 283 |
+
"base_rows": len(rows),
|
| 284 |
+
"topup_rows": len(traces),
|
| 285 |
+
"combined_rows": len(rows) + len(traces),
|
| 286 |
+
"topup_file": str(TOPUP_OUT.relative_to(ROOT)),
|
| 287 |
+
"combined_file": str(COMBINED_OUT.relative_to(ROOT)),
|
| 288 |
+
"exact_prompt_overlap_count": 0,
|
| 289 |
+
}
|
| 290 |
+
REPORT_OUT.write_text(json.dumps(report, indent=2), encoding="utf-8")
|
| 291 |
+
print(json.dumps(report, indent=2))
|
| 292 |
+
return 0
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
if __name__ == "__main__":
|
| 296 |
+
raise SystemExit(main())
|
final_glyph_sft_dataset.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|