codebaton 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.
@@ -0,0 +1,251 @@
1
+ """Shared memory: AGENTS.md, HANDOFF.md, decisions.log and git checkpoints."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+
12
+ AGENTS_FILE = "AGENTS.md"
13
+ HANDOFF_FILE = "HANDOFF.md"
14
+ DECISIONS_FILE = "decisions.log"
15
+ STATE_DIR = ".codebaton"
16
+ BASELINE_FILE = "baseline.json"
17
+ DELETED = "<deleted>"
18
+
19
+ AGENTS_TEMPLATE = """# AGENTS.md
20
+
21
+ Shared instructions for every coding agent working in this repo (Codex reads this
22
+ natively; CLAUDE.md should point here).
23
+
24
+ ## Goal
25
+ <!-- One paragraph: what this project is for and what "done" looks like. -->
26
+
27
+ ## Conventions
28
+ - Small, focused changes. Run the tests before finishing.
29
+ - Never write secrets into files; read keys from env vars or the OS keychain.
30
+ - After work that changes files, update HANDOFF.md and append one line to decisions.log.
31
+ Plain questions need no update. Keep HANDOFF.md short (under ~60 lines): it is read
32
+ at every handover, so move old detail to decisions.log.
33
+ """
34
+
35
+ HANDOFF_TEMPLATE = """# HANDOFF
36
+
37
+ ## Goal
38
+ <!-- Current overall goal. -->
39
+
40
+ ## Done
41
+ - (nothing yet)
42
+
43
+ ## Next
44
+ - (nothing yet)
45
+
46
+ ## Open questions
47
+ - (none)
48
+ """
49
+
50
+ HANDOFF_INSTRUCTIONS = """
51
+ ---
52
+ When you finish (or must stop), you MUST:
53
+ 1. Rewrite HANDOFF.md with exactly these sections: "## Goal", "## Done", "## Next",
54
+ "## Open questions". Write it so a different agent can resume with no other context.
55
+ 2. Append one line to decisions.log: "<ISO timestamp> | <agent> | <decision and why>".
56
+ Do not commit; the router makes the git checkpoint.
57
+ """
58
+
59
+
60
+ @dataclass(frozen=True)
61
+ class Snapshot:
62
+ handoff_hash: str
63
+ decisions_size: int
64
+
65
+
66
+ class HandoffStore:
67
+ def __init__(self, repo: Path) -> None:
68
+ self.repo = repo
69
+
70
+ @property
71
+ def agents_path(self) -> Path:
72
+ return self.repo / AGENTS_FILE
73
+
74
+ @property
75
+ def handoff_path(self) -> Path:
76
+ return self.repo / HANDOFF_FILE
77
+
78
+ @property
79
+ def decisions_path(self) -> Path:
80
+ return self.repo / DECISIONS_FILE
81
+
82
+ def init_files(self) -> list[str]:
83
+ """Create AGENTS.md, HANDOFF.md and decisions.log if missing. Returns created names."""
84
+ created: list[str] = []
85
+ for path, content in (
86
+ (self.agents_path, AGENTS_TEMPLATE),
87
+ (self.handoff_path, HANDOFF_TEMPLATE),
88
+ (self.decisions_path, ""),
89
+ ):
90
+ if not path.exists():
91
+ path.write_text(content, encoding="utf-8")
92
+ created.append(path.name)
93
+ return created
94
+
95
+ def _read(self, path: Path) -> str:
96
+ return path.read_text(encoding="utf-8") if path.exists() else ""
97
+
98
+ def build_prompt(self, task: str, agent: str, instructions: str = "") -> str:
99
+ return (
100
+ f"You are {agent}, working in this repository as part of a multi-agent rotation.\n\n"
101
+ f"=== AGENTS.md ===\n{self._read(self.agents_path).strip()}\n\n"
102
+ f"=== HANDOFF.md (state left by the previous agent) ===\n"
103
+ f"{self._read(self.handoff_path).strip()}\n\n"
104
+ f"=== TASK ===\n{task.strip()}\n"
105
+ f"{instructions or HANDOFF_INSTRUCTIONS}"
106
+ )
107
+
108
+ def snapshot(self) -> Snapshot:
109
+ data = self._read(self.handoff_path).encode()
110
+ size = self.decisions_path.stat().st_size if self.decisions_path.exists() else 0
111
+ return Snapshot(hashlib.sha256(data).hexdigest(), size)
112
+
113
+ def agent_updated(self, before: Snapshot) -> tuple[bool, bool]:
114
+ """Return (handoff rewritten, decisions appended) since ``before``."""
115
+ after = self.snapshot()
116
+ return (
117
+ after.handoff_hash != before.handoff_hash,
118
+ after.decisions_size > before.decisions_size,
119
+ )
120
+
121
+ def write_handoff(
122
+ self, goal: str, done: list[str], next_steps: list[str], questions: list[str]
123
+ ) -> None:
124
+ def bullets(items: list[str]) -> str:
125
+ return "\n".join(f"- {i}" for i in items) if items else "- (none)"
126
+
127
+ self.handoff_path.write_text(
128
+ f"# HANDOFF\n\n## Goal\n{goal}\n\n## Done\n{bullets(done)}\n\n"
129
+ f"## Next\n{bullets(next_steps)}\n\n## Open questions\n{bullets(questions)}\n",
130
+ encoding="utf-8",
131
+ )
132
+
133
+ def append_decision(self, actor: str, decision: str) -> None:
134
+ ts = datetime.now(UTC).isoformat(timespec="seconds")
135
+ line = f"{ts} | {actor} | {' '.join(decision.split())}\n"
136
+ with self.decisions_path.open("a", encoding="utf-8") as fh:
137
+ fh.write(line)
138
+
139
+ def _git(self, *args: str) -> subprocess.CompletedProcess[str]:
140
+ return subprocess.run(
141
+ ["git", *args], cwd=self.repo, capture_output=True, text=True, check=False
142
+ )
143
+
144
+ def git_checkpoint(self, message: str, paths: list[str] | None = None) -> str | None:
145
+ """Commit a checkpoint. Returns the commit SHA, or None if skipped.
146
+
147
+ ``paths=None`` commits every change (used by unattended ``run``, which owns the repo).
148
+ With ``paths``, only those files are staged and committed; anything else the user
149
+ has changed or staged is left exactly as it was.
150
+ """
151
+ if not (self.repo / ".git").exists():
152
+ return None
153
+ if paths is None:
154
+ self._git("add", "-A")
155
+ if self._git("diff", "--cached", "--quiet").returncode == 0:
156
+ return None # nothing to commit
157
+ commit = ["commit", "-m", message]
158
+ else:
159
+ if not paths:
160
+ return None
161
+ self._git("add", "-A", "--", *paths)
162
+ if self._git("diff", "--cached", "--quiet", "--", *paths).returncode == 0:
163
+ return None
164
+ commit = ["commit", "-m", message, "--", *paths] # commits only these paths
165
+ # Hooks stay on: a secret scanner in pre-commit must be able to block a checkpoint.
166
+ if self._git(*commit).returncode != 0:
167
+ return None
168
+ sha = self._git("rev-parse", "HEAD").stdout.strip()
169
+ return sha or None
170
+
171
+ # -- per-turn checkpoints for interactive sessions --------------------------------------
172
+
173
+ @property
174
+ def baseline_path(self) -> Path:
175
+ return self.repo / STATE_DIR / BASELINE_FILE
176
+
177
+ def dirty_files(self) -> dict[str, str]:
178
+ """Uncommitted files (tracked or new, not ignored) -> fingerprint of their content."""
179
+ out = self._git("status", "--porcelain=v1", "-z", "--untracked-files=all")
180
+ if out.returncode != 0:
181
+ return {}
182
+ entries = out.stdout.split("\0")
183
+ paths: list[str] = []
184
+ i = 0
185
+ while i < len(entries):
186
+ entry = entries[i]
187
+ i += 1
188
+ if len(entry) < 4:
189
+ continue
190
+ status, path = entry[:2], entry[3:]
191
+ paths.append(path)
192
+ if "R" in status or "C" in status: # rename/copy: next field is the old path
193
+ if i < len(entries) and entries[i]:
194
+ paths.append(entries[i])
195
+ i += 1
196
+ state: dict[str, str] = {}
197
+ for path in paths:
198
+ if path == STATE_DIR or path.startswith(f"{STATE_DIR}/"):
199
+ continue # the router's own state is never committed
200
+ full = self.repo / path
201
+ try:
202
+ state[path] = hashlib.sha256(full.read_bytes()).hexdigest()
203
+ except IsADirectoryError:
204
+ state[path] = "<dir>"
205
+ except OSError:
206
+ state[path] = DELETED
207
+ return state
208
+
209
+ def save_baseline(self, state: dict[str, str] | None = None) -> None:
210
+ """Remember what was already uncommitted, so checkpoints leave it alone."""
211
+ self.baseline_path.parent.mkdir(parents=True, exist_ok=True)
212
+ data = self.dirty_files() if state is None else state
213
+ self.baseline_path.write_text(json.dumps(data, sort_keys=True), encoding="utf-8")
214
+
215
+ def load_baseline(self) -> dict[str, str] | None:
216
+ try:
217
+ data = json.loads(self.baseline_path.read_text(encoding="utf-8"))
218
+ except (OSError, ValueError):
219
+ return None
220
+ return data if isinstance(data, dict) else None
221
+
222
+ def checkpoint_turn(self, message: str) -> str | None:
223
+ """Commit only files created or changed since the last baseline, then move it on.
224
+
225
+ Files that were already uncommitted when the session started, and that the agent
226
+ did not touch, are never committed. Without a baseline (a session opened by an
227
+ older version), the current state becomes the baseline and nothing is committed.
228
+ """
229
+ if not (self.repo / ".git").exists():
230
+ return None
231
+ baseline = self.load_baseline()
232
+ current = self.dirty_files()
233
+ if baseline is None:
234
+ self.save_baseline(current)
235
+ return None
236
+ changed = sorted(p for p, h in current.items() if baseline.get(p) != h)
237
+ # A file that was dirty at the baseline and is now clean again was reverted or
238
+ # committed by someone else: nothing to do for it.
239
+ sha = self.git_checkpoint(message, changed) if changed else None
240
+ after = self.dirty_files()
241
+ if changed and sha is None:
242
+ # The commit was refused (e.g. a pre-commit hook): keep those files "changed" so
243
+ # the next checkpoint tries again instead of silently adopting them.
244
+ for path in changed:
245
+ if after.get(path) == current.get(path):
246
+ if path in baseline:
247
+ after[path] = baseline[path]
248
+ else:
249
+ after.pop(path, None)
250
+ self.save_baseline(after)
251
+ return sha
@@ -0,0 +1,205 @@
1
+ """Model tier routing within a provider. Rule: when in doubt, go up a tier, never down.
2
+
3
+ Order of precedence:
4
+ 1. ``--model`` override pins the tier; nothing else applies.
5
+ 2. ``force_opus_if`` (paths or keywords) forces opus.
6
+ 3. Rules: an explicit task type, or task-type phrases found in the task text.
7
+ 4. Classifier (Haiku), only when rules are inconclusive. Below
8
+ ``min_confidence_to_downgrade`` the default tier is used, and the classifier alone
9
+ never picks haiku (it is capped at sonnet).
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ import re
16
+ from collections.abc import Callable
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+ from codebaton.config import TIER_ORDER, ModelRoutingConfig, Tier
21
+ from codebaton.plugins.base import Executor
22
+ from codebaton.plugins.providers._common import tail
23
+
24
+ CODEX_TIER_KEYS: dict[Tier, str] = {"haiku": "light", "sonnet": "medium", "opus": "top"}
25
+
26
+ # (task text, known task types) -> (task type or None, confidence 0..1)
27
+ Classifier = Callable[[str, list[str]], tuple[str | None, float]]
28
+
29
+
30
+ @dataclass(frozen=True)
31
+ class TierDecision:
32
+ tier: Tier
33
+ reason: str
34
+ task_type: str | None = None
35
+ confidence: float | None = None
36
+ # override | force | rule | classifier | default: lets callers tell a real rule match
37
+ # from "nothing matched, used the default".
38
+ source: str = "default"
39
+
40
+
41
+ def next_tier(tier: Tier) -> Tier | None:
42
+ idx = TIER_ORDER.index(tier)
43
+ return TIER_ORDER[idx + 1] if idx + 1 < len(TIER_ORDER) else None
44
+
45
+
46
+ def glob_to_regex(pattern: str) -> re.Pattern[str]:
47
+ out = ""
48
+ i = 0
49
+ while i < len(pattern):
50
+ if pattern.startswith("**/", i):
51
+ out += "(?:.*/)?"
52
+ i += 3
53
+ elif pattern.startswith("**", i):
54
+ out += ".*"
55
+ i += 2
56
+ elif pattern[i] == "*":
57
+ out += "[^/]*"
58
+ i += 1
59
+ elif pattern[i] == "?":
60
+ out += "[^/]"
61
+ i += 1
62
+ else:
63
+ out += re.escape(pattern[i])
64
+ i += 1
65
+ return re.compile(out + r"\Z")
66
+
67
+
68
+ _PATH_TOKEN = re.compile(r"[\w.\-]*(?:/[\w.\-*]+)+/?|[\w\-]+\.(?:py|ts|js|go|rs|java|sql|yaml|yml)")
69
+
70
+
71
+ def paths_in(text: str) -> list[str]:
72
+ return [m.group(0).strip("./") or m.group(0) for m in _PATH_TOKEN.finditer(text)]
73
+
74
+
75
+ def _tier_for_type(cfg: ModelRoutingConfig, task_type: str) -> Tier | None:
76
+ found: Tier | None = None
77
+ for tier in TIER_ORDER: # ascending, so the highest matching tier wins
78
+ rule = cfg.tiers.get(tier)
79
+ if rule and task_type in rule.task_types:
80
+ found = tier
81
+ return found
82
+
83
+
84
+ def _known_types(cfg: ModelRoutingConfig) -> list[str]:
85
+ return sorted({t for rule in cfg.tiers.values() for t in rule.task_types})
86
+
87
+
88
+ def decide_tier(
89
+ task: str,
90
+ cfg: ModelRoutingConfig,
91
+ *,
92
+ override: str | None = None,
93
+ task_type: str | None = None,
94
+ paths: list[str] | None = None,
95
+ classifier: Classifier | None = None,
96
+ ) -> TierDecision:
97
+ if override:
98
+ if override not in TIER_ORDER:
99
+ raise ValueError(f"--model must be one of {', '.join(TIER_ORDER)}")
100
+ return TierDecision(
101
+ override, f"pinned by {cfg.override_flag} {override}", source="override"
102
+ )
103
+
104
+ lowered = task.lower()
105
+ touched = [*(paths or []), *paths_in(task)]
106
+ for pattern in cfg.force_opus_if.paths:
107
+ rx = glob_to_regex(pattern)
108
+ for p in touched:
109
+ if rx.match(p.lstrip("./")):
110
+ return TierDecision(
111
+ "opus", f"force_opus_if path '{pattern}' matched '{p}'", source="force"
112
+ )
113
+ for kw in cfg.force_opus_if.keywords:
114
+ if re.search(rf"\b{re.escape(kw.lower())}", lowered):
115
+ return TierDecision("opus", f"force_opus_if keyword '{kw}'", source="force")
116
+
117
+ if task_type:
118
+ tier = _tier_for_type(cfg, task_type)
119
+ if tier is None:
120
+ return TierDecision(
121
+ cfg.default_tier, f"unknown task type '{task_type}': default", task_type
122
+ )
123
+ return TierDecision(tier, f"task type '{task_type}' (explicit)", task_type, source="rule")
124
+
125
+ matched: list[tuple[Tier, str]] = []
126
+ for ttype, phrases in cfg.task_type_keywords.items():
127
+ if any(phrase.lower() in lowered for phrase in phrases):
128
+ tier = _tier_for_type(cfg, ttype)
129
+ if tier:
130
+ matched.append((tier, ttype))
131
+ if matched:
132
+ tier, ttype = max(matched, key=lambda m: TIER_ORDER.index(m[0]))
133
+ return TierDecision(
134
+ tier, f"rule: task text matches task type '{ttype}'", ttype, source="rule"
135
+ )
136
+
137
+ if cfg.classifier != "rules_then_haiku" or classifier is None:
138
+ return TierDecision(cfg.default_tier, "no rule matched: default tier")
139
+
140
+ try:
141
+ ctype, confidence = classifier(task, _known_types(cfg))
142
+ except Exception as exc: # classifier failure must not downgrade
143
+ return TierDecision(cfg.default_tier, f"classifier failed ({exc}): default tier")
144
+ ctier = _tier_for_type(cfg, ctype) if ctype else None
145
+ if ctier is None or confidence < cfg.min_confidence_to_downgrade:
146
+ return TierDecision(
147
+ cfg.default_tier,
148
+ f"classifier inconclusive (type={ctype}, confidence={confidence:.2f}): default tier",
149
+ ctype,
150
+ confidence,
151
+ )
152
+ if ctier == "haiku":
153
+ ctier = "sonnet"
154
+ reason = f"classifier: '{ctype}' ({confidence:.2f}); capped at sonnet (haiku is rules-only)"
155
+ else:
156
+ reason = f"classifier: '{ctype}' ({confidence:.2f})"
157
+ if TIER_ORDER.index(ctier) > TIER_ORDER.index(cfg.default_tier):
158
+ ctier = cfg.default_tier
159
+ return TierDecision(ctier, reason, ctype, confidence, source="classifier")
160
+
161
+
162
+ def native_model(cfg: ModelRoutingConfig, provider: str, tier: Tier) -> tuple[str, str | None]:
163
+ """Map a tier to (provider-native model, reasoning effort). Empty model = CLI default."""
164
+ table = cfg.provider_tiers.get(provider, {})
165
+ entry = table.get(tier) or table.get(CODEX_TIER_KEYS[tier])
166
+ if entry is not None:
167
+ return entry.model, entry.reasoning_effort
168
+ if provider == "claude_code":
169
+ return tier, None # claude accepts the aliases haiku / sonnet / opus
170
+ return "", None
171
+
172
+
173
+ class HaikuClassifier:
174
+ """Ask Claude Haiku (via the official CLI, no tools) to label the task type."""
175
+
176
+ def __init__(self, executor: Executor, cwd: Path) -> None:
177
+ self.executor = executor
178
+ self.cwd = cwd
179
+
180
+ def __call__(self, task: str, task_types: list[str]) -> tuple[str | None, float]:
181
+ prompt = (
182
+ "Classify this coding task into exactly one task type. Reply with only JSON: "
183
+ '{"task_type": "<one of the list or null>", "confidence": <0..1>}.\n'
184
+ f"Task types: {', '.join(task_types)}\nTask: {task}"
185
+ )
186
+ argv = [
187
+ "claude",
188
+ "-p",
189
+ "--output-format",
190
+ "json",
191
+ "--model",
192
+ "haiku",
193
+ "--permission-mode",
194
+ "dontAsk",
195
+ ]
196
+ result = self.executor.run(argv, self.cwd, 120, stdin=prompt)
197
+ if result.returncode != 0:
198
+ raise RuntimeError(f"classifier exited {result.returncode}: {tail(result.stderr, 200)}")
199
+ text = str(json.loads(result.stdout).get("result", ""))
200
+ match = re.search(r"\{.*\}", text, re.DOTALL)
201
+ if not match:
202
+ raise RuntimeError("classifier returned no JSON")
203
+ data = json.loads(match.group(0))
204
+ ttype = data.get("task_type")
205
+ return (ttype if ttype in task_types else None), float(data.get("confidence", 0))
@@ -0,0 +1,98 @@
1
+ """Policy engine: approval profiles compiled to each CLI's native permission flags.
2
+
3
+ Approvals classify actions (read, edit, run command, network, push), not tasks.
4
+
5
+ Profiles (v0):
6
+ - overnight: no human prompt. Agent may edit files and run only allow-listed commands.
7
+ Codex runs sandboxed (workspace-write) with approval_policy=never.
8
+ - per_session: same agent permissions; the human approves once per ``codebaton run``.
9
+ - strict: the human approves every provider attempt; Claude gets no shell at all;
10
+ web and push are always off.
11
+
12
+ Web access and ``git push`` are switches in router.yaml (``allow_web``, ``allow_push``),
13
+ off unless turned on.
14
+
15
+ Flags verified with ``claude --help`` (2.1.334) and ``codex exec --help`` (0.173.0).
16
+ Org-locked minimum profiles and the approval gateway are out of scope for v0.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import sys
22
+ from collections.abc import Callable
23
+
24
+ from codebaton.config import Profile
25
+
26
+ CLAUDE_FILE_TOOLS = ["Read", "Edit", "Write", "Glob", "Grep"]
27
+ CLAUDE_WEB_TOOLS = ["WebFetch", "WebSearch"]
28
+ CLAUDE_PUSH = "Bash(git push:*)"
29
+
30
+
31
+ class PolicyError(ValueError):
32
+ pass
33
+
34
+
35
+ def compile_flags(
36
+ profile: Profile,
37
+ adapter: str,
38
+ allowed_commands: list[str],
39
+ *,
40
+ allow_web: bool = False,
41
+ allow_push: bool = False,
42
+ allow_all_commands: bool = False,
43
+ ) -> list[str]:
44
+ """Return the native permission arguments for ``adapter`` under ``profile``.
45
+
46
+ ``allow_web`` / ``allow_push`` / ``allow_all_commands`` are personal-use switches from
47
+ router.yaml. The strict profile ignores them.
48
+ """
49
+ if profile == "strict":
50
+ allow_web = allow_push = allow_all_commands = False
51
+ if adapter == "claude_code":
52
+ allowed = list(CLAUDE_FILE_TOOLS)
53
+ if allow_all_commands:
54
+ allowed.append("Bash") # any shell command (git push still follows allow_push)
55
+ elif profile != "strict":
56
+ allowed += [f"Bash({c}:*)" for c in allowed_commands]
57
+ denied: list[str] = []
58
+ (allowed if allow_web else denied).extend(CLAUDE_WEB_TOOLS)
59
+ (allowed if allow_push else denied).append(CLAUDE_PUSH)
60
+ # dontAsk denies anything not pre-approved instead of hanging on a prompt.
61
+ mode = "acceptEdits" if profile == "per_session" else "dontAsk"
62
+ flags = ["--permission-mode", mode, "--allowedTools", *allowed]
63
+ if denied:
64
+ flags += ["--disallowedTools", *denied]
65
+ return flags
66
+ if adapter == "codex":
67
+ # Verified against codex 0.173.0 config parsing: sandbox_mode is one of
68
+ # read-only|workspace-write|danger-full-access; approval_policy one of
69
+ # untrusted|on-failure|on-request|granular|never; web_search one of
70
+ # disabled|cached|indexed|live; network_access is a boolean. All passed as -c so
71
+ # they work for both `codex exec` and `codex exec resume` (which has no -s).
72
+ # Codex commands already run freely inside its workspace sandbox.
73
+ flags = ["-c", 'sandbox_mode="workspace-write"', "-c", 'approval_policy="never"']
74
+ if allow_web:
75
+ flags += ["-c", 'web_search="live"']
76
+ network = allow_web or allow_push # push needs the network too
77
+ flags += ["-c", f"sandbox_workspace_write.network_access={str(network).lower()}"]
78
+ return flags
79
+ raise PolicyError(f"no permission mapping for adapter '{adapter}'")
80
+
81
+
82
+ def needs_session_approval(profile: Profile) -> bool:
83
+ return profile == "per_session"
84
+
85
+
86
+ def needs_attempt_approval(profile: Profile) -> bool:
87
+ return profile == "strict"
88
+
89
+
90
+ Confirm = Callable[[str], bool]
91
+
92
+
93
+ def terminal_confirm(question: str) -> bool:
94
+ """Ask on the terminal. No TTY means nobody can answer: default to pause (deny)."""
95
+ if not sys.stdin.isatty():
96
+ return False
97
+ answer = input(f"{question} [y/N] ").strip().lower()
98
+ return answer in {"y", "yes"}