codecop 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,221 @@
1
+ """The agent writes a driver program; CodeCop checks it and runs it under the isolation contract.
2
+
3
+ An agent asked to write a long statement paraphrases it (few variants come back identical); an agent asked to
4
+ write the program that builds it copies the builder's pure code verbatim, and the program's output is exact.
5
+ So for a run-time-built site the agent is asked, in order:
6
+
7
+ 1. a minimal standalone program in the site's language (Go, Rust or Python), standard library only, that copies the
8
+ functions, constants and tables building the statement and prints one JSON line {"condition", "sql"} per variant
9
+ the code supports; CodeCop refuses any program that imports outside an allowlist (no network, files, processes,
10
+ unsafe code) and runs it under isolate.run: basis "builder evaluated";
11
+ 2. only when no driver is possible (the text depends on data the code reads at run time), the statements themselves:
12
+ basis "written by the agent", unverified until a stronger basis gives the same text.
13
+
14
+ Sites are asked by heat (measured executions where a pull placed the site, then request-path code, then the rest)
15
+ inside the run budget (budget.Run). Each answer is stored in families_evaluated.json (`drivers`) and never paid twice.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import json
21
+ import re
22
+ from pathlib import Path
23
+
24
+ from . import isolate, model
25
+
26
+ PROMPT_VERSION = "families-driver-1"
27
+ LANGS = {"go": "go", "rust": "rust", "python": "python"}
28
+ GO_ALLOW = {"fmt", "strings", "strconv", "sort", "slices", "maps", "unicode", "unicode/utf8", "bytes", "math", "errors", "time",
29
+ "regexp", "encoding/json", "encoding/hex", "crypto/sha256", "crypto/md5", "crypto/sha1", "hash/fnv", "cmp",
30
+ "text/template", "math/bits", "iter", "os"}
31
+ GO_OS_OK = re.compile(r"\bos\.(Stdout|Stderr|Exit)\b")
32
+ PY_ALLOW = {"json", "re", "itertools", "string", "textwrap", "enum", "dataclasses", "typing", "collections", "functools",
33
+ "datetime", "math", "hashlib", "uuid", "decimal", "sys", "__future__", "operator", "copy"}
34
+ RUST_DENY = re.compile(r"\bstd::(net|process|fs|os|env|thread|ffi)\b|\bunsafe\b|\bextern\s+crate\b|\binclude(_str|_bytes)?!|"
35
+ r"\benv!|\bcommand\b\s*::|\basm!")
36
+ SCHEMA = {
37
+ "type": "object",
38
+ "properties": {
39
+ "language": {"type": "string", "enum": ["go", "rust", "python", "none"]},
40
+ "program": {"type": "string", "description": "the whole driver program, one file; empty when no driver is possible"},
41
+ "no_driver_reason": {"type": "string"},
42
+ "statements": {"type": "array", "items": {"type": "object", "properties": {"condition": {"type": "string"}, "sql": {"type": "string"}},
43
+ "required": ["condition", "sql"]},
44
+ "description": "only when no driver is possible: the complete statements, most common first"},
45
+ },
46
+ "required": ["language", "program"],
47
+ }
48
+ DEFAULTS = {"max_sql_chars": 6000, "model": "sonnet", "max_call_usd": 1.0, "max_statements": 50, "cost_low": 0.20, "cost_high": 0.40}
49
+
50
+
51
+ def prompt(site: dict, lang: str, sql_chars: int) -> str:
52
+ sql = (site.get("sql") or "")[:sql_chars] or "(no text: the statement is passed in or assembled elsewhere)"
53
+ return f"""You are resolving a database statement that code builds at run time. The repository root is the current directory; use Read, Grep and Glob only.
54
+ Call site: {site['file']}:{site['line']} (function {site.get('symbol') or '?'}), engine {site.get('engine') or '?'}. The SQL as far as a static tool resolved it («expr» marks a part only known at run time; the text may be cut):
55
+ ```
56
+ {sql}
57
+ ```
58
+ Do NOT write SQL yourself. Write a minimal standalone {lang.capitalize()} program, one file, standard library only, no network, no files, no environment, no processes, no database, that reproduces the string-building of this call site by copying the needed pure functions, constants, types and tables from the repository VERBATIM (rename nothing, simplify nothing), and calls them for every variant the code supports: every value of each enum or kind it branches on, each optional filter on and off where it changes the statement. Bind markers stay as the code writes them. For each variant print one JSON line to standard output: {{"condition": "<the choice in code terms, e.g. family = agent, live = nil>", "sql": "<the complete statement>"}}.
59
+ {'Go: package main, func main.' if lang == 'go' else 'Rust: fn main, compiled with plain rustc (no crates; write the JSON by hand with a small escape function).' if lang == 'rust' else 'Python 3.12: run as a script.'}
60
+ Answer with language "{lang}" and the program. Only if no program can reproduce it (the text depends on data read at run time, from a database, a file or a request), answer language "none", say why in no_driver_reason, and give the complete statements (at most 6, most common first, binds as the code writes them) in statements."""
61
+
62
+
63
+ def check_program(lang: str, program: str) -> str:
64
+ """'' when the program may run; else why it is refused."""
65
+ if not program.strip():
66
+ return "empty program"
67
+ if lang == "go":
68
+ imports = set(re.findall(r'^\s*(?:\w+\s+)?"([^"]+)"\s*$', "\n".join(re.findall(r"import\s*\(([^)]*)\)", program, re.S)), re.M)) | \
69
+ set(re.findall(r'^import\s+(?:\w+\s+)?"([^"]+)"', program, re.M))
70
+ bad = sorted(i for i in imports if i not in GO_ALLOW)
71
+ if bad:
72
+ return "imports " + ", ".join(bad)
73
+ if "os" in imports and re.search(r"\bos\.(?!Stdout\b|Stderr\b|Exit\b)\w+", program):
74
+ return "uses os beyond Stdout/Stderr/Exit"
75
+ if re.search(r"\bunsafe\b|//go:linkname|\bsyscall\b|\bgo\s+func\b|\bimport\s+\"C\"", program):
76
+ return "unsafe, cgo, linkname or goroutines"
77
+ return ""
78
+ if lang == "python":
79
+ mods = set(re.findall(r"^\s*import\s+([\w.]+)", program, re.M)) | set(re.findall(r"^\s*from\s+([\w.]+)\s+import", program, re.M))
80
+ bad = sorted(m for m in mods if m.split(".")[0] not in PY_ALLOW)
81
+ if bad:
82
+ return "imports " + ", ".join(bad)
83
+ if re.search(r"\b(open|exec|eval|compile|__import__|getattr\s*\(\s*__builtins__|globals|breakpoint)\s*\(", program):
84
+ return "uses open/exec/eval/__import__"
85
+ if re.search(r"\bsys\.(?!stdout\b|stderr\b|exit\b|argv\b)\w+", program):
86
+ return "uses sys beyond stdout/stderr/exit"
87
+ return ""
88
+ if lang == "rust":
89
+ m = RUST_DENY.search(program)
90
+ if m:
91
+ return "uses " + m.group(0)
92
+ if re.search(r"^\s*(?:use|extern)\s+(?!std\b|core\b|alloc\b|self\b|super\b|crate\b)\w+", program, re.M):
93
+ return "uses a crate outside the standard library"
94
+ return ""
95
+ return f"no runner for {lang}"
96
+
97
+
98
+ RUN = {"go": ("main.go", "printf 'module driver\\ngo 1.24\\n' > go.mod && go build -o /work/prog . && /work/prog"),
99
+ "rust": ("main.rs", "rustc -O --edition 2021 -o /work/prog main.rs && /work/prog"),
100
+ "python": ("main.py", "python3 -B -s -S main.py")}
101
+
102
+
103
+ def run_driver(lang: str, program: str, out_dir: Path | None, ref: str, settings: dict | None = None) -> dict:
104
+ """{ok, statements: [{condition, sql}], refused?, audit, stderr}"""
105
+ why = check_program(lang, program)
106
+ if why:
107
+ return {"ok": False, "refused": why, "statements": []}
108
+ images = {**isolate.DEFAULTS["images"], "rust": "codecop-isolated-rust:1", **((settings or {}).get("images") or {})}
109
+ name, script = RUN[lang]
110
+ r = isolate.run({name: program}, script, image=images[lang], out_dir=out_dir, purpose="driver", ref=ref,
111
+ settings=(settings or {}).get("isolate"))
112
+ stmts = []
113
+ for line in r["stdout"].splitlines():
114
+ try:
115
+ o = json.loads(line)
116
+ except ValueError:
117
+ continue
118
+ if isinstance(o, dict) and isinstance(o.get("sql"), str) and o["sql"].strip():
119
+ stmts.append({"condition": str(o.get("condition") or "")[:300], "sql": o["sql"]})
120
+ return {"ok": r["accepted"] and bool(stmts), "statements": stmts if r["accepted"] else [], "audit": r["audit"],
121
+ "exit": r["exit"], "stderr": r["stderr"][-800:], **({} if r["accepted"] else {"refused": "audit"})}
122
+
123
+
124
+ def heat_order(sites: list[dict], match_doc: dict | None) -> list[dict]:
125
+ """Hottest first: measured executions of the site (or of its function), request-path code, then the rest."""
126
+ load = {}
127
+ for eng in ((match_doc or {}).get("engines") or {}).values():
128
+ for sid, row in (eng.get("sites") or {}).items():
129
+ load[sid] = load.get(sid, 0) + int(row.get("executions") or 0)
130
+ by_fn: dict[tuple, int] = {}
131
+ for s in sites:
132
+ by_fn[(s["file"], s.get("symbol"))] = by_fn.get((s["file"], s.get("symbol")), 0) + load.get(s["id"], 0)
133
+
134
+ def key(s: dict):
135
+ role = s.get("role") or ""
136
+ return (-(load.get(s["id"], 0) or by_fn.get((s["file"], s.get("symbol")), 0)), 0 if role in ("app", "job") else 1,
137
+ -int(s.get("origin_count") or 0), s["file"], s["line"])
138
+ return sorted(sites, key=key)
139
+
140
+
141
+ def ask(out_dir: Path, root: Path, sites: list[dict], *, runner, run=None, settings: dict | None = None, log=lambda m: None,
142
+ workers: int = 4) -> dict:
143
+ """Ask the agent for a driver for each site (in the given order, normally heat_order) until the budget is spent.
144
+ Stores every answer in families_evaluated.json: `drivers` (the call) and `sites` (the variants it gave)."""
145
+ from concurrent.futures import ThreadPoolExecutor
146
+
147
+ from .build import EVALUATED, load
148
+ cfg = {**DEFAULTS, **(settings or {})}
149
+ path = Path(out_dir) / EVALUATED
150
+ doc = load(path, {}) or {}
151
+ doc.setdefault("sites", [])
152
+ doc.setdefault("drivers", [])
153
+ done = {d["site_id"] for d in doc["drivers"] if d.get("prompt_version") == PROMPT_VERSION}
154
+ todo = [s for s in sites if s["id"] not in done and LANGS.get(s.get("language") or "")]
155
+ wrapped = run.wrap(runner, "families") if run is not None else runner
156
+ import threading
157
+ lock = threading.Lock()
158
+
159
+ def one(s: dict) -> dict | None:
160
+ if run is not None and not run.can_pay(float(cfg["cost_low"])):
161
+ return None
162
+ lang = LANGS[s["language"]]
163
+ rec = {"site_id": s["id"], "file": s["file"], "line": s["line"], "language": lang, "prompt_version": PROMPT_VERSION}
164
+ try:
165
+ if run is not None:
166
+ run.tell("families", 1, (float(cfg["cost_low"]), float(cfg["cost_high"])))
167
+ res = wrapped.run(prompt(s, lang, int(cfg["max_sql_chars"])), SCHEMA, Path(root), model=cfg["model"],
168
+ max_budget_usd=float(cfg["max_call_usd"]))
169
+ except Exception as e: # AgentError, budget reached, usage limit: recorded, never fatal
170
+ rec.update(error=str(e)[:300])
171
+ return rec
172
+ out = res.output or {}
173
+ rec.update(cost_usd=round(res.cost_usd, 4), turns=res.turns, seconds=round(res.duration_s, 1), answered=out.get("language"))
174
+ variants: list[dict] = []
175
+ unbuilt: list[dict] = []
176
+ if out.get("language") in RUN and out.get("program"):
177
+ got = run_driver(out["language"], out["program"], out_dir, s["id"], cfg)
178
+ rec.update(driver_ran=got["ok"], refused=got.get("refused", ""), statements=len(got["statements"]),
179
+ exit=got.get("exit"), audit_accepted=(got.get("audit") or {}).get("accepted"))
180
+ if got["ok"]:
181
+ variants = [{"sql": x["sql"], "basis": "evaluated", "condition": x["condition"], "source": "driver"}
182
+ for x in got["statements"][: int(cfg["max_statements"])]]
183
+ else:
184
+ unbuilt.append({"condition": "agent-written driver", "reason": "driver_refused" if got.get("refused") else "driver_failed",
185
+ "detail": got.get("refused") or got.get("stderr", "")[-200:], "source": "driver"})
186
+ prog_dir = Path(out_dir) / "families_drivers"
187
+ prog_dir.mkdir(exist_ok=True)
188
+ (prog_dir / f"{s['id']}.{ {'go': 'go', 'rust': 'rs', 'python': 'py'}[out['language']] }").write_text(out["program"])
189
+ elif out.get("statements"):
190
+ variants = [{"sql": x["sql"], "basis": "agent", "condition": x.get("condition", ""), "source": "agent"}
191
+ for x in out["statements"][:6] if x.get("sql")]
192
+ rec["no_driver_reason"] = (out.get("no_driver_reason") or "")[:300]
193
+ with lock:
194
+ rows = {r["site_id"]: r for r in doc["sites"]}
195
+ row = rows.get(s["id"])
196
+ if row is None:
197
+ row = {"site_id": s["id"], "variants": [], "unbuilt": []}
198
+ doc["sites"].append(row)
199
+ row["variants"] = [v for v in row["variants"] if v.get("source") not in ("driver", "agent")] + variants
200
+ row["unbuilt"] = [u for u in row["unbuilt"] if u.get("source") != "driver"] + unbuilt
201
+ doc["drivers"].append(rec)
202
+ path.write_text(json.dumps(doc, indent=1))
203
+ log(f"{s['file']}:{s['line']} {rec.get('answered')} ran={rec.get('driver_ran')} n={rec.get('statements', len(variants))} ${rec.get('cost_usd', 0)}")
204
+ return rec
205
+
206
+ with ThreadPoolExecutor(max(1, workers)) as ex:
207
+ list(ex.map(one, todo))
208
+ return doc
209
+
210
+
211
+ def planned_ids(fams: list[dict]) -> set[str]:
212
+ return {f["site"]["id"] for f in fams if any((v.get("valid") or {}).get("planned") and v.get("exact") for v in f["variants"])}
213
+
214
+
215
+ def needs_agent(fams: list[dict]) -> list[str]:
216
+ """Sites whose family has no exact statement that plans: what the agent is asked about."""
217
+ ok = planned_ids(fams)
218
+ return [f["site"]["id"] for f in fams if f["site"]["kind"] == "site" and f["site"]["id"] not in ok]
219
+
220
+
221
+ _ = model # the variants this module writes are model.variant records once build.build merges them
@@ -0,0 +1,229 @@
1
+ """Pure slice of a Go builder, evaluated under the isolation contract (isolate.py): basis "builder evaluated".
2
+
3
+ For one Go package directory the slicer (goslice_tool/main.go, CodeCop's own code) parses the package, takes every
4
+ function that returns a string and whose whole closure uses only an allowlist of standard packages (no I/O, no network,
5
+ no database, no goroutines), writes them into a standalone program with a driver that calls each over its enumerable
6
+ arguments (bools, constants of a named type, nil and a zero struct), and the program prints one JSON line per call.
7
+
8
+ Two isolated runs per package, neither with the repository mounted:
9
+ 1. slice: input = the slicer's source and a copy of the package's non-test .go files (and the data files its
10
+ go:embed lines name); output = the generated program.
11
+ 2. evaluate: input = the generated program only; output = the builder's statements.
12
+
13
+ The outputs are then mapped to the package's run-time-built call sites: the site's template matches an output (the
14
+ whole statement), or the site's function calls a builder whose output starts like the site's text, or the site's
15
+ call-expression parts are filled by outputs and the rest by the static rules.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import base64
21
+ import io
22
+ import json
23
+ import os
24
+ import re
25
+ import tarfile
26
+ from collections import defaultdict
27
+ from pathlib import Path
28
+
29
+ from ..realdb.match import shape
30
+ from . import holes, isolate, model
31
+
32
+ TOOL = Path(__file__).with_name("goslice_tool")
33
+ DATA_EXT = (".sql", ".tmpl", ".tpl", ".txt", ".json")
34
+ SQLY = re.compile(r"^\s*\(?\s*(SELECT|WITH|INSERT|UPDATE|DELETE|MERGE)\b", re.I)
35
+ PH = re.compile(r"«([^»]*)»")
36
+ DEFAULTS = {"max_package_bytes": 4_000_000, "max_outputs_per_site": 32}
37
+
38
+
39
+ def package_files(root: Path, pkg: str, max_bytes: int) -> dict[str, bytes]:
40
+ out: dict[str, bytes] = {}
41
+ total = 0
42
+ base = root / pkg
43
+ for dirpath, _dirs, names in os.walk(base):
44
+ rel_dir = os.path.relpath(dirpath, base)
45
+ if rel_dir != "." and not any(n.endswith(DATA_EXT) for n in names):
46
+ continue
47
+ for n in sorted(names):
48
+ rel = os.path.normpath(os.path.join(rel_dir, n))
49
+ if isolate.ENV_FILE.search(rel) or n.endswith("_test.go"):
50
+ continue
51
+ if rel_dir == "." and n.endswith(".go") or n.endswith(DATA_EXT):
52
+ p = Path(dirpath) / n
53
+ try:
54
+ data = p.read_bytes()
55
+ except OSError:
56
+ continue
57
+ total += len(data)
58
+ if total > max_bytes:
59
+ return out
60
+ out[f"pkg/{rel}"] = data
61
+ if rel_dir == ".":
62
+ continue
63
+ return out
64
+
65
+
66
+ def slice_and_run(root: Path, pkg: str, out_dir: Path | None, settings: dict | None = None) -> dict:
67
+ """{pkg, report, outputs: [{fn, args, out, panic}], audits: [..], error?}"""
68
+ cfg = {**DEFAULTS, **(settings or {})}
69
+ image = (cfg.get("images") or isolate.DEFAULTS["images"])["go"]
70
+ files = {f"tool/{n}": (TOOL / n).read_bytes() for n in ("main.go", "go.mod")}
71
+ files.update(package_files(Path(root), pkg, int(cfg["max_package_bytes"])))
72
+ res = {"pkg": pkg, "report": {}, "outputs": [], "audits": []}
73
+ r1 = isolate.run(files, "cd /work/in/tool && go build -o /work/slicer . && /work/slicer /work/in/pkg /work/slice >/dev/null "
74
+ "&& cd /work/slice && tar -czf - . | base64", image=image, out_dir=out_dir, purpose="slice", ref=pkg,
75
+ settings=cfg.get("isolate"))
76
+ res["audits"].append(r1["audit"])
77
+ if not r1["accepted"] or r1["exit"] != 0:
78
+ res["error"] = "slice step failed" if r1["accepted"] else "slice step refused by its audit"
79
+ res["stderr"] = r1["stderr"][-600:]
80
+ return res
81
+ try:
82
+ blob = base64.b64decode("".join(r1["stdout"].split()))
83
+ slice_files: dict[str, bytes] = {}
84
+ with tarfile.open(fileobj=io.BytesIO(blob), mode="r:gz") as tar:
85
+ for m in tar.getmembers():
86
+ if m.isfile():
87
+ slice_files[os.path.normpath(m.name)] = tar.extractfile(m).read()
88
+ except (ValueError, tarfile.TarError) as e:
89
+ res["error"] = f"slice output unreadable: {e}"
90
+ return res
91
+ res["report"] = json.loads(slice_files.pop("report.json", b"{}") or b"{}")
92
+ if not any(str(v).startswith("ok") for v in res["report"].values()):
93
+ res["error"] = "no pure string builder in the package"
94
+ return res
95
+ r2 = isolate.run(slice_files, "go build -o /work/prog . && /work/prog", image=image, out_dir=out_dir, purpose="evaluate",
96
+ ref=pkg, settings=cfg.get("isolate"))
97
+ res["audits"].append(r2["audit"])
98
+ if not r2["accepted"]:
99
+ res["error"] = "evaluate step refused by its audit"
100
+ return res
101
+ if r2["exit"] != 0 and not r2["stdout"].strip():
102
+ res["error"] = "slice did not compile"
103
+ res["stderr"] = r2["stderr"][-600:]
104
+ return res
105
+ for line in r2["stdout"].splitlines():
106
+ try:
107
+ o = json.loads(line)
108
+ except ValueError:
109
+ continue
110
+ if isinstance(o, dict) and o.get("fn"):
111
+ res["outputs"].append(o)
112
+ return res
113
+
114
+
115
+ def _seq(parts: list[str], sh: str) -> bool:
116
+ if not sh.startswith(parts[0]) or not sh.endswith(parts[-1]):
117
+ return False
118
+ i = 0
119
+ for p in parts:
120
+ j = sh.find(p, i)
121
+ if j < 0:
122
+ return False
123
+ i = j + len(p)
124
+ return True
125
+
126
+
127
+ def usable(o: dict) -> bool:
128
+ return not o.get("panic") and bool(SQLY.match(o.get("out") or "")) and "ZZARG" not in (o.get("out") or "")
129
+
130
+
131
+ def condition(o: dict) -> str:
132
+ return f"{o['fn']}({', '.join(o.get('args') or [])})"
133
+
134
+
135
+ def map_site(site: dict, outs: dict[str, list[dict]], src: holes.Source) -> tuple[list[tuple[str, str]], str]:
136
+ """Statements of one site from the package's builder outputs: ([(sql, condition)], how)."""
137
+ sql = site.get("sql") or ""
138
+ fam: list[tuple[str, str]] = []
139
+ win = holes.func_window(src.text(site["file"]), int(site.get("line") or 1), "go")
140
+ if sql.strip():
141
+ parts = shape(sql).split("«»")
142
+ fixed = sum(len(p) for p in parts)
143
+ if len(parts) > 1 and fixed >= 40:
144
+ for os_ in outs.values():
145
+ for o in os_:
146
+ if usable(o):
147
+ so = shape(o["out"])
148
+ if fixed >= 0.5 * len(so) and _seq(parts, so):
149
+ fam.append((o["out"], condition(o)))
150
+ if fam:
151
+ return fam, "whole statement = builder output"
152
+ pre = parts[0][:60]
153
+ for fn, os_ in outs.items():
154
+ if re.search(r"\b" + re.escape(fn) + r"\(", win):
155
+ for o in os_:
156
+ if usable(o) and len(pre) >= 30 and shape(o["out"]).startswith(pre):
157
+ fam.append((o["out"], condition(o)))
158
+ if fam:
159
+ return fam, "the site's function calls a builder"
160
+ calls = {}
161
+ for m in PH.finditer(sql):
162
+ mm = re.fullmatch(r"(?:\w+\.)?(\w+)\((.*)\)", m.group(1).strip(), re.S)
163
+ if mm and mm.group(1) in outs:
164
+ calls[m.group(1)] = [o for o in outs[mm.group(1)] if not o.get("panic") and "ZZARG" not in o["out"]]
165
+ if calls and all(calls.values()):
166
+ n = max(len(v) for v in calls.values())
167
+ for i in range(n):
168
+ filled = PH.sub(lambda m: calls[m.group(1)][i % len(calls[m.group(1)])]["out"] if m.group(1) in calls else m.group(0), sql)
169
+ cond = ", ".join(condition(v[i % len(v)]) for v in calls.values())
170
+ if "«" in filled:
171
+ vs, _ = holes.fill({**site, "sql": filled}, src)
172
+ fam += [(v["sql"], f"{cond}; {v['condition']}") for v in vs[:3] if v["basis"] == "filled"]
173
+ else:
174
+ fam.append((filled, cond))
175
+ if fam:
176
+ return fam, "parts filled by builder outputs"
177
+ return [], ""
178
+ ex = (site.get("expr") or "") + win
179
+ for fn, os_ in outs.items():
180
+ if re.search(r"\b" + re.escape(fn) + r"\(", ex):
181
+ fam += [(o["out"], condition(o)) for o in os_ if usable(o)]
182
+ return fam, "the site's argument calls a builder" if fam else ""
183
+
184
+
185
+ def evaluate(out_dir: Path, root: Path, inventory: dict, sites: list[dict] | None = None, settings: dict | None = None,
186
+ log=lambda m: None) -> dict:
187
+ """Slice every package that holds a Go run-time-built site; record what each site got in families_evaluated.json."""
188
+ from .build import EVALUATED, is_built, load
189
+ cfg = {**DEFAULTS, **(settings or {})}
190
+ sites = sites if sites is not None else [s for s in inventory.get("call_sites") or [] if s.get("language") == "go" and is_built(s)]
191
+ by_pkg: dict[str, list[dict]] = defaultdict(list)
192
+ for s in sites:
193
+ by_pkg[os.path.dirname(s["file"])].append(s)
194
+ src = holes.Source(root)
195
+ doc = load(Path(out_dir) / EVALUATED, {}) or {}
196
+ rows = {r["site_id"]: r for r in doc.get("sites") or []}
197
+ packages = {p["pkg"]: p for p in doc.get("packages") or []}
198
+ for pkg, ss in sorted(by_pkg.items(), key=lambda kv: -len(kv[1])):
199
+ res = slice_and_run(Path(root), pkg, out_dir, cfg)
200
+ outs: dict[str, list[dict]] = defaultdict(list)
201
+ for o in res["outputs"]:
202
+ outs[o["fn"]].append(o)
203
+ packages[pkg] = {"pkg": pkg, "sites": len(ss), "error": res.get("error", ""), "pure": sum(1 for v in res["report"].values() if str(v).startswith("ok")),
204
+ "impure": sum(1 for v in res["report"].values() if str(v).startswith("impure")), "outputs": len(res["outputs"]),
205
+ "accepted": all(a["accepted"] for a in res["audits"])}
206
+ log(f"{pkg}: {packages[pkg]}")
207
+ for s in ss:
208
+ row = rows.setdefault(s["id"], {"site_id": s["id"], "variants": [], "unbuilt": []})
209
+ row["variants"] = [v for v in row["variants"] if v.get("source") != "goslice"]
210
+ row["unbuilt"] = [u for u in row["unbuilt"] if u.get("source") != "goslice"]
211
+ if res.get("error"):
212
+ row["unbuilt"].append({"condition": "builder evaluation", "reason": "slice_not_evaluated", "detail": res["error"], "source": "goslice"})
213
+ continue
214
+ fam, how = map_site(s, outs, src)
215
+ seen = set()
216
+ for sql, cond in fam:
217
+ vid = model.variant_id(sql)
218
+ if vid in seen:
219
+ continue
220
+ seen.add(vid)
221
+ row["variants"].append({"sql": sql, "basis": "evaluated", "condition": cond, "source": "goslice", "how": how})
222
+ if len(seen) >= int(cfg["max_outputs_per_site"]):
223
+ break
224
+ if not fam:
225
+ row["unbuilt"].append({"condition": "builder evaluation", "reason": "no_builder_output_matches", "source": "goslice"})
226
+ doc = {"schema_version": 1, "sites": list(rows.values()), "packages": list(packages.values()),
227
+ "drivers": doc.get("drivers") or []}
228
+ (Path(out_dir) / EVALUATED).write_text(json.dumps(doc, indent=1))
229
+ return doc
@@ -0,0 +1,3 @@
1
+ module slicer
2
+
3
+ go 1.24