|
1 | 1 | # SPDX-License-Identifier: Apache-2.0 |
2 | 2 | # Copyright 2026 MbitAI — see NOTICE for attribution. |
3 | | -"""LM assist (Phase 2 stub). Not wired — exits 2 with a pointer. |
4 | | -
|
5 | | -The assist will read an immutable parse audit plus its paired structured |
6 | | -CSV, then write proposals and decisions to a separate append-only review |
7 | | -JSONL. It will never modify deterministic outputs. See docs/PHASE2-LM.md. |
8 | | -Never runs in v0.1. |
9 | | -""" |
| 3 | +"""Review deterministic parse candidates with a local OpenAI-compatible model.""" |
10 | 4 |
|
11 | 5 | from __future__ import annotations |
12 | 6 |
|
| 7 | +import argparse |
| 8 | +import hashlib |
13 | 9 | import sys |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +ROOT = Path(__file__).resolve().parents[1] |
| 13 | +sys.path.insert(0, str(ROOT)) |
| 14 | + |
| 15 | +from trailparse import audit as audit_mod # noqa: E402 |
| 16 | +from trailparse import io as io_mod # noqa: E402 |
| 17 | +from trailparse.assist import ( # noqa: E402 |
| 18 | + append_review, |
| 19 | + apply_decisions, |
| 20 | + review_candidate, |
| 21 | + select_candidates, |
| 22 | +) |
| 23 | +from trailparse.lm import ( # noqa: E402 |
| 24 | + DEFAULT_BASE_URL, |
| 25 | + DEFAULT_MODEL, |
| 26 | + LocalModelClient, |
| 27 | +) |
| 28 | + |
| 29 | +RAW_RESULTS = (ROOT / "results" / "raw").resolve() |
| 30 | + |
| 31 | + |
| 32 | +def sha256(path: Path) -> str: |
| 33 | + return hashlib.sha256(path.read_bytes()).hexdigest() |
| 34 | + |
| 35 | + |
| 36 | +def validate_paths( |
| 37 | + csv_path: Path, |
| 38 | + audit_path: Path, |
| 39 | + review_path: Path, |
| 40 | + out_csv: Path | None, |
| 41 | +) -> None: |
| 42 | + inputs = {csv_path.resolve(), audit_path.resolve()} |
| 43 | + if len(inputs) != 2: |
| 44 | + raise ValueError("CSV and audit inputs must be different files") |
| 45 | + if review_path.resolve() in inputs: |
| 46 | + raise ValueError("review output cannot overwrite an input") |
| 47 | + if not review_path.name.endswith(".lm-review.jsonl"): |
| 48 | + raise ValueError("review output must end with .lm-review.jsonl") |
| 49 | + if not review_path.resolve().is_relative_to(RAW_RESULTS): |
| 50 | + raise ValueError("review output must be under results/raw/") |
| 51 | + if out_csv is not None: |
| 52 | + if out_csv.resolve() in inputs or out_csv.resolve() == review_path.resolve(): |
| 53 | + raise ValueError("assisted CSV cannot overwrite an input or review log") |
| 54 | + if not out_csv.name.endswith("_lm.csv"): |
| 55 | + raise ValueError("assisted CSV must end with _lm.csv") |
| 56 | + if not out_csv.resolve().is_relative_to(RAW_RESULTS): |
| 57 | + raise ValueError("assisted CSV must be under results/raw/") |
14 | 58 |
|
15 | 59 |
|
16 | 60 | def main() -> None: |
17 | | - print("LM assist is Phase 2 and not wired. See docs/PHASE2-LM.md.") |
18 | | - print( |
19 | | - "Parse audit and CSV inputs stay immutable; model review will use " |
20 | | - "a separate local-only JSONL." |
| 61 | + ap = argparse.ArgumentParser() |
| 62 | + ap.add_argument("--csv", required=True, help="immutable structured CSV") |
| 63 | + ap.add_argument("--audit", required=True, help="immutable parse audit JSONL") |
| 64 | + ap.add_argument( |
| 65 | + "--review", |
| 66 | + default="results/raw/trail.lm-review.jsonl", |
| 67 | + help="append-only review JSONL under results/raw/", |
21 | 68 | ) |
22 | | - sys.exit(2) |
| 69 | + ap.add_argument( |
| 70 | + "--out-csv", |
| 71 | + default="", |
| 72 | + help="optional assisted CSV under results/raw/, ending in _lm.csv", |
| 73 | + ) |
| 74 | + ap.add_argument("--base-url", default=DEFAULT_BASE_URL) |
| 75 | + ap.add_argument("--model", default=DEFAULT_MODEL) |
| 76 | + ap.add_argument("--timeout", type=float, default=120.0) |
| 77 | + ap.add_argument( |
| 78 | + "--dry-run", |
| 79 | + action="store_true", |
| 80 | + help="list candidates without calling a model or writing outputs", |
| 81 | + ) |
| 82 | + args = ap.parse_args() |
| 83 | + |
| 84 | + csv_path = Path(args.csv) |
| 85 | + audit_path = Path(args.audit) |
| 86 | + review_path = Path(args.review) |
| 87 | + out_csv = Path(args.out_csv) if args.out_csv else None |
| 88 | + try: |
| 89 | + validate_paths(csv_path, audit_path, review_path, out_csv) |
| 90 | + except ValueError as exc: |
| 91 | + ap.error(str(exc)) |
| 92 | + |
| 93 | + before = {csv_path: sha256(csv_path), audit_path: sha256(audit_path)} |
| 94 | + records = audit_mod.read_jsonl(audit_path) |
| 95 | + rows = io_mod.read_structured(csv_path) |
| 96 | + candidates = select_candidates(records, rows) |
| 97 | + print(f"selected {len(candidates)} candidates") |
| 98 | + if args.dry_run: |
| 99 | + for candidate in candidates: |
| 100 | + print( |
| 101 | + f"{candidate.kind}: {','.join(candidate.cluster_ids)} " |
| 102 | + f"audit lines={list(candidate.cited_audit_lines)}" |
| 103 | + ) |
| 104 | + return |
| 105 | + |
| 106 | + try: |
| 107 | + client = LocalModelClient(args.base_url, args.model, args.timeout) |
| 108 | + except ValueError as exc: |
| 109 | + ap.error(str(exc)) |
| 110 | + reviews = [] |
| 111 | + for candidate in candidates: |
| 112 | + review = review_candidate( |
| 113 | + candidate, |
| 114 | + client, |
| 115 | + audit_sha256=before[audit_path], |
| 116 | + csv_sha256=before[csv_path], |
| 117 | + ) |
| 118 | + append_review(review_path, review) |
| 119 | + reviews.append(review) |
| 120 | + print( |
| 121 | + f"{candidate.kind} {','.join(candidate.cluster_ids)}: " |
| 122 | + f"{review['decision']} ({review['reason']})" |
| 123 | + ) |
| 124 | + if review["response"].get("error"): |
| 125 | + raise SystemExit( |
| 126 | + f"local model request failed; rejection recorded in {review_path}" |
| 127 | + ) |
| 128 | + |
| 129 | + if out_csv is not None: |
| 130 | + io_mod.write_structured(apply_decisions(rows, reviews), out_csv) |
| 131 | + print(f"wrote assisted CSV to {out_csv}") |
| 132 | + |
| 133 | + after = {csv_path: sha256(csv_path), audit_path: sha256(audit_path)} |
| 134 | + if after != before: |
| 135 | + raise RuntimeError("immutable input changed during LM review") |
23 | 136 |
|
24 | 137 |
|
25 | 138 | if __name__ == "__main__": |
|
0 commit comments