promptectomy 0.3.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 @@
1
+
@@ -0,0 +1,268 @@
1
+ import hashlib
2
+ import json
3
+ import re
4
+ from collections import defaultdict
5
+ from dataclasses import dataclass
6
+ from statistics import median
7
+
8
+ import pandas as pd
9
+ from sklearn.cluster import AgglomerativeClustering
10
+ from sklearn.feature_extraction.text import TfidfVectorizer
11
+ from sklearn.metrics.pairwise import cosine_distances
12
+
13
+ from .models import Call, Price, TaskKind
14
+ from .storage import canonical
15
+
16
+ _DATA_MARKER = re.compile(r"(?im)(?:^|\s)(?:input|email|text|data|payload|value)\s*:\s*(?=\S)")
17
+ _VARIABLES = re.compile(r'\{\{.+?\}\}|"(?:[^"\\]|\\.)*"|\b\d+(?:[.\-/]\d+)*\b')
18
+ _EMAIL = re.compile(r"[\w.+-]+@[\w.-]+\.[a-z]{2,}", re.I)
19
+ _CHAT_PREFIX = "chat | "
20
+ _DETAIL_REQUEST = re.compile(r"\b(please|provide|share|give|tell|need|what|could|can|may)\b", re.I)
21
+ _REPLY_VALUE = re.compile(
22
+ rf"(?P<email>{_EMAIL.pattern})"
23
+ r"|(?P<date>\b\d{4}-\d{2}-\d{2}\b)"
24
+ r"|(?P<reference>\b[a-z]+-\d+\b|\#\d+\b)"
25
+ r"|(?P<phone>(?<!\w)(?:\+\d{1,3}[ .-])?(?:\(\d{2,4}\)|\d{2,4})[ .-]\d{3,4}[ .-]\d{3,4}\b)"
26
+ r"|(?P<number>\b\d{3,}\b)",
27
+ re.I,
28
+ )
29
+ _DIRECTIVE = re.compile(
30
+ r"\b(extract|parse|classify|convert|format|normalize|transform|draft|write|summarize|translate)\b",
31
+ re.I,
32
+ )
33
+ _SIGNALS: dict[TaskKind, str] = {
34
+ "classification": r"\b(classif\w*|categoriz\w*|choose (?:one|from)|route)\b",
35
+ "extraction": r"\b(extract\w*|parse|pull out|find the)\b",
36
+ "formatting": r"\b(format\w*|normaliz\w*|reformat\w*|standardiz\w*)\b",
37
+ "conversion": r"\b(convert\w*|transform\w*)\b",
38
+ }
39
+ DEFAULT_PRICES = {
40
+ "gpt-4o-mini": Price(input_per_million=0.15, output_per_million=0.60),
41
+ "gpt-4o-mini-2024-07-18": Price(input_per_million=0.15, output_per_million=0.60),
42
+ "gpt-4o": Price(input_per_million=2.50, output_per_million=10.00),
43
+ "gpt-4o-2024-08-06": Price(input_per_million=2.50, output_per_million=10.00),
44
+ "gpt-4o-2024-11-20": Price(input_per_million=2.50, output_per_million=10.00),
45
+ "gpt-4.1-mini": Price(input_per_million=0.40, output_per_million=1.60),
46
+ "gpt-4.1-mini-2025-04-14": Price(input_per_million=0.40, output_per_million=1.60),
47
+ }
48
+
49
+
50
+ @dataclass
51
+ class Task:
52
+ id: str
53
+ kind: TaskKind
54
+ calls: list[Call]
55
+ monthly_usd: float | None
56
+ priced_calls: int
57
+ median_ms: float | None
58
+ timed_calls: int
59
+ repeated_inputs: int = 0
60
+ consistent_inputs: int = 0
61
+ estimated_priced_calls: int = 0
62
+
63
+
64
+ def instruction_prefix(text: str) -> str:
65
+ marker = _DATA_MARKER.search(text)
66
+ instruction = text[: marker.start()] if marker else text.strip().partition("\n")[0]
67
+ instruction = _EMAIL.sub(" <email> ", instruction)
68
+ return " ".join(_VARIABLES.sub(" <value> ", instruction.casefold()).split())
69
+
70
+
71
+ def chat_turns(prompt: str) -> list[tuple[str, str]]:
72
+ if not prompt.lstrip().startswith("["):
73
+ return []
74
+ try:
75
+ messages = json.loads(prompt)
76
+ except (ValueError, RecursionError):
77
+ return []
78
+ if not isinstance(messages, list):
79
+ return []
80
+ turns = []
81
+ for message in messages:
82
+ if not isinstance(message, dict):
83
+ return []
84
+ fields = message.get("kwargs", message)
85
+ if not isinstance(fields, dict):
86
+ return []
87
+ role = fields.get("role") or fields.get("type") or message.get("type")
88
+ if role == "constructor" and isinstance(message.get("id"), list) and message["id"]:
89
+ role = message["id"][-1]
90
+ if isinstance(role, str):
91
+ role = {
92
+ "human": "user",
93
+ "HumanMessage": "user",
94
+ "AIMessage": "assistant",
95
+ "ai": "assistant",
96
+ "SystemMessage": "system",
97
+ "ToolMessage": "tool",
98
+ "FunctionMessage": "tool",
99
+ "function": "tool",
100
+ }.get(role, role)
101
+ if role not in ("user", "system", "developer", "assistant", "tool"):
102
+ return []
103
+ content = fields.get("content", fields.get("parts"))
104
+ if isinstance(content, list):
105
+ content = " ".join(
106
+ part["text"]
107
+ for part in content
108
+ if isinstance(part, dict) and isinstance(part.get("text"), str)
109
+ )
110
+ turns.append((role, content if isinstance(content, str) else ""))
111
+ return turns
112
+
113
+
114
+ def template(prompt: str) -> str:
115
+ turns = chat_turns(prompt)
116
+ last_user = next((i for i in range(len(turns) - 1, -1, -1) if turns[i][0] == "user"), None)
117
+ if last_user is None:
118
+ return instruction_prefix(prompt)
119
+
120
+ system = " ".join(
121
+ " ".join(text.casefold().split()) for role, text in turns if role in ("system", "developer")
122
+ )[:240]
123
+ user = turns[last_user][1]
124
+ directive = instruction_prefix(user)
125
+ previous_role, previous = turns[last_user - 1] if last_user else ("", "")
126
+ if system and not _DIRECTIVE.match(directive.removeprefix("please ")):
127
+ value = _REPLY_VALUE.search(user) if previous_role == "assistant" else None
128
+ directive = (
129
+ f"reply with {value.lastgroup}" if value and _DETAIL_REQUEST.search(previous) else ""
130
+ )
131
+ return f"{_CHAT_PREFIX}{system} | {directive}"
132
+
133
+
134
+ def reserve_task_id(keys: list[str], taken: set[str]) -> str:
135
+ digest = hashlib.sha256("\n".join(keys).encode()).hexdigest()
136
+ task_id = f"template-{digest[:12]}"
137
+ while task_id in taken:
138
+ task_id += "-"
139
+ taken.add(task_id)
140
+ return task_id
141
+
142
+
143
+ def group_calls(calls: list[Call], known: dict[str, str]) -> dict[str, list[Call]]:
144
+ groups: dict[str, list[Call]] = {}
145
+ templates: dict[str, list[Call]] = {}
146
+ for call in calls:
147
+ if call.step:
148
+ groups.setdefault(call.step, []).append(call)
149
+ else:
150
+ templates.setdefault(template(call.prompt), []).append(call)
151
+
152
+ if not templates:
153
+ return groups
154
+ if set(known.values()) & groups.keys():
155
+ raise ValueError("A step label collides with a persisted task ID. Rename the step.")
156
+ taken = set(known.values()) | groups.keys()
157
+ # Chat signatures already describe the instruction and turn shape. Comparing their
158
+ # shared system text would conflate distinct steps in the same conversation.
159
+ for key in templates:
160
+ if key.startswith(_CHAT_PREFIX) and key not in known:
161
+ known[key] = reserve_task_id([key], taken)
162
+ names = sorted(
163
+ key for key in templates.keys() | known.keys() if not key.startswith(_CHAT_PREFIX)
164
+ )
165
+ positions = {name: index for index, name in enumerate(names)}
166
+ clusters = list(range(len(names)))
167
+ distances = None
168
+ if len(names) > 1:
169
+ vectors = TfidfVectorizer(analyzer="char", ngram_range=(1, 4)).fit_transform(
170
+ [name or "<empty>" for name in names]
171
+ )
172
+ distances = cosine_distances(vectors)
173
+ clusters = AgglomerativeClustering(
174
+ n_clusters=None, distance_threshold=0.3, metric="precomputed", linkage="complete"
175
+ ).fit_predict(distances)
176
+
177
+ members: dict[int, list[str]] = {}
178
+ for cluster, name in zip(clusters, names, strict=True):
179
+ members.setdefault(cluster, []).append(name)
180
+ for keys in members.values():
181
+ anchors = [key for key in keys if key in known]
182
+ new_keys = [key for key in keys if key not in known]
183
+ if not anchors:
184
+ task_id = reserve_task_id(keys, taken)
185
+ known.update(dict.fromkeys(new_keys, task_id))
186
+ continue
187
+ if new_keys:
188
+ assert distances is not None
189
+ for key in new_keys:
190
+ nearest = min(anchors, key=lambda item: distances[positions[key], positions[item]])
191
+ known[key] = known[nearest]
192
+ for key, items in templates.items():
193
+ groups.setdefault(known[key], []).extend(items)
194
+ return groups
195
+
196
+
197
+ def analyze(
198
+ calls: list[Call],
199
+ prices: dict[str, Price],
200
+ days: float,
201
+ known: dict[str, str] | None = None,
202
+ ) -> list[Task]:
203
+ tasks = []
204
+ rows = []
205
+ rates = DEFAULT_PRICES | prices
206
+ for task_id, group in group_calls(calls, known if known is not None else {}).items():
207
+ hints = (
208
+ task_id.replace("_", " ").replace("-", " ")
209
+ + " "
210
+ + " ".join(template(call.prompt) for call in group[:20])
211
+ )
212
+ kind = next(
213
+ (kind for kind, signal in _SIGNALS.items() if re.search(signal, hints, re.I)),
214
+ "unknown",
215
+ )
216
+ costs = []
217
+ estimated_priced = 0
218
+ elapsed = [call.latency_ms for call in group if call.latency_ms is not None]
219
+ outputs = defaultdict(list)
220
+ for call in group:
221
+ outputs[call.prompt].append(canonical(call.output))
222
+ if call.cost_usd is not None:
223
+ costs.append(call.cost_usd)
224
+ elif (
225
+ call.model in rates
226
+ and call.input_tokens is not None
227
+ and call.output_tokens is not None
228
+ ):
229
+ price = rates[call.model]
230
+ estimated_priced += call.estimated_tokens
231
+ costs.append(
232
+ (
233
+ price.input_per_million * call.input_tokens
234
+ + price.output_per_million * call.output_tokens
235
+ )
236
+ / 1_000_000
237
+ )
238
+ monthly = float(pd.Series(costs, dtype=float).sum()) * 30 / days if costs else None
239
+ repeated = [values for values in outputs.values() if len(values) > 1]
240
+ tasks.append(
241
+ Task(
242
+ task_id,
243
+ kind,
244
+ group,
245
+ monthly,
246
+ len(costs),
247
+ median(elapsed) if elapsed else None,
248
+ len(elapsed),
249
+ len(repeated),
250
+ sum(len(set(values)) == 1 for values in repeated),
251
+ estimated_priced,
252
+ )
253
+ )
254
+ rows.append(
255
+ {"candidate": kind != "unknown", "cost": monthly, "calls": len(group), "task": task_id}
256
+ )
257
+ order = (
258
+ pd.DataFrame(rows)
259
+ .sort_values(
260
+ ["candidate", "cost", "calls", "task"],
261
+ ascending=[False, False, False, True],
262
+ na_position="last",
263
+ )
264
+ .index
265
+ if rows
266
+ else []
267
+ )
268
+ return [tasks[index] for index in order]
promptectomy/cli.py ADDED
@@ -0,0 +1,364 @@
1
+ import io
2
+ import math
3
+ import os
4
+ import random
5
+ import re
6
+ import sqlite3
7
+ import sys
8
+ from collections.abc import Callable
9
+ from functools import wraps
10
+ from importlib.metadata import version
11
+ from pathlib import Path
12
+ from typing import TYPE_CHECKING, Annotated
13
+
14
+ import typer
15
+ from dotenv import dotenv_values, find_dotenv
16
+ from pydantic import TypeAdapter, ValidationError
17
+ from rich.cells import cell_len
18
+ from rich.console import Console
19
+ from rich.syntax import Syntax
20
+ from rich.table import Column, Table
21
+ from rich.text import Text
22
+
23
+ from .evidence import COPIED, authentic, digest, key_pair, sign, transaction, used_inputs
24
+ from .importers import LogFormat, import_calls
25
+ from .models import Call, Candidate, Example, Policy, Price, TaskSpec
26
+ from .storage import load_rows, parse_rows, redact, write_rows, write_text
27
+
28
+ if TYPE_CHECKING:
29
+ from .analysis import Task
30
+
31
+ app = typer.Typer(no_args_is_help=True, pretty_exceptions_show_locals=False)
32
+ console = Console()
33
+ errors = Console(stderr=True)
34
+ STORE = Path(".promptectomy/calls.jsonl")
35
+ DAYS = Annotated[
36
+ float | None, typer.Option(min=0.00001, help="Override the observed log window in days.")
37
+ ]
38
+ PRICES = Annotated[Path | None, typer.Option(help="JSON with USD token rates per model.")]
39
+
40
+
41
+ def print_version(value: bool):
42
+ if value:
43
+ console.print(f"promptectomy {version('promptectomy')}")
44
+ raise typer.Exit()
45
+
46
+
47
+ @app.callback()
48
+ def configure_console(
49
+ show_version: Annotated[
50
+ bool, typer.Option("--version", callback=print_version, is_eager=True)
51
+ ] = False,
52
+ ):
53
+ for stream in (sys.stdout, sys.stderr):
54
+ if isinstance(stream, io.TextIOWrapper):
55
+ stream.reconfigure(errors="backslashreplace")
56
+
57
+
58
+ def command(function: Callable):
59
+ @wraps(function)
60
+ def run(*args, **kwargs):
61
+ try:
62
+ return function(*args, **kwargs)
63
+ except ValidationError as error:
64
+ for item in error.errors(include_input=False):
65
+ location = ".".join(map(str, item["loc"])) or "document"
66
+ errors.print(
67
+ Text(f"Invalid {location}: {item['type']}"), style="red", soft_wrap=True
68
+ )
69
+ except (OSError, ValueError, OverflowError, re.error, sqlite3.Error) as error:
70
+ errors.print(Text(str(error)), style="red", soft_wrap=True)
71
+ raise typer.Exit(2)
72
+
73
+ return run
74
+
75
+
76
+ def log_window(calls: list[Call], days: float | None) -> tuple[float, str]:
77
+ if days is not None:
78
+ if not math.isfinite(days):
79
+ raise ValueError("--days must be finite.")
80
+ return days, "explicit --days"
81
+ dates = [call.timestamp for call in calls if call.timestamp is not None]
82
+ if len(dates) == len(calls) and len(dates) > 1 and max(dates) > min(dates):
83
+ return max(1, (max(dates) - min(dates)).total_seconds() / 86_400), (
84
+ "timestamp span, with a one-day minimum"
85
+ )
86
+ return 30, f"assumed window, no complete timestamp span ({len(dates)}/{len(calls)} dated)"
87
+
88
+
89
+ def rank_tasks(calls: list[Call], prices: bytes | None, days: float, state: Path) -> list["Task"]:
90
+ from .analysis import analyze as analyze_calls
91
+
92
+ rates = TypeAdapter(dict[str, Price]).validate_json(prices) if prices is not None else {}
93
+ with transaction(state) as db:
94
+ db.execute("CREATE TABLE IF NOT EXISTS task_ids (template TEXT PRIMARY KEY, id TEXT)")
95
+ known = dict(db.execute("SELECT template, id FROM task_ids"))
96
+ tasks = analyze_calls(calls, rates, days, known)
97
+ db.executemany("INSERT OR IGNORE INTO task_ids VALUES (?, ?)", known.items())
98
+ return tasks
99
+
100
+
101
+ @app.command()
102
+ @command
103
+ def ingest(
104
+ source: Path,
105
+ store: Path = STORE,
106
+ log_format: Annotated[LogFormat, typer.Option("--format")] = LogFormat.native,
107
+ requests: Annotated[Path | None, typer.Option(help="OpenAI Batch input JSONL.")] = None,
108
+ redact_pattern: Annotated[
109
+ list[str] | None,
110
+ typer.Option("--redact", help="Remove matching text from prompts and output values."),
111
+ ] = None,
112
+ ):
113
+ """Import native, Chat Completions, Batch, or OpenTelemetry logs."""
114
+ patterns = [re.compile(pattern) for pattern in redact_pattern or []]
115
+ calls, skipped = import_calls(source, log_format, requests)
116
+ if not calls:
117
+ raise ValueError("The log has no usable calls.")
118
+ for call in calls:
119
+ for pattern in patterns:
120
+ prompt = redact(call.prompt, pattern)
121
+ output = redact(call.output, pattern)
122
+ call.redacted |= prompt != call.prompt or output != call.output
123
+ call.prompt, call.output = prompt, output
124
+ if store.exists() and not patterns:
125
+ previous = load_rows(store, Call)
126
+ rank_tasks(previous, None, 30, store.parent / "state.sqlite3")
127
+ write_rows(store, calls)
128
+ console.print(Text(f"Saved {len(calls)} calls to {store}. Skipped {skipped} records."))
129
+
130
+
131
+ @app.command()
132
+ @command
133
+ def analyze(store: Path = STORE, prices: PRICES = None, days: DAYS = None):
134
+ """Group local calls and rank likely replacements by cost and frequency."""
135
+ calls = load_rows(store, Call)
136
+ window, basis = log_window(calls, days)
137
+ tasks = rank_tasks(
138
+ calls, prices.read_bytes() if prices else None, window, store.parent / "state.sqlite3"
139
+ )
140
+ id_width = max((cell_len(item.id) for item in tasks), default=4)
141
+ compact = console.width < id_width + 66
142
+ table = Table(
143
+ Column("Task", no_wrap=True, min_width=id_width),
144
+ "Pattern",
145
+ "Calls",
146
+ "USD / 30 days",
147
+ "Median ms",
148
+ "Repeat agreement",
149
+ )
150
+ for task in tasks:
151
+ cost = (
152
+ f"${task.monthly_usd:.6f} ({task.priced_calls}/{len(task.calls)})"
153
+ if task.monthly_usd is not None
154
+ else "-"
155
+ )
156
+ if task.estimated_priced_calls:
157
+ cost += f", {task.estimated_priced_calls} with estimated tokens"
158
+ latency = (
159
+ f"{task.median_ms:.2f} ({task.timed_calls}/{len(task.calls)})"
160
+ if task.median_ms is not None
161
+ else "-"
162
+ )
163
+ agreement = (
164
+ f"{task.consistent_inputs}/{task.repeated_inputs}" if task.repeated_inputs else "-"
165
+ )
166
+ if compact:
167
+ console.print(Text(task.id, style="bold"), soft_wrap=True)
168
+ console.print(
169
+ f" {task.kind} | {len(task.calls)} calls | USD/30d {cost} | "
170
+ f"median ms {latency} | repeat agreement {agreement}"
171
+ )
172
+ else:
173
+ table.add_row(Text(task.id), task.kind, str(len(task.calls)), cost, latency, agreement)
174
+ if not compact:
175
+ console.print(table)
176
+ console.print(f"Log window: {window:g} days ({basis}). Parentheses show data coverage.")
177
+
178
+
179
+ @app.command()
180
+ @command
181
+ def review(
182
+ task: str,
183
+ store: Path = STORE,
184
+ out: Path = Path(".promptectomy/review.jsonl"),
185
+ count: Annotated[int, typer.Option(min=1)] = 100,
186
+ seed: int = 42,
187
+ include_used: Annotated[bool, typer.Option(help="Include previously scored prompts.")] = False,
188
+ ):
189
+ """Draft task inputs for independent review without including model outputs."""
190
+ state = store.parent / "state.sqlite3"
191
+ tasks = {item.id: item for item in rank_tasks(load_rows(store, Call), None, 30, state)}
192
+ if task not in tasks:
193
+ raise ValueError("The task is absent from the ingested log. Run analyze.")
194
+ used = set() if include_used else used_inputs(state)
195
+ prompts = sorted(
196
+ {call.prompt for call in tasks[task].calls if digest(call.prompt.encode()) not in used}
197
+ )
198
+ if not prompts:
199
+ raise ValueError("No fresh task inputs are available. Import newer calls.")
200
+ reviewed = random.Random(seed).sample(prompts, min(count, len(prompts)))
201
+ write_rows(
202
+ out,
203
+ [
204
+ Example(
205
+ input=prompt, expected=None, verified=False, source="pending independent review"
206
+ )
207
+ for prompt in reviewed
208
+ ],
209
+ )
210
+ console.print(Text(f"Saved {len(reviewed)} prompts for independent review to {out}."))
211
+
212
+
213
+ @app.command("review-key")
214
+ @command
215
+ def review_key(secret: Path, public: Path):
216
+ """Create an Ed25519 key pair for an independent reviewer."""
217
+ if secret.resolve() == public.resolve() or secret.exists() or public.exists():
218
+ raise ValueError("Use two distinct paths for new key files.")
219
+ private, trusted = key_pair()
220
+ write_text(secret, private + "\n")
221
+ write_text(public, trusted + "\n")
222
+ console.print(Text(f"Share {public}. Keep {secret} private."))
223
+
224
+
225
+ @app.command()
226
+ @command
227
+ def attest(task: str, examples: Path, secret: Path, out: Path):
228
+ """Sign exact JSONL bytes after checking the answers independently."""
229
+ if out.resolve() in {examples.resolve(), secret.resolve()}:
230
+ raise ValueError("Use a separate output path for the attestation.")
231
+ data = examples.read_bytes()
232
+ rows = parse_rows(examples, data, Example)
233
+ if not any(row.verified for row in rows) or any(
234
+ COPIED.search(row.source) for row in rows if row.verified
235
+ ):
236
+ raise ValueError("Attest only independently checked answers with their sources.")
237
+ write_text(out, sign(task, data, secret.read_text(encoding="ascii").strip()) + "\n")
238
+ console.print(Text(f"Saved attestation to {out}."))
239
+
240
+
241
+ @app.command()
242
+ @command
243
+ def suggest(
244
+ spec: Path,
245
+ out: Path = Path(".promptectomy/candidate.json"),
246
+ code_out: Annotated[Path | None, typer.Option(help="Export the proposed Python.")] = None,
247
+ model: Annotated[
248
+ str | None, typer.Option(help="Groq model ID, or rules for offline use.")
249
+ ] = None,
250
+ ):
251
+ """Use Groq or local rules to propose a replacement or keep the AI call."""
252
+ from groq import APIError
253
+
254
+ from .suggest import generate, offline
255
+
256
+ task_spec = TaskSpec.model_validate_json(spec.read_bytes())
257
+ local = offline(task_spec)
258
+ if out.resolve() == spec.resolve() or (
259
+ code_out and code_out.resolve() in {out.resolve(), spec.resolve()}
260
+ ):
261
+ raise ValueError("Use distinct paths for the task spec, candidate, and Python export.")
262
+ api_key = ""
263
+ if model != "rules" and task_spec.rule != "keep-ai":
264
+ api_key = os.environ.get("GROQ_API_KEY", "").strip()
265
+ if not api_key:
266
+ dotenv = find_dotenv(usecwd=True)
267
+ if dotenv:
268
+ api_key = (dotenv_values(dotenv).get("GROQ_API_KEY") or "").strip()
269
+ if model and not api_key:
270
+ if sys.stdin.isatty():
271
+ api_key = typer.prompt("GROQ_API_KEY", hide_input=True).strip()
272
+ if not api_key:
273
+ raise ValueError("Set GROQ_API_KEY to use this Groq model.")
274
+ try:
275
+ candidate = generate(task_spec, api_key, model) if api_key else local
276
+ except APIError as error:
277
+ raise ValueError(f"Groq request failed ({type(error).__name__}).") from None
278
+ write_text(out, candidate.model_dump_json(indent=2) + "\n")
279
+ if candidate.suggestion.status == "candidate":
280
+ if code_out:
281
+ write_text(code_out, candidate.suggestion.code.rstrip() + "\n")
282
+ console.print(Syntax(candidate.suggestion.code, "python", word_wrap=True))
283
+ elif candidate.suggestion.status == "keep_ai":
284
+ console.print("KEEP_AI", style="cyan")
285
+ for assumption in candidate.suggestion.assumptions:
286
+ console.print(Text(f"- {assumption}"))
287
+ console.print(Text(f"Saved {candidate.suggestion.status} to {out}."))
288
+
289
+
290
+ @app.command()
291
+ @command
292
+ def test(
293
+ candidate: Path,
294
+ examples: Path,
295
+ policy: Path,
296
+ store: Path = STORE,
297
+ prices: PRICES = None,
298
+ days: DAYS = None,
299
+ report: Path = Path(".promptectomy/report.md"),
300
+ reviewer_key: Annotated[Path | None, typer.Option(help="Trusted reviewer public key.")] = None,
301
+ attestation: Annotated[Path | None, typer.Option(help="Detached evidence signature.")] = None,
302
+ reviewed: Annotated[bool, typer.Option(help="You inspected the candidate Python.")] = False,
303
+ development: Annotated[bool, typer.Option(help="Score development inputs without a PASS.")] = (
304
+ False
305
+ ),
306
+ ):
307
+ """Score a candidate on independently attested, held-out task inputs."""
308
+ from .verify import verify
309
+
310
+ inputs = {"candidate": candidate, "examples": examples, "policy": policy, "log": store}
311
+ for name, path in (
312
+ ("prices", prices),
313
+ ("reviewer_key", reviewer_key),
314
+ ("attestation", attestation),
315
+ ):
316
+ if path is not None:
317
+ inputs[name] = path
318
+ state = store.parent / "state.sqlite3"
319
+ if report.resolve() in {path.resolve() for path in (*inputs.values(), state)}:
320
+ raise ValueError("The report path must be separate from the input and state files.")
321
+ if report.suffix.lower() not in (".md", ".html"):
322
+ raise ValueError("Use a .md or .html report path.")
323
+ contents = {name: path.read_bytes() for name, path in inputs.items()}
324
+ proposal = Candidate.model_validate_json(contents["candidate"])
325
+ criteria = Policy.model_validate_json(contents["policy"])
326
+ cases = parse_rows(examples, contents["examples"], Example)
327
+ logs = parse_rows(store, contents["log"], Call)
328
+ window, basis = log_window(logs, days)
329
+ tasks = {task.id: task for task in rank_tasks(logs, contents.get("prices"), window, state)}
330
+ if proposal.task not in tasks:
331
+ raise ValueError("The candidate task is absent from the ingested log. Run analyze.")
332
+ fingerprints = {name: digest(data) for name, data in contents.items()}
333
+ attested = authentic(
334
+ proposal.task,
335
+ contents["examples"],
336
+ contents.get("attestation", b"").decode("ascii").strip(),
337
+ contents.get("reviewer_key", b"").decode("ascii").strip(),
338
+ )
339
+ result = verify(
340
+ tasks[proposal.task],
341
+ proposal,
342
+ cases,
343
+ criteria,
344
+ window,
345
+ reviewed,
346
+ attested=attested,
347
+ state=state,
348
+ development=development,
349
+ )
350
+ result.notes.append(f"Log window: {window:g} days ({basis}).")
351
+ write_text(
352
+ report,
353
+ result.report(proposal, criteria, fingerprints, html=report.suffix.lower() == ".html"),
354
+ )
355
+ colors = {"PASS": "green", "FAIL": "red", "UNVERIFIED": "yellow", "KEEP_AI": "cyan"}
356
+ console.print(Text(result.verdict, style=colors[result.verdict]))
357
+ console.print(Text(result.reason), soft_wrap=True)
358
+ console.print(Text(f"Report: {report}"), soft_wrap=True)
359
+ if result.verdict != "PASS":
360
+ raise typer.Exit({"FAIL": 1, "UNVERIFIED": 3, "KEEP_AI": 4}[result.verdict])
361
+
362
+
363
+ if __name__ == "__main__":
364
+ app()