scribe-gate 0.1.3__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.
scribe/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ """scribe-gate: a validation gauntlet / trust gate for agent-written Python code."""
2
+
3
+ __version__ = "0.1.3"
4
+ __all__ = ["__version__"]
scribe/agent.py ADDED
@@ -0,0 +1,396 @@
1
+ """ScribeAgent: orchestrates the validation gauntlet end to end."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ import sys
9
+ import traceback
10
+ from collections.abc import Callable
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from typing import Any
14
+
15
+ from . import __version__
16
+ from .config import ScribeConfig
17
+ from .environment import EnvironmentManager
18
+ from .llm import LLMBackend, LLMClient, build_backend
19
+ from .models import (
20
+ STATUS_FAILURE,
21
+ STATUS_PENDING,
22
+ STATUS_SKIPPED,
23
+ STATUS_SUCCESS,
24
+ FinalReport,
25
+ ScribeError,
26
+ ScribeInputError,
27
+ StepResult,
28
+ )
29
+ from .report import render
30
+ from .runner import ToolRunner
31
+ from .steps import WorkflowSteps
32
+
33
+ APP_NAME = "scribe-gate"
34
+
35
+ # Steps that consume the previous step's details as an argument.
36
+ _STEPS_WITH_DEPENDENCIES = {"generate_tests", "save_tests", "execute_tests"}
37
+
38
+
39
+ class ScribeAgent:
40
+ """Runs the configured gauntlet steps in order and emits a final report."""
41
+
42
+ def __init__(self, args: argparse.Namespace, llm_backend: LLMBackend | None = None) -> None:
43
+ self.args = args
44
+ self.in_place: bool = bool(getattr(args, "in_place", False))
45
+
46
+ # Commit policy: NEVER commit unless explicitly requested, and even
47
+ # then only with operator approval (see request_commit_approval).
48
+ self._review_only = bool(args.review_only)
49
+ self._commit_requested = bool(args.commit) and not self._review_only
50
+ self._do_commit = self._commit_requested and not bool(args.no_commit)
51
+
52
+ self._run_id = f"scribe_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S_%f')}"
53
+ self._logger = logging.getLogger(APP_NAME)
54
+ self._overall_success = True
55
+
56
+ self.source_file_path: Path | None = None
57
+ self.target_file_path: Path | None = None
58
+ self.target_file_relative: str = str(args.target_file)
59
+
60
+ try:
61
+ target_dir = Path(args.target_dir).expanduser().resolve()
62
+ self.config = ScribeConfig(
63
+ config_path_override=args.config_file,
64
+ project_dir_for_local_config=target_dir,
65
+ )
66
+ self.target_dir = self._validate_target_dir(target_dir)
67
+ self.tool_runner = ToolRunner(self.config)
68
+ self.env_manager = EnvironmentManager(self.target_dir, self.tool_runner, self.config)
69
+ backend = llm_backend or build_backend(
70
+ self.config,
71
+ backend=args.llm_backend,
72
+ model=args.llm_model,
73
+ base_url=args.llm_base_url,
74
+ )
75
+ self.llm_client = LLMClient(self.config, backend)
76
+ self.git_exe = self._find_git()
77
+ self.report_data: FinalReport = self._initialize_report()
78
+ self.workflow = WorkflowSteps(self)
79
+ except ScribeError as exc:
80
+ self._emit_minimal_error_report(f"Initialization failed: {exc}")
81
+ raise SystemExit(2) from exc
82
+ except Exception as exc: # noqa: BLE001 - init must never crash silently
83
+ self._emit_minimal_error_report(
84
+ f"Unexpected initialization error: {exc}", include_traceback=True
85
+ )
86
+ raise SystemExit(2) from exc
87
+
88
+ self._logger.info(
89
+ "%s v%s starting | run=%s | target=%s | commit_planned=%s",
90
+ APP_NAME,
91
+ __version__,
92
+ self._run_id,
93
+ self.target_dir,
94
+ self._do_commit,
95
+ )
96
+
97
+ # ------------------------------------------------------------------
98
+ # setup helpers
99
+ # ------------------------------------------------------------------
100
+ def _validate_target_dir(self, target_dir: Path) -> Path:
101
+ if not target_dir.is_dir():
102
+ raise ScribeInputError(f"Target dir is not a directory: {target_dir}")
103
+ allowed = [
104
+ Path(p).expanduser().resolve() for p in self.config.get_list("allowed_target_bases", [])
105
+ ]
106
+ if allowed and not any(target_dir.is_relative_to(base) for base in allowed):
107
+ raise ScribeInputError(
108
+ f"Target dir '{target_dir}' is outside allowed bases: {allowed}. "
109
+ "Adjust 'allowed_target_bases' in scribe.toml to permit it."
110
+ )
111
+ return target_dir
112
+
113
+ def _find_git(self) -> str | None:
114
+ try:
115
+ return str(self.tool_runner._find_executable("git"))
116
+ except ScribeError:
117
+ self._logger.warning("git executable not found; commit step will skip.")
118
+ return None
119
+
120
+ def _initialize_report(self) -> FinalReport:
121
+ return {
122
+ "scribe_version": __version__,
123
+ "run_id": self._run_id,
124
+ "start_time": datetime.now(timezone.utc).isoformat(),
125
+ "end_time": "",
126
+ "total_duration_seconds": 0.0,
127
+ "overall_status": STATUS_PENDING,
128
+ "target_project_dir": str(self.target_dir),
129
+ "target_file_relative": self.target_file_relative,
130
+ "language": "python",
131
+ "python_version": sys.version.split()[0],
132
+ "commit_attempted": self._do_commit,
133
+ "commit_sha": None,
134
+ "steps": [],
135
+ "audit_findings": None,
136
+ "ai_review_findings": None,
137
+ "test_results_summary": None,
138
+ "error_message": None,
139
+ }
140
+
141
+ # ------------------------------------------------------------------
142
+ # commit approval gate
143
+ # ------------------------------------------------------------------
144
+ def request_commit_approval(self) -> bool:
145
+ """Human gate: approve the git commit, or decline safely.
146
+
147
+ ``--yes`` bypasses the prompt (explicit operator intent for CI).
148
+ Without a TTY and without ``--yes``, approval is declined — the
149
+ safe default is to never commit blind.
150
+ """
151
+ if getattr(self.args, "yes", False):
152
+ self._logger.info("Commit approved via --yes flag.")
153
+ return True
154
+ stdin = sys.stdin
155
+ if not stdin.isatty():
156
+ self._logger.warning(
157
+ "Commit requested but stdin is not interactive and --yes was not "
158
+ "passed; declining commit (safe default)."
159
+ )
160
+ return False
161
+ try:
162
+ answer = (
163
+ input(
164
+ f"\n[{APP_NAME}] Validation passed. Commit "
165
+ f"'{self.target_file_relative}'? [y/N] "
166
+ )
167
+ .strip()
168
+ .lower()
169
+ )
170
+ except (EOFError, KeyboardInterrupt):
171
+ print()
172
+ return False
173
+ approved = answer in ("y", "yes")
174
+ self._logger.info("Operator commit approval: %s", "granted" if approved else "declined")
175
+ return approved
176
+
177
+ # ------------------------------------------------------------------
178
+ # main loop
179
+ # ------------------------------------------------------------------
180
+ def run(self) -> int:
181
+ steps = self.config.get_list("validation_steps")
182
+ if not steps:
183
+ self._record_custom(
184
+ "pipeline_setup",
185
+ STATUS_FAILURE,
186
+ {"message": "No validation steps configured."},
187
+ error_message="Empty validation_steps in config.",
188
+ )
189
+ self._overall_success = False
190
+ self._finish_report()
191
+ return 1
192
+
193
+ step_outputs: dict[str, dict[str, Any]] = {}
194
+ for step_name in steps:
195
+ step_func = getattr(self.workflow, step_name, None)
196
+ if not callable(step_func):
197
+ self._logger.error("Unknown step '%s' in validation_steps.", step_name)
198
+ self._record_custom(
199
+ step_name,
200
+ STATUS_FAILURE,
201
+ {"message": f"Unknown step '{step_name}'."},
202
+ error_message=f"Unknown step '{step_name}'.",
203
+ )
204
+ self._overall_success = False
205
+ break
206
+
207
+ if step_name == "run_precommit" and self._review_only:
208
+ self._record_custom(
209
+ step_name, STATUS_SKIPPED, {"message": "Skipped (--review-only)."}
210
+ )
211
+ continue
212
+ if step_name in {"generate_tests", "save_tests", "execute_tests"} and self._review_only:
213
+ self._record_custom(
214
+ step_name, STATUS_SKIPPED, {"message": "Skipped (--review-only)."}
215
+ )
216
+ continue
217
+ if step_name == "commit_changes" and not self._do_commit:
218
+ reason = (
219
+ "--review-only"
220
+ if self._review_only
221
+ else "--no-commit"
222
+ if self.args.no_commit
223
+ else "commit not requested (pass --commit to enable)"
224
+ )
225
+ self._record_custom(
226
+ step_name,
227
+ STATUS_SKIPPED,
228
+ {"message": f"Skipped ({reason})."},
229
+ )
230
+ self.report_data["commit_attempted"] = False
231
+ continue
232
+
233
+ dependency = None
234
+ if step_name in _STEPS_WITH_DEPENDENCIES:
235
+ dependency = step_outputs.get(
236
+ {
237
+ "generate_tests": "extract_signatures",
238
+ "save_tests": "generate_tests",
239
+ "execute_tests": "save_tests",
240
+ }[step_name],
241
+ {},
242
+ ).get("details")
243
+
244
+ if not self._execute_step(step_name, step_func, step_outputs, dependency):
245
+ self._logger.warning("Halting pipeline at failed step '%s'.", step_name)
246
+ break
247
+
248
+ if step_name == "review_code" and self._review_only:
249
+ self._logger.info("--review-only: stopping after review_code.")
250
+ break
251
+
252
+ self._finish_report()
253
+ return 0 if self._overall_success else 1
254
+
255
+ def _execute_step(
256
+ self,
257
+ name: str,
258
+ step_func: Callable,
259
+ step_outputs: dict[str, dict[str, Any]],
260
+ dependency: dict[str, Any] | None,
261
+ ) -> bool:
262
+ start = datetime.now(timezone.utc)
263
+ result: StepResult = {
264
+ "name": name,
265
+ "status": STATUS_PENDING,
266
+ "start_time": start.isoformat(),
267
+ "end_time": "",
268
+ "duration_seconds": 0.0,
269
+ "details": None,
270
+ "error_message": None,
271
+ }
272
+ try:
273
+ self._logger.info("--- Step: %s ---", name)
274
+ if name in _STEPS_WITH_DEPENDENCIES:
275
+ status, details = step_func(dependency)
276
+ else:
277
+ status, details = step_func()
278
+ result["status"] = status
279
+ result["details"] = details
280
+ step_outputs[name] = {"details": details}
281
+ if status == STATUS_FAILURE:
282
+ self._overall_success = False
283
+ except ScribeError as exc:
284
+ self._logger.error("Step '%s' failed: %s", name, exc)
285
+ result["status"] = STATUS_FAILURE
286
+ result["error_message"] = str(exc)
287
+ result["details"] = exc.details or {"message": str(exc)}
288
+ self._overall_success = False
289
+ except Exception as exc: # noqa: BLE001 - a step must never kill the report
290
+ self._logger.critical("Step '%s' crashed: %s", name, exc, exc_info=True)
291
+ result["status"] = STATUS_FAILURE
292
+ result["error_message"] = f"{type(exc).__name__}: {exc}"
293
+ result["details"] = {"traceback": traceback.format_exc()}
294
+ self._overall_success = False
295
+ self._record(result)
296
+ return result["status"] != STATUS_FAILURE
297
+
298
+ # ------------------------------------------------------------------
299
+ # report bookkeeping
300
+ # ------------------------------------------------------------------
301
+ def _record(self, result: StepResult) -> None:
302
+ end = datetime.now(timezone.utc)
303
+ result["end_time"] = end.isoformat()
304
+ try:
305
+ start = datetime.fromisoformat(result["start_time"])
306
+ result["duration_seconds"] = round((end - start).total_seconds(), 3)
307
+ except ValueError:
308
+ result["duration_seconds"] = -1.0
309
+ self.report_data["steps"].append(result)
310
+ self._logger.info(
311
+ "Step '%s' -> %s (%.2fs)",
312
+ result["name"],
313
+ result["status"],
314
+ result["duration_seconds"],
315
+ )
316
+
317
+ def _record_custom(
318
+ self,
319
+ name: str,
320
+ status: str,
321
+ details: dict[str, Any],
322
+ error_message: str | None = None,
323
+ ) -> None:
324
+ now = datetime.now(timezone.utc).isoformat()
325
+ self._record(
326
+ {
327
+ "name": name,
328
+ "status": status,
329
+ "start_time": now,
330
+ "end_time": now,
331
+ "duration_seconds": 0.0,
332
+ "details": details,
333
+ "error_message": error_message,
334
+ }
335
+ )
336
+
337
+ def _finish_report(self) -> None:
338
+ self.report_data["end_time"] = datetime.now(timezone.utc).isoformat()
339
+ try:
340
+ start = datetime.fromisoformat(self.report_data["start_time"])
341
+ end = datetime.fromisoformat(self.report_data["end_time"])
342
+ self.report_data["total_duration_seconds"] = round((end - start).total_seconds(), 3)
343
+ except ValueError:
344
+ self.report_data["total_duration_seconds"] = -1.0
345
+ self.report_data["overall_status"] = (
346
+ STATUS_SUCCESS if self._overall_success else STATUS_FAILURE
347
+ )
348
+ output = render(self.report_data, self.args.report_format)
349
+ report_file = getattr(self.args, "report_file", None)
350
+ if report_file:
351
+ try:
352
+ Path(report_file).expanduser().write_text(output, encoding="utf-8")
353
+ self._logger.info("Wrote report to %s", report_file)
354
+ except OSError as exc:
355
+ self._logger.error("Could not write report file: %s", exc)
356
+ print(output)
357
+
358
+ def _emit_minimal_error_report(self, message: str, include_traceback: bool = False) -> None:
359
+ now = datetime.now(timezone.utc).isoformat()
360
+ step: StepResult = {
361
+ "name": "initialization_failure",
362
+ "status": STATUS_FAILURE,
363
+ "start_time": now,
364
+ "end_time": now,
365
+ "duration_seconds": 0.0,
366
+ "details": {"message": message},
367
+ "error_message": message,
368
+ }
369
+ if include_traceback:
370
+ step["details"] = {
371
+ "message": message,
372
+ "traceback": traceback.format_exc(),
373
+ }
374
+ report: dict[str, Any] = {
375
+ "scribe_version": __version__,
376
+ "run_id": getattr(self, "_run_id", "unknown"),
377
+ "start_time": now,
378
+ "end_time": now,
379
+ "total_duration_seconds": 0.0,
380
+ "overall_status": STATUS_FAILURE,
381
+ "target_project_dir": "unset",
382
+ "target_file_relative": "unset",
383
+ "language": "python",
384
+ "python_version": sys.version.split()[0],
385
+ "commit_attempted": False,
386
+ "commit_sha": None,
387
+ "steps": [step],
388
+ "audit_findings": None,
389
+ "ai_review_findings": None,
390
+ "test_results_summary": None,
391
+ "error_message": message,
392
+ }
393
+ try:
394
+ print(json.dumps(report, indent=2, default=str))
395
+ except Exception: # noqa: BLE001 - last resort
396
+ print(f'{{"overall_status": "FAILURE", "error_message": {message!r}}}')
scribe/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ """Command-line entry point for scribe-gate (``scribe`` / ``scribe-gate``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import logging
7
+ import sys
8
+ import time
9
+ from collections.abc import Sequence
10
+ from pathlib import Path
11
+
12
+ from . import __version__
13
+ from .agent import APP_NAME, ScribeAgent
14
+ from .config import (
15
+ DEFAULT_OLLAMA_BASE_URL,
16
+ )
17
+
18
+ LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(
23
+ prog="scribe",
24
+ description=(
25
+ f"{APP_NAME} v{__version__}: a validation gauntlet / trust gate for "
26
+ "agent-written Python code. Validates, reports, and only commits "
27
+ "with explicit operator approval."
28
+ ),
29
+ formatter_class=argparse.ArgumentDefaultsHelpFormatter,
30
+ )
31
+ parser.add_argument(
32
+ "target_dir",
33
+ nargs="?",
34
+ default=".",
35
+ help="Project directory the code belongs to (default: current dir).",
36
+ )
37
+ source_group = parser.add_mutually_exclusive_group()
38
+ source_group.add_argument(
39
+ "--source-file",
40
+ default=None,
41
+ help="Path to the new code file to validate.",
42
+ )
43
+ source_group.add_argument(
44
+ "--files",
45
+ nargs="+",
46
+ default=None,
47
+ metavar="FILE",
48
+ help="Validate these files in place (paths relative to target_dir). "
49
+ "Used by the pre-commit hook.",
50
+ )
51
+ parser.add_argument(
52
+ "--target-file",
53
+ default=None,
54
+ help="Relative path inside target_dir to place the new code "
55
+ "(e.g. 'src/main.py'). Required with --source-file.",
56
+ )
57
+ parser.add_argument(
58
+ "--review-only",
59
+ action="store_true",
60
+ help="Run through the AI review step, print the report, then exit. Never commits.",
61
+ )
62
+ parser.add_argument(
63
+ "--commit",
64
+ action="store_true",
65
+ help="Allow a git commit if validation passes. Still requires "
66
+ "operator approval at the prompt unless --yes is given.",
67
+ )
68
+ parser.add_argument(
69
+ "--no-commit",
70
+ action="store_true",
71
+ help="Explicitly disable the commit step (this is already the default).",
72
+ )
73
+ parser.add_argument(
74
+ "--yes",
75
+ action="store_true",
76
+ help="Approve the commit non-interactively. Only meaningful with --commit.",
77
+ )
78
+ parser.add_argument(
79
+ "--llm-backend",
80
+ default=None,
81
+ choices=["ollama", "openai", "openai-compatible"],
82
+ help="LLM backend (default: SCRIBE_LLM_BACKEND or 'ollama').",
83
+ )
84
+ parser.add_argument(
85
+ "--llm-model",
86
+ default=None,
87
+ help="Model name (default: SCRIBE_LLM_MODEL or backend default).",
88
+ )
89
+ parser.add_argument(
90
+ "--llm-base-url",
91
+ default=None,
92
+ help=f"Backend base URL (default: SCRIBE_LLM_BASE_URL or {DEFAULT_OLLAMA_BASE_URL}).",
93
+ )
94
+ parser.add_argument(
95
+ "--config-file",
96
+ default=None,
97
+ help="Explicit path to a scribe.toml config file.",
98
+ )
99
+ parser.add_argument(
100
+ "--report-format",
101
+ default="json",
102
+ choices=["json", "text"],
103
+ help="Final report output format.",
104
+ )
105
+ parser.add_argument(
106
+ "--report-file",
107
+ default=None,
108
+ help="Also write the final report to this path.",
109
+ )
110
+ parser.add_argument(
111
+ "--log-level", default="INFO", choices=LOG_LEVELS, help="Console log level."
112
+ )
113
+ parser.add_argument("--log-file", default=None, help="Append detailed DEBUG logs to this file.")
114
+ parser.add_argument("--version", action="version", version=f"{APP_NAME} {__version__}")
115
+ return parser
116
+
117
+
118
+ def parse_args(argv: Sequence[str] | None = None) -> argparse.Namespace:
119
+ args = build_parser().parse_args(argv)
120
+ args.in_place = args.files is not None
121
+ if args.files:
122
+ if args.source_file or args.target_file:
123
+ raise SystemExit("error: --files cannot be combined with --source-file/--target-file.")
124
+ else:
125
+ if not args.source_file or not args.target_file:
126
+ raise SystemExit(
127
+ "error: --source-file and --target-file are required "
128
+ "(or use --files for in-place validation)."
129
+ )
130
+ return args
131
+
132
+
133
+ def setup_logging(level: str, log_file: str | None = None) -> None:
134
+ root = logging.getLogger()
135
+ root.setLevel(logging.DEBUG)
136
+ for handler in root.handlers[:]:
137
+ root.removeHandler(handler)
138
+ try:
139
+ handler.close()
140
+ except Exception: # noqa: BLE001 - logging cleanup must not fail
141
+ pass
142
+ logging.Formatter.converter = time.gmtime
143
+ formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s (UTC)")
144
+ console = logging.StreamHandler(sys.stderr)
145
+ console.setLevel(getattr(logging, level.upper(), logging.INFO))
146
+ console.setFormatter(formatter)
147
+ root.addHandler(console)
148
+ if log_file:
149
+ try:
150
+ path = Path(log_file).expanduser()
151
+ path.parent.mkdir(parents=True, exist_ok=True)
152
+ file_handler = logging.FileHandler(path, mode="a", encoding="utf-8")
153
+ file_handler.setLevel(logging.DEBUG)
154
+ file_handler.setFormatter(formatter)
155
+ root.addHandler(file_handler)
156
+ except OSError as exc:
157
+ logging.getLogger(APP_NAME).error("Could not open log file '%s': %s", log_file, exc)
158
+
159
+
160
+ def _run_single(args: argparse.Namespace) -> int:
161
+ agent = ScribeAgent(args)
162
+ return agent.run()
163
+
164
+
165
+ def main(argv: Sequence[str] | None = None) -> int:
166
+ args = parse_args(argv)
167
+ setup_logging(args.log_level, args.log_file)
168
+
169
+ if not args.in_place:
170
+ return _run_single(args)
171
+
172
+ # --files mode: one gauntlet run per file, each with its own report.
173
+ assert args.files is not None
174
+ worst = 0
175
+ for index, filename in enumerate(args.files):
176
+ if index:
177
+ print("---", file=sys.stderr)
178
+ per_file = argparse.Namespace(
179
+ **{**vars(args), "source_file": filename, "target_file": filename, "in_place": True}
180
+ )
181
+ try:
182
+ code = _run_single(per_file)
183
+ except SystemExit as exc:
184
+ code = int(exc.code) if isinstance(exc.code, int) else 1
185
+ worst = max(worst, code)
186
+ return worst
187
+
188
+
189
+ if __name__ == "__main__":
190
+ raise SystemExit(main())