"""Agentic conversations for the pool, stored structurally. python tools/gen_agentic.py --n-base 420 --n-extra 260 Two sources feed this: * `pipeline/agentic.py` already grounds traces in real repository files — a grep that really matches, a read that returns the real numbered source, an edit against a substring that really is unique, a test run that fails and is then diagnosed. Those traces are reused, with tool arguments converted from JSON strings to mappings because the Muse Glimmer template rejects a string. * Scenario families added here cover the call shapes that generator never produces: five and six argument calls, object- and array-valued arguments, and tool calls that fail with a structured error the assistant has to read and correct. Nothing is written by a language model. Every turn is a template filled from real repository text and computed values, which is why it is reproducible from a seed and why the same file always yields the same conversations. The conversations are stored as messages, not as rendered markup. Rendering to Muse Glimmer's special tokens happens in tools/build.py. """ from __future__ import annotations import argparse import copy import hashlib import json import os import random import sys HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) sys.path.insert(0, os.path.join(os.path.dirname(HERE), "pipeline")) import poollib as P SEED = 20260810 GENERATOR_VERSION = "gen_agentic/1.0" # Reasoning strength distribution. The model card recommends high or xhigh for # agentic work, so the corpus leans that way while still covering the cheap # settings a scaffold will actually use for simple steps. RS_WEIGHTS = [("low", 1), ("medium", 2), ("high", 4), ("xhigh", 3)] def pick_rs(rng: random.Random) -> str: pool = [v for v, w in RS_WEIGHTS for _ in range(w)] return rng.choice(pool) # --------------------------------------------------------------- extra tools HTTP = { "type": "function", "function": { "name": "http.request", "description": "Perform an HTTP request and return status, headers and body.", "parameters": { "type": "object", "properties": { "method": {"type": "string", "enum": ["GET", "POST", "PUT", "PATCH", "DELETE"]}, "url": {"type": "string"}, "headers": {"type": "object", "description": "Header name to value"}, "json_body": {"type": "object", "description": "Request body, sent as JSON"}, "timeout_s": {"type": "integer"}, "follow_redirects": {"type": "boolean"}, }, "required": ["method", "url"], }, }, } DBQ = { "type": "function", "function": { "name": "db.query", "description": "Run a parameterised SQL query against a named database.", "parameters": { "type": "object", "properties": { "sql": {"type": "string"}, "params": {"type": "array", "items": {}}, "database": {"type": "string"}, "timeout_s": {"type": "integer"}, "readonly": {"type": "boolean"}, }, "required": ["sql", "database"], }, }, } CODESEARCH = { "type": "function", "function": { "name": "search.code", "description": "Search the indexed codebase.", "parameters": { "type": "object", "properties": { "query": {"type": "string"}, "path_glob": {"type": "string"}, "case_sensitive": {"type": "boolean"}, "max_results": {"type": "integer"}, "context_lines": {"type": "integer"}, }, "required": ["query"], }, }, } BROWSER = { "type": "function", "function": { "name": "browser.act", "description": "Drive a page: click, type, scroll, or wait for a condition.", "parameters": { "type": "object", "properties": { "action": {"type": "string", "enum": ["click", "type", "scroll", "wait"]}, "selector": {"type": "string"}, "value": {"type": "string"}, "wait_for": {"type": "object", "description": "{selector, state, timeout_ms}"}, "screenshot": {"type": "boolean"}, }, "required": ["action"], }, }, } MCP = { "type": "function", "function": { "name": "mcp.call_tool", "description": "Invoke a tool exposed by a connected MCP server.", "parameters": { "type": "object", "properties": { "server": {"type": "string"}, "tool": {"type": "string"}, "arguments": {"type": "object"}, "timeout_s": {"type": "integer"}, "dry_run": {"type": "boolean"}, }, "required": ["server", "tool", "arguments"], }, }, } FSLIST = { "type": "function", "function": { "name": "fs.list", "description": "List a directory.", "parameters": { "type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"], }, }, } NS_DESCRIPTIONS = { "http": "Outbound HTTP from the agent sandbox.", "db": "Read/write access to the project's databases.", "search": "Code and document search over the indexed workspace.", "browser": "A headless browser under the agent's control.", "mcp": "Tools exposed by connected Model Context Protocol servers.", "fs": "Workspace filesystem.", } def _call(cid: str, name: str, args: dict) -> dict: return {"id": cid, "type": "function", "function": {"name": name, "arguments": args}} def _err(code: str, message: str, **extra) -> str: return json.dumps({"error": {"code": code, "message": message, **extra}}, ensure_ascii=False, indent=2) # ----------------------------------------------------------------- scenarios # Each returns (messages, tools). Every one contains at least one failing tool # call followed by a corrected retry, because failure recovery is a stated # capability of the target model and a corpus of only-happy paths would never # exercise it. def sc_http_pagination(rng, doc, repo): host = rng.choice(["api.internal", "registry.example.org", "hub.example.net"]) page_size = rng.choice([50, 100, 200]) msgs = [ {"role": "system", "content": f"You are an integration agent working against the {repo} project's " f"release tooling. Use the tools; do not guess at API shapes."}, {"role": "user", "content": f"Pull the full list of published {repo} versions from {host} and tell me " f"how many there are. The endpoint paginates."}, {"role": "assistant", "reasoning_content": "I do not know this API's pagination convention yet, so the first " "request should be a small page that shows me the envelope. If it " "returns a cursor I follow it; if it returns a total I can stop early.", "tool_calls": [_call("h1", "http.request", { "method": "GET", "url": f"https://{host}/v2/{repo}/versions", "headers": {"Accept": "application/json", "User-Agent": f"{repo}-agent/1.0"}, "timeout_s": 30, "follow_redirects": True, })]}, {"role": "tool", "name": "http.request", "content": _err("http_401", "Unauthorized", status=401, hint="this endpoint requires a bearer token in the Authorization header")}, {"role": "assistant", "reasoning_content": "401 with a hint naming the header. The token is in the environment " "as RELEASE_TOKEN; I add the Authorization header and keep everything " "else identical so that the only variable is authentication.", "tool_calls": [_call("h2", "http.request", { "method": "GET", "url": f"https://{host}/v2/{repo}/versions", "headers": {"Accept": "application/json", "Authorization": "Bearer ${RELEASE_TOKEN}", "User-Agent": f"{repo}-agent/1.0"}, "json_body": {}, "timeout_s": 30, "follow_redirects": True, })]}, {"role": "tool", "name": "http.request", "content": json.dumps({ "status": 200, "headers": {"content-type": "application/json", "x-total-count": str(page_size * 3 + 17)}, "body": {"versions": [f"{rng.randint(1,9)}.{i}.0" for i in range(5)], "next_cursor": "eyJvZmZzZXQiOjUwfQ=="}, }, ensure_ascii=False, indent=2)}, {"role": "assistant", "reasoning_content": "x-total-count says how many there are, so I do not have to walk every " "page to answer the question. I will confirm the count is stable by " "requesting the last page rather than trusting one header alone.", "tool_calls": [_call("h3", "http.request", { "method": "GET", "url": f"https://{host}/v2/{repo}/versions", "headers": {"Accept": "application/json", "Authorization": "Bearer ${RELEASE_TOKEN}"}, "json_body": {"cursor": "eyJvZmZzZXQiOjUwfQ==", "page_size": page_size}, "timeout_s": 30, "follow_redirects": True, })]}, {"role": "tool", "name": "http.request", "content": json.dumps({"status": 200, "body": {"versions": [f"{rng.randint(1,9)}.{i}.0" for i in range(17)], "next_cursor": None}}, ensure_ascii=False, indent=2)}, {"role": "assistant", "content": f"{page_size * 3 + 17} published versions. The first request failed with 401 — " f"the endpoint needs `Authorization: Bearer $RELEASE_TOKEN`, which is worth " f"noting if you script this. The `x-total-count` header agrees with walking to " f"the final page, so the count is trustworthy."}, ] return msgs, [HTTP] def sc_db_migration(rng, doc, repo): table = rng.choice(["assets", "sessions", "build_artifacts", "render_jobs"]) msgs = [ {"role": "system", "content": "You are a database operations agent. Every statement you run against a " "production database must be read-only unless the user has explicitly " "approved a write."}, {"role": "user", "content": f"The {table} table has grown a lot. Find out how much of it is rows older " f"than 90 days, but do not delete anything yet."}, {"role": "assistant", "reasoning_content": "Read-only by default, and the user explicitly said not to delete. " "A COUNT with a date predicate answers this without touching data. " "I will pass the cutoff as a parameter rather than inlining it.", "tool_calls": [_call("d1", "db.query", { "sql": f"SELECT count(*) AS old_rows FROM {table} WHERE created_at < $1", "params": ["2026-05-12T00:00:00Z"], "database": "prod", "timeout_s": 60, "readonly": True, })]}, {"role": "tool", "name": "db.query", "content": _err("undefined_column", f'column "created_at" does not exist', detail=f"table {table} has columns: id, inserted_at, payload, state", sqlstate="42703")}, {"role": "assistant", "reasoning_content": "The column is `inserted_at`, not `created_at`. The error listed the " "real columns, so I do not need a separate schema lookup — I just " "correct the predicate and re-run the same read-only query.", "tool_calls": [_call("d2", "db.query", { "sql": f"SELECT count(*) AS old_rows, pg_size_pretty(sum(pg_column_size(payload))) " f"AS payload_bytes FROM {table} WHERE inserted_at < $1", "params": ["2026-05-12T00:00:00Z"], "database": "prod", "timeout_s": 60, "readonly": True, })]}, {"role": "tool", "name": "db.query", "content": json.dumps({"rows": [{"old_rows": rng.randint(400_000, 9_000_000), "payload_bytes": f"{rng.randint(2, 90)} GB"}], "row_count": 1, "elapsed_ms": rng.randint(80, 4000)}, ensure_ascii=False, indent=2)}, {"role": "assistant", "content": f"Counted, nothing deleted. Note the column is `inserted_at` — my first query " f"assumed `created_at` and the database corrected me. Say the word and I will " f"draft the deletion in batches, but that needs your approval since it is a write."}, ] return msgs, [DBQ] def sc_mcp_chain(rng, doc, repo): server = rng.choice(["atlas-fs", "atlas-issues", "atlas-ci"]) msgs = [ {"role": "system", "content": "You have access to connected MCP servers. Prefer a dry run before any tool " "call that changes remote state."}, {"role": "user", "content": f"Open an issue on the {repo} tracker for the failing nightly build, and link " f"it to the last green commit."}, {"role": "assistant", "reasoning_content": "Two unknowns: which build failed, and which commit was last green. " "I need both before I can write a useful issue, so the CI query comes " "first and the issue creation last.", "tool_calls": [_call("m1", "mcp.call_tool", { "server": "atlas-ci", "tool": "list_runs", "arguments": {"project": repo, "branch": "main", "status": ["failed", "success"], "limit": 20, "fields": ["id", "status", "commit", "started_at"]}, "timeout_s": 45, "dry_run": False, })]}, {"role": "tool", "name": "mcp.call_tool", "content": json.dumps({"runs": [ {"id": 8841, "status": "failed", "commit": "a1c9f02", "started_at": "2026-08-10T02:11:00Z"}, {"id": 8840, "status": "failed", "commit": "a1c9f02", "started_at": "2026-08-09T02:11:00Z"}, {"id": 8839, "status": "success", "commit": "77de1b4", "started_at": "2026-08-08T02:10:00Z"}, ]}, ensure_ascii=False, indent=2)}, {"role": "assistant", "reasoning_content": "Two consecutive failures on a1c9f02, last green is 77de1b4. That is " "enough to write the issue. I dry-run first because creating an issue " "is remote state I cannot undo cleanly.", "tool_calls": [_call("m2", "mcp.call_tool", { "server": server, "tool": "create_issue", "arguments": { "repo": repo, "title": "Nightly build red since a1c9f02", "body": "Runs 8840 and 8841 both failed on `a1c9f02`. Last green run was 8839 on " "`77de1b4`.", "labels": ["ci", "regression"], "links": [{"type": "commit", "ref": "a1c9f02"}, {"type": "commit", "ref": "77de1b4", "note": "last green"}], }, "timeout_s": 30, "dry_run": True, })]}, {"role": "tool", "name": "mcp.call_tool", "content": _err("validation_failed", "label 'regression' is not defined in this project", allowed_labels=["ci", "bug", "build-break", "flaky"])}, {"role": "assistant", "reasoning_content": "The dry run earned its keep: `regression` does not exist here. " "`build-break` is the project's equivalent. Swapping it and running " "for real.", "tool_calls": [_call("m3", "mcp.call_tool", { "server": server, "tool": "create_issue", "arguments": { "repo": repo, "title": "Nightly build red since a1c9f02", "body": "Runs 8840 and 8841 both failed on `a1c9f02`. Last green run was 8839 on " "`77de1b4`.", "labels": ["ci", "build-break"], "links": [{"type": "commit", "ref": "a1c9f02"}, {"type": "commit", "ref": "77de1b4", "note": "last green"}], }, "timeout_s": 30, "dry_run": False, })]}, {"role": "tool", "name": "mcp.call_tool", "content": json.dumps({"issue": {"number": rng.randint(100, 9000), "url": f"https://tracker.example/{repo}/issues/1"}}, ensure_ascii=False, indent=2)}, {"role": "assistant", "content": "Filed. Two things worth knowing: the break is `a1c9f02` with `77de1b4` as the " "last green, and this project does not have a `regression` label — I used " "`build-break`, which the dry run surfaced before anything was created."}, ] return msgs, [MCP] def sc_search_refactor(rng, doc, repo): sym = doc.get("_symbol") or "resolve" path = doc["path"] msgs = [ {"role": "system", "content": f"You are a refactoring agent on the {repo} codebase. Establish the blast " f"radius of a change before making it."}, {"role": "user", "content": f"I want to rename `{sym}` in `{path}`. How many call sites are there?"}, {"role": "assistant", "reasoning_content": "A rename is only safe if I have seen every reference, including " "re-exports and string references in tests. Start broad, " "case-sensitive, with enough context to tell a definition from a call.", "tool_calls": [_call("s1", "search.code", { "query": sym, "path_glob": "**/*", "case_sensitive": True, "max_results": 500, "context_lines": 2, })]}, {"role": "tool", "name": "search.code", "content": _err("too_many_results", f"query matched {rng.randint(2000, 9000)} lines, above max_results=500", hint="narrow path_glob or raise max_results")}, {"role": "assistant", "reasoning_content": "Too broad — the bare identifier appears inside longer words. I will " "scope to source extensions and keep the context lines so I can still " "classify each hit.", "tool_calls": [_call("s2", "search.code", { "query": f"\\b{sym}\\b", "path_glob": "{src,test,packages}/**/*.{ts,tsx,js,mjs}", "case_sensitive": True, "max_results": 500, "context_lines": 2, })]}, {"role": "tool", "name": "search.code", "content": json.dumps({"total": 34, "files": 11, "by_kind": {"definition": 1, "call": 27, "re-export": 4, "test": 2}}, ensure_ascii=False, indent=2)}, {"role": "assistant", "content": f"34 references across 11 files: one definition in `{path}`, 27 calls, " f"4 re-exports and 2 test references. The re-exports are the risky ones — " f"renaming without updating them changes the public surface. My first search " f"was too broad because `{sym}` occurs inside longer identifiers; the word-" f"boundary form is the one to trust."}, ] return msgs, [CODESEARCH] def sc_browser_osworld(rng, doc, repo): msgs = [ {"role": "system", "content": "You control a headless browser. Take a screenshot whenever the page state is " "ambiguous."}, {"role": "user", "content": [ {"type": "text", "text": "This settings page won't save. Here's what I see:\n"}, {"type": "image"}, {"type": "text", "text": "\nFigure out why and fix it."}, ]}, {"role": "assistant", "reasoning_content": "The screenshot shows the save button but I cannot tell from a still " "image whether it is disabled or the click is being swallowed. " "Clicking it and watching for the confirmation toast distinguishes " "the two.", "tool_calls": [_call("b1", "browser.act", { "action": "click", "selector": "button[data-testid='save-settings']", "wait_for": {"selector": "[role=status]", "state": "visible", "timeout_ms": 5000}, "screenshot": True, })]}, {"role": "tool", "name": "browser.act", "content": _err("timeout", "wait_for condition not met within 5000ms", element_state={"disabled": True, "aria-disabled": "true"}, screenshot="/tmp/shot-1.png")}, {"role": "assistant", "reasoning_content": "The button is genuinely disabled, so the click was never the problem. " "A disabled save on a settings form almost always means a required " "field failed validation. Look for the invalid control.", "tool_calls": [_call("b2", "browser.act", { "action": "wait", "selector": "[aria-invalid='true']", "wait_for": {"selector": "[aria-invalid='true']", "state": "attached", "timeout_ms": 2000}, "screenshot": True, })]}, {"role": "tool", "name": "browser.act", "content": json.dumps({"found": True, "element": {"id": "webhook-url", "aria-invalid": "true", "validationMessage": "Enter a valid https:// URL"}, "screenshot": "/tmp/shot-2.png"}, ensure_ascii=False, indent=2)}, {"role": "assistant", "reasoning_content": "There it is. The webhook URL field is invalid, which disables save. " "Correcting it should re-enable the button.", "tool_calls": [_call("b3", "browser.act", { "action": "type", "selector": "#webhook-url", "value": "https://hooks.example.org/ingest", "wait_for": {"selector": "button[data-testid='save-settings']:not([disabled])", "state": "visible", "timeout_ms": 3000}, "screenshot": False, })]}, {"role": "tool", "name": "browser.act", "content": json.dumps({"ok": True, "button_enabled": True}, ensure_ascii=False)}, {"role": "assistant", "content": "The save button was disabled, not unresponsive — the webhook URL field was " "`aria-invalid` because it needs an `https://` URL. I filled in a valid one and " "save is enabled again. Nothing was actually broken about the page; the form " "just gives no visible reason for the disabled state, which is the real bug."}, ] return msgs, [BROWSER] def sc_single_arg(rng, doc, repo): """Deliberately minimal: one call, one argument. A corpus made only of elaborate calls would never see the one-parameter shape.""" d = os.path.dirname(doc["path"]) or "." msgs = [ {"role": "user", "content": f"What's in `{d}` in the {repo} checkout?"}, {"role": "assistant", "reasoning_content": "Straightforward listing, no need to plan around it.", "tool_calls": [_call("f1", "fs.list", {"path": d})]}, {"role": "tool", "name": "fs.list", "content": "\n".join(sorted({os.path.basename(doc["path"])} | {f"{c}.ts" for c in ("index", "types", "utils")}))}, {"role": "assistant", "content": f"`{d}` holds the module entry point plus its types and helpers."}, ] return msgs, [FSLIST] SCENARIOS = [ (sc_http_pagination, 6), (sc_db_migration, 5), (sc_mcp_chain, 6), (sc_search_refactor, 5), (sc_browser_osworld, 4), (sc_single_arg, 3), ] # ------------------------------------------------------------------ coverage def arg_shapes(messages) -> dict: """What call shapes a conversation actually contains.""" arities, nested, errors, chain = set(), 0, 0, 0 for m in messages: for tc in m.get("tool_calls") or []: args = tc["function"]["arguments"] arities.add(len(args)) if any(isinstance(v, (dict, list)) and v for v in args.values()): nested += 1 chain += 1 if m.get("role") == "tool": try: if isinstance(json.loads(m["content"]), dict) and \ "error" in json.loads(m["content"]): errors += 1 except (json.JSONDecodeError, TypeError): pass return {"arities": arities, "nested": nested, "errors": errors, "calls": chain} def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--n-base", type=int, default=420) ap.add_argument("--n-extra", type=int, default=260) ap.add_argument("--seed", type=int, default=SEED) args = ap.parse_args() rng = random.Random(args.seed) # Repository files reserved for agentic use. pipeline/agentic.py keeps a # disjoint sha1(path)%10 bucket so that file content used inside a trace is # not also present as a plain code document. import agentic as A pool = [d for d in P.load_pool(categories=("code", "graphics")) if d.get("render") == "text"] for d in pool: d.setdefault("id", "") reserved = [d for d in pool if int(hashlib.sha1(d["path"].encode()).hexdigest(), 16) % 10 == A.AGENTIC_BUCKET] print(f" {len(reserved)} repository files in the reserved agentic bucket " f"(of {len(pool)} code/graphics documents)") records: list[P.Record] = [] # --- traces grounded in real files ------------------------------------- # build_traces renders its conversations to DeepSeek markup on the way out # and drops the messages. Swapping the renderer for a JSON dump recovers the # structure without forking two hundred lines of trace-construction logic, # and keeps this generator tracking any future fix to pipeline/agentic.py. A.encode_chat = lambda msgs, **kw: json.dumps(msgs, ensure_ascii=False) traces = [(d["source"].split(":", 1)[1], json.loads(d["text"]), d["path"].split("/", 1)[1]) for d in A.build_traces(reserved, args.n_base, seed=args.seed)] print(f" {len(traces)} grounded traces from pipeline/agentic.py") for repo, msgs, kind in traces: msgs = copy.deepcopy(msgs) for m in msgs: for tc in m.get("tool_calls") or []: a = tc["function"]["arguments"] if isinstance(a, str): # template needs a mapping tc["function"]["arguments"] = json.loads(a) rs = pick_rs(rng) records.append(P.Record( category="agentic", domain="agentic", source=f"synthetic/agentic:{repo}", license="CC0-1.0 (generated; embedded file excerpts keep their upstream licence)", path=f"agentic/{kind}/{repo}", lang="chat", origin="synth_agentic", messages=msgs, tools=A.TOOLS, reasoning_strength=rs, render="chat", synthetic=True, provenance={"generator": GENERATOR_VERSION, "base": "pipeline/agentic.py", "seed": args.seed, "kind": kind, "grounded_in": "real repository files from the reserved bucket"}, )) # --- scenario families for the missing call shapes ---------------------- weights = [f for f, w in SCENARIOS for _ in range(w)] docs = sorted(reserved, key=lambda d: d["id"]) or sorted(pool, key=lambda d: d["id"]) for i in range(args.n_extra): fn = weights[i % len(weights)] doc = dict(docs[(i * 7919) % len(docs)]) doc["_symbol"] = A._pick_symbol(doc["text"], rng) repo = doc["source"] msgs, tools = fn(rng, doc, repo) rs = pick_rs(rng) records.append(P.Record( category="agentic", domain="agentic", source=f"synthetic/agentic:{fn.__name__[3:]}", license="CC0-1.0 (generated)", path=f"agentic/scenario/{fn.__name__[3:]}/{i:04d}", lang="chat", origin="synth_agentic_scenario", messages=msgs, tools=tools, reasoning_strength=rs, render="chat", synthetic=True, provenance={"generator": GENERATOR_VERSION, "scenario": fn.__name__, "seed": args.seed, "namespace_descriptions": NS_DESCRIPTIONS}, )) # --- required-coverage gate -------------------------------------------- all_arities: set[int] = set() nested = errors = multi = 0 for r in records: s = arg_shapes(r.messages) all_arities |= s["arities"] nested += s["nested"] errors += s["errors"] multi += 1 if s["calls"] >= 3 else 0 have5 = any(a >= 5 for a in all_arities) print(f" argument arities present : {sorted(all_arities)}") print(f" calls with nested values : {nested}") print(f" tool errors recovered : {errors}") print(f" chains of >=3 calls : {multi} of {len(records)}") missing = [a for a in (1, 2, 3) if a not in all_arities] if missing or not have5 or not nested or not errors: raise SystemExit(f"coverage gate failed: missing arities {missing}, " f"5+={have5}, nested={nested}, errors={errors}") n = P.write_jsonl(os.path.join(P.POOL_ROOT, "agentic", "synthetic", "conversations.jsonl"), records) print(f" pool/agentic/synthetic/conversations.jsonl {n} conversations") return 0 if __name__ == "__main__": sys.exit(main())