feat(learning): חיווט אוטונומי לכפתורי מסלול-הסופי — סקריפט-תזמור אחד לכל שלב
הכפתורים "הרץ למידת-קול"/"הרץ אימות-הלכות" מעירים את הרמס, ובמקום שהסוכן (DeepSeek) ירכיב כמה קריאות-כלי (שביר), הוא מריץ עכשיו פקודה דטרמיניסטית אחת. חדש: - scripts/final_learning_pipeline.py — (1) ingest_final_version עם נתיב-הסופי (מדלג אם הזוג כבר analyzed; --force לחידוש), (2) רישום לקורפוס-הסגנון (idempotent — סוגר את הפער שפאנל-הסגנון דרש corpus_id), (3) style_lesson_panel --apply. --dry-run להרצה בטוחה. - scripts/final_halacha_pipeline.py — extract_internal_citations → corroboration.build_all → halacha_panel_approve --apply. --dry-run / --limit. briefs הרמס (web/paperclip_client._curator_task_brief) פושטו לפקודה-אחת לכל task — חסין מול הרצת-סוכן. תוקנו שני הפערים שזוהו: ingest דרש file_path, ופאנל-הסגנון דרש style_corpus. נלווה: תיקון help מיושן של halacha_panel_approve (--apply מחווט). SCRIPTS.md. אומת: שני ה-pipelines רצו dry-run על בל"מ 8126-03-25 (skip-ingest, קורפוס, פאנלים) בהצלחה. Invariants: INV-LRN1/LRN5/G10 (הפיך, שער-יו"ר ידני נשמר), INV-DM7. G2 — תזמור של יכולות קיימות, לא מסלול-מקביל. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -51,6 +51,8 @@
|
||||
| `goldset_independent_judge.py` | python | **INV-DM7 ולידציה** — שופט-תפקיד **עצמאי שני** ממודל אחר (DeepSeek API ישיר, OpenAI-compatible) ששובר את עיגון-ה-AI: מסווג rule_role **בעיוור** (בלי לראות תיוג-אדם או המלצת-claude) ומחשב מטריצת-הסכמה (deepseek↔אדם מול ai↔אדם) + ציר-גס (כלל-בר-הכללה מול application/obiter). **ממצא (2026-06-07):** ai↔אדם=100% (מעוגן), deepseek↔אדם=50% מדויק אך **92% גס** → תת-הסוג holding/interpretive/procedural עמום-מטבעו (לא לשער עליו); הציר-הגס אמין חוצה-מודלים. read-only על הזהב. `--model`/`--limit`/`--concurrency`. מפתח מ-`~/.hermes/profiles/deepseek/.env`. raw→`/tmp/goldset_judge_raw.json`. | ידני — ולידציית אמינות-תוויות |
|
||||
| `halacha_panel_approve.py` | python | **פאנל-אישור הלכות (Trust-or-Escalate, dry-run).** 3 שופטים בלתי-תלויי-לינאז' (Opus/claude_session · DeepSeek · Gemini-2.5-flash) מצביעים על ה**ציר-הגס האמין** (92% חוצה-מודלים): נקיות→"הלכה לשמירה?"; nli_unsupported→"הציטוט תומך בכלל?" (שיפוט-מחדש); פגומות→re-extraction. רק ורדיקט מוסכם פועל אוטומטית, **פיצול מסלים ליו"ר** (INV-G10). `--apply` **מחווט** (clean: רוב 2/3; nli: פה-אחד-entailed מנקה flag) — הפיך, מגבה ל-`data/audit/` קודם. מפתחות: DeepSeek מ-`~/.hermes/...`, Gemini מ-`~/.env`. **חובה מקומי**. dry-run 2026-06-07: 197→103 אוטו (פה-אחד) / ~15 (רוב). | ידני / שלב-אימות-הלכות במסלול-הסופי |
|
||||
| `style_lesson_panel.py` | python | **פאנל-סגנון דו-סוכני (למידה כפולה).** על-גבי דיסטילציית-ה-Opus (draft↔final ב-`draft_final_pairs.analysis`), שני שופטים בלתי-תלויים — DeepSeek + Gemini-2.5-flash — מצביעים לכל לקח על השאלה הגסה "האם זו הנחיית-סגנון מופשטת ובת-הכללה (INV-LRN5 — קול ולא מהות)?". הסכמה 2/2-keep → נכתב כ-`decision_lesson` (`source=panel:deepseek+gemini`); 2/2-drop → לא נכתב; פיצול/substance → מוסלם ליו"ר. `--apply` הפיך, מגבה ל-`data/audit/`. הטמעה ל-SKILL.md/lessons.md נשארת שער-יו"ר ידני (INV-G10). מפתחות כמו פאנל-ההלכות. **חובה מקומי**. `--case <num>` / `--pair-id <uuid>`. | שלב-למידה במסלול-הסופי |
|
||||
| `final_learning_pipeline.py` | python | **תזמור שלב-הלמידה (פקודה אחת).** מופעל ע"י הרמס כשלוחצים "הרץ למידת-קול" במסלול-הסופי. דטרמיניסטי: (1) `ingest_final_version` עם נתיב-הסופי, (2) רישום לקורפוס-הסגנון (idempotent), (3) `style_lesson_panel --apply`. מקפל את הזרימה לפקודה אחת כדי שהסוכן לא ירכיב כמה קריאות (חסין). idempotent. **חובה מקומי**. `--case <num>`. | אוטו (כפתור run-learning) / ידני |
|
||||
| `final_halacha_pipeline.py` | python | **תזמור שלב-אימות-ההלכות (פקודה אחת).** מופעל ע"י הרמס כשלוחצים "הרץ אימות-הלכות". דטרמיניסטי: (1) `extract_internal_citations(chair)`, (2) `corroboration.build_all()`, (3) `halacha_panel_approve --apply`. **חובה מקומי**. `--case <num>` / `--limit N` (תקרת תור). | אוטו (כפתור run-halacha) / ידני |
|
||||
| `halacha_panel_audit.py` | python | **רשת-ביטחון לפאנל** (selective-prediction monitoring) — דוגם הלכות שאושרו ע"י הפאנל (`reviewer LIKE 'panel:%'`), מריץ עליהן **שוב** את הצבעת-ה-KEEP של 3 השופטים, ומציף כל מקרה שכעת נוטה DROP (false-keep פוטנציאלי). report-only כברירת-מחדל; `--flag` מחזיר את ה-flips ל-`pending_review` לסקירת-יו"ר. `--sample N`/`--seed`. בסיס 2026-06-07: 0/15. מיועד להרצה תקופתית (שבועי). מייבא שופטים מ-`halacha_panel_approve`. **חובה מקומי**. | תקופתי (שבועי) — ניטור |
|
||||
| `halacha_panel_calibrate.py` | python | **כיול מדיניות-ההצבעה של הפאנל** (Trust-or-Escalate, ICLR 2025). מריץ את שאלת-ה-KEEP של `halacha_panel_approve` על מדגם-הזהב ומודד מול `is_holding` (הציר-הגס) precision+coverage לכל מדיניות (unanimous/majority) + ספירת false-keep/false-drop. נותן את **אחוז-הטעות בפועל** לבחירת סף-סיכון α. מייבא שופטים מ-`halacha_panel_approve` (מקור-אמת יחיד). read-only, **חובה מקומי**. | ידני — לפני חיווט `--apply` |
|
||||
| `halacha_rule_role_backfill.py` | python | **INV-DM7** — backfill חד-פעמי: מסווג-מחדש את ההלכות הישנות (`rule_type IN ('binding','persuasive')` — ערכי-סמכות שנשמרו במסווה תפקיד לפני פיצול הצירים) לאחד מחמשת **תפקידי-הכלל** (holding/interpretive/procedural/application/obiter) דרך claude_session המקומי (אפס עלות). **לא נוגע בסמכות** (נגזרת מ-`precedent_level`). `--apply` (ברירת-מחדל dry-run) / `--limit N` / `--concurrency`. כותב backup CSV ל-`data/audit/` תחילה. fail-safe (פריט שנכשל → נשמר ערך ישן). **חובה מקומי** (claude_session). | ידני חד-פעמי אחרי deploy של פיצול-הסמכות |
|
||||
|
||||
87
scripts/final_halacha_pipeline.py
Normal file
87
scripts/final_halacha_pipeline.py
Normal file
@@ -0,0 +1,87 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot LOCAL pipeline for the 'run-halacha' button (halacha validation).
|
||||
|
||||
The /api/cases/{case}/final/run-halacha endpoint wakes the Hermes curator, which
|
||||
runs THIS single deterministic command (the 3-judge panel uses local DeepSeek+Gemini
|
||||
keys + the local claude CLI, so it can't run inside the container).
|
||||
|
||||
Steps:
|
||||
[1] extract_internal_citations(chair) → links the citation graph for the chair's
|
||||
decisions (idempotent; ON CONFLICT DO NOTHING).
|
||||
[2] corroboration_rebuild → builds the citation-treatment signal and applies the
|
||||
corroborated→approved / overruled→pending policy (X11 Phase 2).
|
||||
[3] halacha_panel_approve --apply → 3 judges (Opus+DeepSeek+Gemini); agreement
|
||||
auto-approves/rejects (reversible, CSV-backed); splits/defects → chair (INV-G10).
|
||||
|
||||
NB: per-precedent halacha extraction for newly-cited precedents is NOT automated here
|
||||
(it needs each cited precedent to be in the library with a known case_law_id) — the
|
||||
chair drives that from /precedents when a missing precedent is added.
|
||||
|
||||
Local-only. Idempotent. The panel pass over the full pending queue can take minutes.
|
||||
|
||||
cd ~/legal-ai/mcp-server
|
||||
.venv/bin/python ../scripts/final_halacha_pipeline.py --case 8126-03-25
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from legal_mcp.services import corroboration, db # noqa: E402
|
||||
from legal_mcp.tools.citations import extract_internal_citations # noqa: E402
|
||||
|
||||
|
||||
async def main(args: argparse.Namespace) -> int:
|
||||
case_number = args.case
|
||||
case = await db.get_case_by_number(case_number)
|
||||
if not case:
|
||||
print(f"✗ תיק {case_number} לא נמצא")
|
||||
return 1
|
||||
chair = case.get("chair_name") or "דפנה תמיר"
|
||||
|
||||
# [1] citation graph
|
||||
print(f"[1/3] extract_internal_citations (chair={chair})…", flush=True)
|
||||
raw = await extract_internal_citations(chair_name=chair, limit=0)
|
||||
try:
|
||||
d = json.loads(raw).get("data", {})
|
||||
print(f" ✓ extracted {d.get('extracted')} · linked {d.get('linked')} "
|
||||
f"· new {d.get('new')}")
|
||||
except Exception:
|
||||
print(f" (citations returned: {str(raw)[:160]})")
|
||||
|
||||
# [2] corroboration signal + policy (whole corpus backfill) — skipped on dry-run
|
||||
if args.dry_run:
|
||||
print("[2/3] corroboration_rebuild — מדולג (dry-run)")
|
||||
else:
|
||||
print("[2/3] corroboration_rebuild (backfill)…", flush=True)
|
||||
try:
|
||||
cr = await corroboration.build_all()
|
||||
print(f" ✓ {cr}")
|
||||
except Exception as e:
|
||||
print(f" ⚠ corroboration failed (non-fatal): {e}")
|
||||
|
||||
# [3] three-judge halacha panel
|
||||
apply = not args.dry_run
|
||||
print(f"[3/3] halacha_panel_approve {'--apply' if apply else '(dry-run)'} "
|
||||
f"(Opus+DeepSeek+Gemini)…", flush=True)
|
||||
import halacha_panel_approve as hpa
|
||||
rc = await hpa.main(Namespace(limit=args.limit, concurrency=6, apply=apply))
|
||||
print("\n✓ pipeline-אימות-הלכות הושלם" + (" (dry-run)" if args.dry_run else ""))
|
||||
return rc or 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--case", required=True, help="case_number, e.g. 8126-03-25")
|
||||
ap.add_argument("--limit", type=int, default=0,
|
||||
help="cap pending halachot judged (0 = full queue)")
|
||||
ap.add_argument("--dry-run", dest="dry_run", action="store_true",
|
||||
help="citations only; skip corroboration writes; panel in dry-run")
|
||||
raise SystemExit(asyncio.run(main(ap.parse_args())))
|
||||
140
scripts/final_learning_pipeline.py
Normal file
140
scripts/final_learning_pipeline.py
Normal file
@@ -0,0 +1,140 @@
|
||||
#!/usr/bin/env python3
|
||||
"""One-shot LOCAL pipeline for the 'run-learning' button (voice learning).
|
||||
|
||||
The container can't run the LLM steps (claude/DeepSeek/Gemini keys are local), so
|
||||
the /api/cases/{case}/final/run-learning endpoint wakes the Hermes curator, which
|
||||
runs THIS single deterministic command. Collapsing the flow into one script (rather
|
||||
than asking the agent to assemble several tool calls) makes the autonomous path
|
||||
reliable.
|
||||
|
||||
Steps:
|
||||
[1] ingest_final_version(case, file_path) → Opus distils draft↔final into
|
||||
draft_final_pairs.analysis (status→analyzed). INV-LRN5 separates style↔substance.
|
||||
[2] enroll the final into style_corpus (idempotent) so lessons have a corpus_id.
|
||||
[3] style_lesson_panel --apply → DeepSeek+Gemini vote per style lesson; 2/2-keep →
|
||||
decision_lesson (source=panel:deepseek+gemini); split → chair (INV-G10).
|
||||
|
||||
The fold into SKILL.md / legal-decision-lessons.md stays a manual chair gate.
|
||||
Local-only. Idempotent — safe to re-run.
|
||||
|
||||
cd ~/legal-ai/mcp-server
|
||||
.venv/bin/python ../scripts/final_learning_pipeline.py --case 8126-03-25
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import json
|
||||
import sys
|
||||
from argparse import Namespace
|
||||
from pathlib import Path
|
||||
|
||||
# scripts/ is not a package — make style_lesson_panel importable.
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
|
||||
from legal_mcp import config # noqa: E402
|
||||
from legal_mcp.services import db # noqa: E402
|
||||
from legal_mcp.tools.documents import document_upload_training # noqa: E402
|
||||
from legal_mcp.tools.workflow import ingest_final_version # noqa: E402
|
||||
|
||||
|
||||
def _resolve_final_path(case_number: str) -> str | None:
|
||||
"""The canonical final saved by /final/upload, with a graceful fallback."""
|
||||
export_dir = config.find_case_dir(case_number) / "exports"
|
||||
canonical = export_dir / f"סופי-{case_number}.docx"
|
||||
if canonical.exists():
|
||||
return str(canonical)
|
||||
cands = sorted(export_dir.glob("סופי-*.docx"))
|
||||
return str(cands[0]) if cands else None
|
||||
|
||||
|
||||
async def _has_style_corpus(decision_number: str) -> bool:
|
||||
pool = await db.get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
row = await conn.fetchrow(
|
||||
"SELECT 1 FROM style_corpus WHERE decision_number = $1 LIMIT 1",
|
||||
decision_number,
|
||||
)
|
||||
return bool(row)
|
||||
|
||||
|
||||
async def _latest_pair_status(case_id) -> str | None:
|
||||
pool = await db.get_pool()
|
||||
async with pool.acquire() as conn:
|
||||
return await conn.fetchval(
|
||||
"SELECT status FROM draft_final_pairs WHERE case_id = $1 "
|
||||
"ORDER BY created_at DESC LIMIT 1",
|
||||
case_id,
|
||||
)
|
||||
|
||||
|
||||
async def main(args: argparse.Namespace) -> int:
|
||||
case_number = args.case
|
||||
case = await db.get_case_by_number(case_number)
|
||||
if not case:
|
||||
print(f"✗ תיק {case_number} לא נמצא")
|
||||
return 1
|
||||
|
||||
final_path = _resolve_final_path(case_number)
|
||||
if not final_path:
|
||||
print(f"✗ לא נמצא קובץ סופי ל-{case_number} (העלה דרך 'העלאת החלטה סופית של היו\"ר')")
|
||||
return 1
|
||||
print(f"final: {final_path}\n")
|
||||
|
||||
# [1] distillation (Opus) — skip if already analyzed (idempotent; --force to redo)
|
||||
status = await _latest_pair_status(case["id"])
|
||||
if status == "analyzed" and not args.force:
|
||||
print(f"[1/3] ingest_final_version — דולג (הזוג כבר analyzed; --force לחידוש)")
|
||||
else:
|
||||
print("[1/3] ingest_final_version — דיסטילציית טיוטה↔סופי…", flush=True)
|
||||
raw = await ingest_final_version(case_number, file_path=final_path)
|
||||
try:
|
||||
env = json.loads(raw)
|
||||
if env.get("status") == "error":
|
||||
print(f" ✗ {env.get('message')}")
|
||||
return 1
|
||||
d = env.get("data", {})
|
||||
ds = d.get("diff_stats", {})
|
||||
print(f" ✓ change {ds.get('change_percent')}% · lessons {d.get('lessons_count')} "
|
||||
f"· new_expr {d.get('new_expressions')}")
|
||||
except Exception:
|
||||
print(f" (ingest returned: {raw[:200]})")
|
||||
|
||||
# [2] enroll into style_corpus (idempotent) — lessons need a corpus_id
|
||||
print("[2/3] רישום לקורפוס-הסגנון (idempotent)…", flush=True)
|
||||
if await _has_style_corpus(case_number):
|
||||
print(" ✓ כבר רשום בקורפוס-הסגנון")
|
||||
else:
|
||||
r = await document_upload_training(
|
||||
final_path,
|
||||
decision_number=case_number,
|
||||
title=f"החלטה סופית — {case.get('proceeding_type', '')} {case_number}".strip(),
|
||||
practice_area=case.get("practice_area") or "appeals_committee",
|
||||
appeal_subtype=case.get("appeal_subtype") or "",
|
||||
)
|
||||
try:
|
||||
print(f" ✓ corpus_id {json.loads(r).get('data', {}).get('corpus_id')}")
|
||||
except Exception:
|
||||
print(f" (training upload returned: {r[:160]})")
|
||||
|
||||
# [3] two-judge style panel (DeepSeek + Gemini)
|
||||
apply = not args.dry_run
|
||||
print(f"[3/3] פאנל-סגנון דו-סוכני (DeepSeek+Gemini) {'--apply' if apply else '(dry-run)'}…",
|
||||
flush=True)
|
||||
import style_lesson_panel as slp
|
||||
rc = await slp.main(Namespace(
|
||||
case=case_number, pair_id=None, apply=apply, limit=0, concurrency=4,
|
||||
))
|
||||
print("\n✓ pipeline-למידה הושלם" + (" (dry-run)" if args.dry_run else ""))
|
||||
return rc or 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--case", required=True, help="case_number, e.g. 8126-03-25")
|
||||
ap.add_argument("--dry-run", dest="dry_run", action="store_true",
|
||||
help="run the chain but the style panel in dry-run (no decision_lesson writes)")
|
||||
ap.add_argument("--force", action="store_true",
|
||||
help="re-run ingest_final_version even if the pair is already analyzed")
|
||||
raise SystemExit(asyncio.run(main(ap.parse_args())))
|
||||
@@ -335,5 +335,6 @@ if __name__ == "__main__":
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--limit", type=int, default=0)
|
||||
ap.add_argument("--concurrency", type=int, default=6)
|
||||
ap.add_argument("--apply", action="store_true", help="(not yet wired — dry-run only)")
|
||||
ap.add_argument("--apply", action="store_true",
|
||||
help="write the agreed verdicts (reversible, CSV-backed); default dry-run")
|
||||
raise SystemExit(asyncio.run(main(ap.parse_args())))
|
||||
|
||||
Reference in New Issue
Block a user