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
codecop/agent.py ADDED
@@ -0,0 +1,221 @@
1
+ """Running the developer's coding agent headless.
2
+
3
+ One interface, AgentRunner, so Claude and Codex are interchangeable and CI can
4
+ swap in an API key. CodeCop only starts the official binary as a subprocess. It
5
+ never reads, stores or forwards the agent's credentials.
6
+
7
+ The agent gets read-only tools. The repo's own settings, hooks and MCP servers
8
+ are not loaded, so scanning a repo cannot run that repo's hooks.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import json
14
+ import os
15
+ import re
16
+ import shutil
17
+ import subprocess
18
+ from dataclasses import dataclass, field
19
+ from pathlib import Path
20
+
21
+ READ_ONLY_TOOLS = ["Read", "Grep", "Glob"]
22
+
23
+
24
+ class AgentError(RuntimeError):
25
+ pass
26
+
27
+
28
+ class UsageLimitError(AgentError):
29
+ """The agent CLI said the account cannot run more now. `kind`: `usage_limit` (the plan's usage window is used up:
30
+ `resets_at`, unix seconds, when the CLI gave it), `rate_limit` (too many requests a minute: HTTP 429) or `overloaded`
31
+ (the service is busy: 529). Read from the CLI's structured output (its rate_limit_event, the result's
32
+ api_error_status and api_error_type), the result text only when neither is there."""
33
+
34
+ def __init__(self, message: str, *, kind: str = "usage_limit", resets_at: float | None = None, limit_type: str = "",
35
+ status: int | None = None):
36
+ super().__init__(message)
37
+ self.kind, self.resets_at, self.limit_type, self.status = kind, resets_at, limit_type, status
38
+
39
+
40
+ @dataclass
41
+ class AgentResult:
42
+ output: dict # the structured output, validated against the schema by the agent CLI
43
+ model: str = ""
44
+ cost_usd: float = 0.0
45
+ duration_s: float = 0.0
46
+ turns: int = 0
47
+ usage: dict = field(default_factory=dict)
48
+ limit: dict = field(default_factory=dict) # the last rate_limit_event's info (status, resetsAt, rateLimitType, utilization)
49
+
50
+
51
+ # The words the CLI's result text has used for a used-up plan window, when no structured field says it (older CLIs:
52
+ # "Claude AI usage limit reached|1735689600"; later "5-hour limit reached ∙ resets 3pm").
53
+ LIMIT_WORDS = re.compile(r"usage limit reached|limit reached\b.*\bresets|hit your (?:usage )?limit|out of (?:extra )?usage", re.I)
54
+
55
+
56
+ def limit_of(events: list[dict], result: dict | None, returncode: int = 0) -> UsageLimitError | None:
57
+ """The limit the agent CLI's stream-json output says the call ran into, or None. `events`: every line it wrote."""
58
+ info: dict = {}
59
+ for ev in events:
60
+ if ev.get("type") == "rate_limit_event" and isinstance(ev.get("rate_limit_info"), dict):
61
+ info = ev["rate_limit_info"]
62
+ r = result or {}
63
+ status = r.get("api_error_status")
64
+ etype = str(r.get("api_error_type") or "")
65
+ text = str(r.get("result") or "")
66
+ resets = info.get("resetsAt")
67
+ try:
68
+ resets = float(resets) if resets else None
69
+ except (TypeError, ValueError):
70
+ resets = None
71
+ rejected = info.get("status") == "rejected" and info.get("overageStatus") not in ("allowed", "allowed_warning")
72
+ if r.get("is_error") or result is None or returncode:
73
+ if rejected:
74
+ return UsageLimitError(f"the plan's usage limit ({info.get('rateLimitType') or 'window'}) is reached", kind="usage_limit",
75
+ resets_at=resets, limit_type=str(info.get("rateLimitType") or ""), status=status)
76
+ if status == 429 or etype == "rate_limit_error":
77
+ return UsageLimitError(f"rate limited (HTTP 429): {text[:200]}", kind="rate_limit", resets_at=resets, status=status or 429,
78
+ limit_type=str(info.get("rateLimitType") or ""))
79
+ if status == 529 or etype == "overloaded_error":
80
+ return UsageLimitError(f"the service is overloaded: {text[:200]}", kind="overloaded", status=status or 529)
81
+ m = LIMIT_WORDS.search(text)
82
+ if m:
83
+ stamp = re.search(r"\|(\d{9,11})\b", text)
84
+ return UsageLimitError(f"the plan's usage limit is reached: {text[:200]}", kind="usage_limit",
85
+ resets_at=float(stamp.group(1)) if stamp else resets)
86
+ return None
87
+
88
+
89
+ class AgentRunner:
90
+ name = "base"
91
+
92
+ def available(self) -> bool:
93
+ raise NotImplementedError
94
+
95
+ def billing_note(self) -> str:
96
+ """Which account a run will be billed to, shown before the run."""
97
+ raise NotImplementedError
98
+
99
+ def run(self, prompt: str, schema: dict, cwd: Path, *, model: str | None = None,
100
+ max_budget_usd: float | None = None, timeout_s: int = 1800) -> AgentResult:
101
+ raise NotImplementedError
102
+
103
+
104
+ def billing(runner) -> dict:
105
+ """For a stage file: how the run was paid for, and what its cost figure is.
106
+
107
+ The agent CLI reports a cost computed at API prices. On a plan login nothing is billed per token, so the
108
+ figure is an estimate of what the same work would cost through the API, not a charge."""
109
+ mode = getattr(runner, "billing_mode", lambda: "unknown")()
110
+ return {"billing": mode, "cost_basis": "estimate at API rates" if mode != "api_key" else "billed to the API key, as reported by the agent CLI"}
111
+
112
+
113
+ class ClaudeRunner(AgentRunner):
114
+ name = "claude"
115
+ default_model = "opus"
116
+
117
+ def billing_mode(self) -> str:
118
+ """`api_key` when the run is billed per token to ANTHROPIC_API_KEY, `plan` when it uses the logged-in plan."""
119
+ return "api_key" if os.environ.get("ANTHROPIC_API_KEY") else "plan"
120
+
121
+ def available(self) -> bool:
122
+ return shutil.which("claude") is not None
123
+
124
+ def billing_note(self) -> str:
125
+ if os.environ.get("ANTHROPIC_API_KEY"):
126
+ return "ANTHROPIC_API_KEY is set: this run is billed to that API key, not to a Claude subscription."
127
+ return "No ANTHROPIC_API_KEY set: this run uses your logged-in Claude Code account and its plan limits."
128
+
129
+ def run(self, prompt: str, schema: dict, cwd: Path, *, model: str | None = None,
130
+ max_budget_usd: float | None = None, timeout_s: int = 1800) -> AgentResult:
131
+ cmd = [
132
+ "claude", "-p",
133
+ # every message, one JSON object a line: the last is the result; a rate_limit_event says the plan's window
134
+ "--output-format", "stream-json", "--verbose",
135
+ "--json-schema", json.dumps(schema),
136
+ "--model", model or self.default_model,
137
+ "--tools", ",".join(READ_ONLY_TOOLS),
138
+ "--allowedTools", *READ_ONLY_TOOLS,
139
+ "--setting-sources", "", # do not load user, project or local settings: no hooks, no plugins
140
+ "--strict-mcp-config", # no MCP servers
141
+ "--no-session-persistence",
142
+ ]
143
+ if max_budget_usd:
144
+ cmd += ["--max-budget-usd", str(max_budget_usd)]
145
+ try:
146
+ proc = subprocess.run(cmd, input=prompt, capture_output=True, text=True, cwd=str(cwd), timeout=timeout_s)
147
+ except subprocess.TimeoutExpired as e:
148
+ raise AgentError(f"claude did not finish within {timeout_s}s") from e
149
+ events = parse_lines(proc.stdout)
150
+ data = next((e for e in reversed(events) if e.get("type") == "result"), None)
151
+ limited = limit_of(events, data, proc.returncode)
152
+ if limited is not None:
153
+ raise limited
154
+ if data is None:
155
+ raise AgentError(f"claude returned no JSON (exit {proc.returncode}): {(proc.stderr or proc.stdout)[:500]}")
156
+ if data.get("is_error") or data.get("structured_output") is None:
157
+ raise AgentError(f"claude run failed ({data.get('subtype')}): {str(data.get('result'))[:500]}")
158
+ usage = data.get("usage") or {}
159
+ info = next((e["rate_limit_info"] for e in reversed(events) if e.get("type") == "rate_limit_event"
160
+ and isinstance(e.get("rate_limit_info"), dict)), {})
161
+ return AgentResult(
162
+ limit={k: info.get(k) for k in ("status", "resetsAt", "rateLimitType", "utilization", "surpassedThreshold") if info.get(k) is not None},
163
+ output=data["structured_output"],
164
+ model=next(iter(data.get("modelUsage") or {}), model or self.default_model),
165
+ cost_usd=float(data.get("total_cost_usd") or 0.0),
166
+ duration_s=float(data.get("duration_ms") or 0) / 1000,
167
+ turns=int(data.get("num_turns") or 0),
168
+ usage={k: usage.get(k, 0) for k in ("input_tokens", "output_tokens", "cache_creation_input_tokens", "cache_read_input_tokens")},
169
+ )
170
+
171
+
172
+ def parse_lines(stdout: str) -> list[dict]:
173
+ """The agent CLI's stream-json output (one object a line), or its single json object (`--output-format json`)."""
174
+ text = (stdout or "").strip()
175
+ if not text:
176
+ return []
177
+ try:
178
+ one = json.loads(text)
179
+ if isinstance(one, dict):
180
+ return [{"type": "result", **one} if "type" not in one else one]
181
+ if isinstance(one, list):
182
+ return [x for x in one if isinstance(x, dict)]
183
+ except json.JSONDecodeError:
184
+ pass
185
+ out = []
186
+ for line in text.splitlines():
187
+ line = line.strip()
188
+ if not line.startswith("{"):
189
+ continue
190
+ try:
191
+ obj = json.loads(line)
192
+ except json.JSONDecodeError:
193
+ continue
194
+ if isinstance(obj, dict):
195
+ out.append(obj)
196
+ return out
197
+
198
+
199
+ RUNNERS: dict[str, type[AgentRunner]] = {"claude": ClaudeRunner}
200
+ # The agent every paid step (rank, profile, observed/scenario variants, groups --agent-variants) runs when `--agent` is
201
+ # not given: one value, so no step can default to a name the others do not know.
202
+ DEFAULT_AGENT = "claude"
203
+ # Names an earlier option default or a user's habit used for one of RUNNERS.
204
+ ALIASES = {"claude-code": "claude", "claude_code": "claude"}
205
+
206
+
207
+ def agent_name(name: str | None) -> str:
208
+ """The runner a `--agent` value selects: the default when empty, an alias resolved, else the name as given."""
209
+ n = (name or "").strip() or DEFAULT_AGENT
210
+ return ALIASES.get(n.lower(), n)
211
+
212
+
213
+ def get_runner(name: str | None = None) -> AgentRunner:
214
+ """The one way every agent-calling step gets its runner (see DEFAULT_AGENT)."""
215
+ name = agent_name(name)
216
+ if name not in RUNNERS:
217
+ raise AgentError(f"Unknown agent '{name}'. Available: {', '.join(RUNNERS)}")
218
+ runner = RUNNERS[name]()
219
+ if not runner.available():
220
+ raise AgentError(f"The '{name}' CLI is not installed or not on PATH.")
221
+ return runner