Compare commits
1 Commits
6ad0a387fe
...
worktree-c
| Author | SHA1 | Date | |
|---|---|---|---|
| dde44b8095 |
@@ -226,7 +226,7 @@ Paperclip חוסם אוטומטית כל issue ב-`in_progress` שאין לו ru
|
|||||||
### שלב 0: בדוק למה התעוררת
|
### שלב 0: בדוק למה התעוררת
|
||||||
|
|
||||||
**לפני כל דבר אחר** — בדוק את סיבת ההתעוררות (`$PAPERCLIP_WAKE_REASON`):
|
**לפני כל דבר אחר** — בדוק את סיבת ההתעוררות (`$PAPERCLIP_WAKE_REASON`):
|
||||||
- **פעולות סטרוקטורליות (כפתורי-UI, בלי פענוח-טקסט):** אם `$PAPERCLIP_WAKE_PAYLOAD_JSON` מכיל שדה `action` → נתב דטרמיניסטית לפי הערך: `action == "interim_draft"` → **שלב H** (טיוטת ביניים); `action == "party_claims_summary"` → **שלב H2** (סיכום מנהלים). אלו side-quests — אל תסרוק תיקים אחרים, טפל רק בתיק שב-payload (`case_number`/`issueId`). ה-`issueId` שב-payload הוא **issue-ילד ייעודי שמשויך אליך** (נוצר ע"י המערכת כדי שהריצה לא תבוטל כשה-issue הראשי ממתין-ליו"ר; #227) — הרץ את הפעולה, פרסם comment עם התוצאה, ו**סגור את ה-issue-ילד הזה כ-done** בסיום. אל תיגע ב-issue הראשי של התיק.
|
- **פעולות סטרוקטורליות (כפתורי-UI, בלי פענוח-טקסט):** אם `$PAPERCLIP_WAKE_PAYLOAD_JSON` מכיל שדה `action` → נתב דטרמיניסטית לפי הערך: `action == "interim_draft"` → **שלב H** (טיוטת ביניים); `action == "party_claims_summary"` → **שלב H2** (סיכום מנהלים). אלו side-quests — אל תסרוק תיקים אחרים, טפל רק בתיק שב-payload (`case_number`/`issueId`).
|
||||||
- אם ה-reason מכיל `user_commented` **ו**-`$PAPERCLIP_WAKE_PAYLOAD_JSON` כולל `issueId` → **דלג ישירות לסעיף "טיפול בתגובות חדשות מחיים"** עם ה-issue הזה. אל תסרוק תיקים אחרים. **טפל רק בתגובה.**
|
- אם ה-reason מכיל `user_commented` **ו**-`$PAPERCLIP_WAKE_PAYLOAD_JSON` כולל `issueId` → **דלג ישירות לסעיף "טיפול בתגובות חדשות מחיים"** עם ה-issue הזה. אל תסרוק תיקים אחרים. **טפל רק בתגובה.**
|
||||||
- אם ה-reason מכיל `agent_completion` → דלג לשלב E/F בהתאם לסוכן שסיים
|
- אם ה-reason מכיל `agent_completion` → דלג לשלב E/F בהתאם לסוכן שסיים
|
||||||
- אם ה-reason מכיל `precedent_extraction_` → **דלג לסעיף "חילוץ פסיקה אוטומטי"**. אל תיגע בתיקים — זו עבודת ספרייה.
|
- אם ה-reason מכיל `precedent_extraction_` → **דלג לסעיף "חילוץ פסיקה אוטומטי"**. אל תיגע בתיקים — זו עבודת ספרייה.
|
||||||
@@ -719,13 +719,13 @@ ls data/cases/$CASE_NUMBER/documents/research/analysis-and-research.md
|
|||||||
```
|
```
|
||||||
mcp__legal-ai__export_interim_draft(case_number="...")
|
mcp__legal-ai__export_interim_draft(case_number="...")
|
||||||
```
|
```
|
||||||
מייצר `data/cases/{case_number}/exports/טיוטה-טענות_הצדדים_{N}.docx`, מעדכן `active_draft_path`.
|
מייצר `data/cases/{case_number}/exports/טיוטת-ביניים-v{N}.docx`, מעדכן `active_draft_path`.
|
||||||
|
|
||||||
5. **דווח לחיים** (כולל מייל דרך `scripts/notify.py`):
|
5. **דווח לחיים** (כולל מייל דרך `scripts/notify.py`):
|
||||||
```
|
```
|
||||||
## טיוטת ביניים מוכנה — ערר {case_number}
|
## טיוטת ביניים מוכנה — ערר {case_number}
|
||||||
|
|
||||||
📄 **קובץ:** `data/cases/{case_number}/exports/טיוטה-טענות_הצדדים_{N}.docx`
|
📄 **קובץ:** `data/cases/{case_number}/exports/טיוטת-ביניים-v{N}.docx`
|
||||||
|
|
||||||
### מה כלול
|
### מה כלול
|
||||||
| בלוק | כותרת | מילים |
|
| בלוק | כותרת | מילים |
|
||||||
|
|||||||
@@ -531,3 +531,33 @@ Two 1200-25 entries recorded a case-specific issue order (threshold → plan int
|
|||||||
traffic) with no generalizable rule. They are case artifacts, captured in that case's
|
traffic) with no generalizable rule. They are case artifacts, captured in that case's
|
||||||
analysis-and-research.md — no general lesson folded.
|
analysis-and-research.md — no general lesson folded.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Doctrinal Lessons — Chair Final vs. Our Draft, 8125-09-24 (July 5, 2026)
|
||||||
|
|
||||||
|
### Source
|
||||||
|
- Case: 8125-09-24 (שובל טוב רמות / רמות אלון — ערר על שומה מכרעת, היטל השבחה; קבלה
|
||||||
|
חלקית + מינוי שמאי מייעץ חדש). Dafna's signed final vs. our full draft (block י).
|
||||||
|
- These are **substantive doctrine**, not style. Recorded verbatim from the signed
|
||||||
|
decision; also captured as `chair_feedback` ד1–ד4 on the case (category `other`),
|
||||||
|
pending a proper canonical-principle home (TaskMaster #225).
|
||||||
|
- ⚠ **#47 and #48 SUPERSEDE our prior draft's legal thesis.** Our draft parked the
|
||||||
|
chargeability question as an "open interpretive question" and over-weighted the
|
||||||
|
equality doctrine toward the appellant; Dafna decided the opposite. Follow the chair.
|
||||||
|
|
||||||
|
### 47. "Space Conversion" מחיר-למשתכן→שוק-חופשי IS a Chargeable Planning Betterment (SUPERSEDES prior thesis)
|
||||||
|
- **Lesson:** כאשר הקלה מוסיפה יחידות דיור (בלי תוספת זכויות/שטח עיקרי) ומשנה את תמהיל הדירות כך ששטחים שבמצב הקודם היו כפופים למגבלת "מחיר למשתכן" משתחררים לשיווק בשוק חופשי — זו **השבחה תכנונית בת-חיוב**, ומתודת ה"הסבה" (הפרש השווי מחיר-למשתכן↔שוק-חופשי על השטחים שהוסבו) לגיטימית ומנומקת: "לא ייתכן כי יזם 'ייהנה' משווי נמוך יותר לצורך חיוב בהיטל לאור מגבלות מחיר למשתכן כשזה משרת אותו". **אין** לגדֵר זאת כשאלה משפטית-פרשנית פתוחה בדבר "גדרי השבחה תכנונית" ולהטיל ספק בחיוב מכוח דרישת הקשר-הסיבתי (בית הכרם/פמיני) — זו הייתה גישת הטיוטה שלנו, והיא נדחתה.
|
||||||
|
- **Rule:** In מחיר-למשתכן projects, treat the free-market "space conversion" enabled by a unit-count relief as a chargeable planning betterment and uphold the difference-in-value method. Do NOT frame it as an open interpretive question or cast causal-nexus doubt on chargeability.
|
||||||
|
|
||||||
|
### 48. A Neighboring Final Assessment Does Not Compel Alignment; Equality Does Not Perpetuate Error
|
||||||
|
- **Lesson:** קיום שומה מכרעת חלוטה בנכס סמוך (אף באותו מכרז ותנאים) **אינו מחייב** את השמאי המכריע/הוועדה ליישר קו עמה; שומה מנומקת היטב רשאית לסטות ממנה — "לא נוכל להיאחז בשומה מכרעת אחרת רק מכיוון והיא קיימת". עקרון השוויון בגביית מס אינו מנציח טעות. אין להעמיס את דוקטרינת השוויון (דיבון שלום/גנדליס) כ"חובת הנמקה מוגברת" המטה לקבלת הערר — כפי שעשתה הטיוטה שלנו. עדיין: פער ניכר מול שומה סמוכה מצדיק בחינה והנמקה, לא אימוץ אוטומטי. **הערת-לוואי (ד3):** ועדה מקומית החולקת על שומה מכרעת ובוחרת שלא לערור עליה — ראוי שתיידע את הציבור; שינוי-עמדה שלה עם הזמן אפשרי אך צריך להיות החריג ומחייב הנמקה מוגברת.
|
||||||
|
- **Rule:** A final neighboring assessment is persuasive, not binding; a well-reasoned assessment may depart from it. Do not over-weight the equality doctrine to favor the appellant — flag the gap, require reasoning, but do not auto-align.
|
||||||
|
|
||||||
|
### 49. When Remand-to-the-Original-Assessor Is Blocked, Appoint a New Advisory Assessor
|
||||||
|
- **Lesson:** כשדרך-המלך (השבת השומה לשמאי המכריע לתיקון/הבהרה) חסומה מפני שהשמאי המכריע פרש/סיים כהונתו — מינוי **שמאי מייעץ חדש** לבחינה מחודשת של הרכיב שבמחלוקת הוא הפתרון, מכוח סמכות הוועדה הרחבה (אשקלוני) והיגיון גנדליס.
|
||||||
|
- **Rule:** If the deciding assessor has left office and cannot receive the file back, appoint a new advisory assessor to re-examine the disputed component under the committee's guidance.
|
||||||
|
|
||||||
|
### 50. Prefer a Reasoned Holding Over a Parked "Open Question" (methodology)
|
||||||
|
- **Lesson:** במקום לגדר סוגיה מהותית כ"שאלה משפטית פתוחה לשתי גישות לגיטימיות" ולהעבירה כמות-שהיא להשבה, דפנה **הכריעה** בה כשהחומר תמך בכך ("אנו סבורים כי השמאי המכריע פעל כדין ונסביר… בנקודה זו צדק לדעתנו השמאי המכריע"), והשיבה רק את הרכיב השמאי-היישומי הצר. הכרעה מנומקת עדיפה על היסוס אקדמי.
|
||||||
|
- **Rule:** Decide the interpretive question when the record supports a holding; reserve remand for the narrow appraisal-application residue. Don't park a decidable מהות issue as an "open question."
|
||||||
|
|
||||||
|
|||||||
@@ -192,16 +192,16 @@ BLOCK_PROMPTS = {
|
|||||||
## כללים קריטיים:
|
## כללים קריטיים:
|
||||||
- **סנתז טענות דומות** — אל תרשום כל טענה בנפרד. קבץ טענות דומות לנושא אחד. למשל: כל הטענות על הודעות → סעיף אחד, כל הטענות על רכוש משותף → סעיף אחד.
|
- **סנתז טענות דומות** — אל תרשום כל טענה בנפרד. קבץ טענות דומות לנושא אחד. למשל: כל הטענות על הודעות → סעיף אחד, כל הטענות על רכוש משותף → סעיף אחד.
|
||||||
- גוף שלישי: "העוררים טוענים כי...", "הוועדה המקומית ציינה כי..."
|
- גוף שלישי: "העוררים טוענים כי...", "הוועדה המקומית ציינה כי..."
|
||||||
- **מבנה: חלק (סעיף עם כותרת-משנה) לכל צד שמופיע בטענות שחולצו למטה** — לפי הכותרות שם (### ...). אל תמציא צדדים שאינם מופיעים ואל תשמיט צד שמופיע.
|
- **מבנה קבוע עם 3 חלקים:**
|
||||||
- "טענות העוררים" — 8-12 סעיפים מקובצים לפי נושא.
|
1. "טענות העוררים" — 8-12 סעיפים מקובצים לפי נושא
|
||||||
- **צד-משיב/מתנגד: כתוב חלק נפרד לכל כתב-תשובה** שמופיע (למשל "עמדת משיבות 2-3" ו-"עמדת משיבים 4-6" בנפרד) — 5-10 סעיפים לכל אחד. **אל תמזג משיבים שונים לסעיף אחד**, ואם עמדותיהם מנוגדות — שקף זאת.
|
2. "עמדת הוועדה המקומית" — 5-8 סעיפים
|
||||||
- "עמדת הוועדה המקומית" / "עמדת מבקשי ההיתר" (אם מופיעים) — 5-8 סעיפים.
|
3. "עמדת מבקשי ההיתר" (אם יש) — 5-10 סעיפים
|
||||||
- כותרת: "תמצית טענות הצדדים"
|
- כותרת: "תמצית טענות הצדדים"
|
||||||
- נאמנות למקור — לא להמציא טענות, אבל כן לאחד ולסכם טענות חוזרות
|
- נאמנות למקור — לא להמציא טענות, אבל כן לאחד ולסכם טענות חוזרות
|
||||||
- אין ניתוח, אין מסקנות, אין הערכה ("טענה חלשה/חזקה")
|
- אין ניתוח, אין מסקנות, אין הערכה ("טענה חלשה/חזקה")
|
||||||
- רק מכתבי טענות מקוריים (לא השלמות טיעון)
|
- רק מכתבי טענות מקוריים (לא השלמות טיעון)
|
||||||
- מספור רציף
|
- מספור רציף
|
||||||
- **יעד אורך: 800-1500 מילים** (יותר כשיש כמה כתבי-תשובה נפרדים — כל צד מקבל את מלוא ההתייחסות)
|
- **יעד אורך: 800-1500 מילים**
|
||||||
|
|
||||||
## טענות שחולצו (קבץ טענות דומות לנושאים):
|
## טענות שחולצו (קבץ טענות דומות לנושאים):
|
||||||
{claims_context}
|
{claims_context}
|
||||||
@@ -284,7 +284,6 @@ BLOCK_PROMPTS = {
|
|||||||
- **ללא כפילות** — הפנה לבלוקים קודמים: "כאמור בסעיף X לעיל"
|
- **ללא כפילות** — הפנה לבלוקים קודמים: "כאמור בסעיף X לעיל"
|
||||||
- **מספור רציף** — המשך מספור מהבלוק הקודם
|
- **מספור רציף** — המשך מספור מהבלוק הקודם
|
||||||
- מותרות כותרות-משנה כשיש נושאים נפרדים לחלוטין
|
- מותרות כותרות-משנה כשיש נושאים נפרדים לחלוטין
|
||||||
- **צדדים מרובים** — כשיש כמה משיבים/מתנגדים או כתבי-תשובה נפרדים (ראה הכותרות שתחת "טענות" לעיל, למשל "משיבות 2-3" מול "משיבים 4-6"), התייחס לעמדת כל אחד לגופה ואל תמזג אותם ל"טענות המשיבים" גורפות. אם משיבים שונים נוקטים **עמדות מנוגדות זו לזו** — ציין זאת במפורש והכרע ביניהן בנימוק; אם עמדותיהם משלימות — ניתן לאגד תוך שמירת הייחוס.
|
|
||||||
|
|
||||||
## כיוון מאושר (חובה):
|
## כיוון מאושר (חובה):
|
||||||
{direction_context}
|
{direction_context}
|
||||||
@@ -630,44 +629,18 @@ async def _build_claims_context(case_id: UUID) -> str:
|
|||||||
# Fallback to all non-block-zayin claims if no source claims exist.
|
# Fallback to all non-block-zayin claims if no source claims exist.
|
||||||
source_claims = [c for c in claims if c.get("source_document", "") != "block-zayin"] or claims
|
source_claims = [c for c in claims if c.get("source_document", "") != "block-zayin"] or claims
|
||||||
|
|
||||||
# Group by (party_role, brief) so a multi-litigant side (respondent /
|
lines = []
|
||||||
# permit_applicant) whose claims come from distinct pleadings reads as
|
current_role = ""
|
||||||
# SEPARATE positions — e.g. "כתב תשובה משיבות 2-3" vs "משיבים 4-6" — instead
|
|
||||||
# of one merged "טענות המשיבים" (#224). The brief label is the source
|
|
||||||
# pleading, and which sides split is SPLIT_PARTIES — the SAME rule the
|
|
||||||
# argument aggregator uses, so block ז and the arguments panel agree (G2).
|
|
||||||
from legal_mcp.services.argument_aggregator import SPLIT_PARTIES
|
|
||||||
|
|
||||||
role_heb = {"appellant": "טענות העוררים", "respondent": "טענות המשיבים",
|
role_heb = {"appellant": "טענות העוררים", "respondent": "טענות המשיבים",
|
||||||
"committee": "עמדת הוועדה המקומית", "permit_applicant": "עמדת מבקשי ההיתר"}
|
"committee": "עמדת הוועדה המקומית", "permit_applicant": "עמדת מבקשי ההיתר"}
|
||||||
role_order = ["appellant", "committee", "respondent", "permit_applicant"]
|
|
||||||
|
|
||||||
groups: dict[tuple[str, str], list[dict]] = {}
|
|
||||||
for c in source_claims:
|
|
||||||
role = c.get("party_role", "") or ""
|
|
||||||
brief = (c.get("source_document", "") or "").strip() if role in SPLIT_PARTIES else ""
|
|
||||||
groups.setdefault((role, brief), []).append(c)
|
|
||||||
|
|
||||||
def _sort_key(k: tuple[str, str]) -> tuple[int, str]:
|
|
||||||
role, brief = k
|
|
||||||
idx = role_order.index(role) if role in role_order else len(role_order)
|
|
||||||
return (idx, brief)
|
|
||||||
|
|
||||||
lines: list[str] = []
|
|
||||||
claim_num = 0
|
claim_num = 0
|
||||||
for role, brief in sorted(groups.keys(), key=_sort_key):
|
for c in source_claims:
|
||||||
header = role_heb.get(role, role or "טענות נוספות")
|
if c["party_role"] != current_role:
|
||||||
if brief:
|
current_role = c["party_role"]
|
||||||
header = f"{header} — {brief}"
|
lines.append(f"\n### {role_heb.get(current_role, current_role)}")
|
||||||
lines.append(f"\n### {header}")
|
|
||||||
for c in groups[(role, brief)]:
|
|
||||||
claim_num += 1
|
claim_num += 1
|
||||||
lines.append(f"טענה #{claim_num}: {c['claim_text'][:400]}")
|
lines.append(f"טענה #{claim_num}: {c['claim_text'][:400]}")
|
||||||
lines.append(
|
lines.append(f"\n**סה\"כ {claim_num} טענות. ענה על כל טענה מהותית; טענות [bundle] — אגד; טענות [skip] — ציון קצר בלבד.**")
|
||||||
f"\n**סה\"כ {claim_num} טענות. שמור על ההפרדה בין הצדדים לעיל — "
|
|
||||||
f"לכל צד/כתב-תשובה עמדה נפרדת (אל תמזג משיבים שונים). ענה על כל טענה "
|
|
||||||
f"מהותית; טענות [bundle] — אגד; טענות [skip] — ציון קצר בלבד.**"
|
|
||||||
)
|
|
||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1900,24 +1900,6 @@ CREATE INDEX IF NOT EXISTS idx_legal_arguments_party_name
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
|
|
||||||
# V51 (#226): hearing-attendance provenance for the "מה קרה בדיון" panel. The
|
|
||||||
# ערר-hearing protocol names who actually appeared (עוררים/משיבים + their
|
|
||||||
# counsel) and, when stated, the presiding panel. ``_extract_header`` already
|
|
||||||
# extracts this feed but only ``hearing_date`` had a canonical home (on cases);
|
|
||||||
# the attendee lists were returned as provenance and dropped. This column gives
|
|
||||||
# them a home so the panel can display them.
|
|
||||||
#
|
|
||||||
# This is DISTINCT from ``decisions.panel_members`` (G2, not a parallel path):
|
|
||||||
# that column is the authoring tribunal recorded on a specific written-decision
|
|
||||||
# version (the DOCX signature block). ``hearing_attendees`` is a snapshot of who
|
|
||||||
# was present at the *hearing*, extracted from the protocol — hearing-event
|
|
||||||
# provenance, not decision-authorship. Shape:
|
|
||||||
# {"panel_members": [...], "appellants_present": [...], "respondents_present": [...]}
|
|
||||||
SCHEMA_V51_SQL = """
|
|
||||||
ALTER TABLE cases ADD COLUMN IF NOT EXISTS hearing_attendees JSONB NOT NULL DEFAULT '{}';
|
|
||||||
"""
|
|
||||||
|
|
||||||
|
|
||||||
# Stable, arbitrary key for the session-level advisory lock that serialises
|
# Stable, arbitrary key for the session-level advisory lock that serialises
|
||||||
# schema DDL across processes. Every short-lived process (cron drains, services)
|
# schema DDL across processes. Every short-lived process (cron drains, services)
|
||||||
# re-runs the idempotent migrations on startup; without this lock two processes
|
# re-runs the idempotent migrations on startup; without this lock two processes
|
||||||
@@ -1990,7 +1972,6 @@ async def _apply_schema_ddl(conn: asyncpg.Connection) -> None:
|
|||||||
await conn.execute(SCHEMA_V48_SQL)
|
await conn.execute(SCHEMA_V48_SQL)
|
||||||
await conn.execute(SCHEMA_V49_SQL)
|
await conn.execute(SCHEMA_V49_SQL)
|
||||||
await conn.execute(SCHEMA_V50_SQL)
|
await conn.execute(SCHEMA_V50_SQL)
|
||||||
await conn.execute(SCHEMA_V51_SQL)
|
|
||||||
|
|
||||||
|
|
||||||
async def init_schema() -> None:
|
async def init_schema() -> None:
|
||||||
@@ -2213,7 +2194,7 @@ async def update_case(case_id: UUID, **fields) -> dict | None:
|
|||||||
set_clauses = []
|
set_clauses = []
|
||||||
values = []
|
values = []
|
||||||
for i, (key, val) in enumerate(fields.items(), start=2):
|
for i, (key, val) in enumerate(fields.items(), start=2):
|
||||||
if key in ("appellants", "respondents", "tags", "hearing_attendees"):
|
if key in ("appellants", "respondents", "tags"):
|
||||||
val = json.dumps(val)
|
val = json.dumps(val)
|
||||||
set_clauses.append(f"{key} = ${i}")
|
set_clauses.append(f"{key} = ${i}")
|
||||||
values.append(val)
|
values.append(val)
|
||||||
@@ -2226,7 +2207,7 @@ async def update_case(case_id: UUID, **fields) -> dict | None:
|
|||||||
|
|
||||||
def _row_to_case(row: asyncpg.Record) -> dict:
|
def _row_to_case(row: asyncpg.Record) -> dict:
|
||||||
d = dict(row)
|
d = dict(row)
|
||||||
for field in ("appellants", "respondents", "tags", "hearing_attendees"):
|
for field in ("appellants", "respondents", "tags"):
|
||||||
if isinstance(d.get(field), str):
|
if isinstance(d.get(field), str):
|
||||||
d[field] = json.loads(d[field])
|
d[field] = json.loads(d[field])
|
||||||
d["id"] = str(d["id"])
|
d["id"] = str(d["id"])
|
||||||
|
|||||||
@@ -399,15 +399,8 @@ _INTERIM_BLOCK_ORDER = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def _draft_naming(mode: str) -> tuple[str, str]:
|
def _draft_filename_prefix(mode: str) -> str:
|
||||||
"""(filename prefix, version separator) per export mode.
|
return "טיוטת-ביניים" if mode == "interim" else "טיוטה"
|
||||||
|
|
||||||
interim → ``טיוטה-טענות_הצדדים_{N}.docx`` (chair-requested naming);
|
|
||||||
final → ``טיוטה-v{N}.docx``.
|
|
||||||
"""
|
|
||||||
if mode == "interim":
|
|
||||||
return "טיוטה-טענות_הצדדים", "_"
|
|
||||||
return "טיוטה", "-v"
|
|
||||||
|
|
||||||
|
|
||||||
async def export_decision(
|
async def export_decision(
|
||||||
@@ -492,19 +485,16 @@ async def export_decision(
|
|||||||
if not output_path:
|
if not output_path:
|
||||||
export_dir = config.find_case_dir(case["case_number"]) / "exports"
|
export_dir = config.find_case_dir(case["case_number"]) / "exports"
|
||||||
export_dir.mkdir(parents=True, exist_ok=True)
|
export_dir.mkdir(parents=True, exist_ok=True)
|
||||||
prefix, sep = _draft_naming(mode)
|
prefix = _draft_filename_prefix(mode)
|
||||||
existing = sorted(export_dir.glob(f"{prefix}{sep}*.docx"))
|
existing = sorted(export_dir.glob(f"{prefix}-v*.docx"))
|
||||||
next_ver = 1
|
next_ver = 1
|
||||||
for p in existing:
|
for p in existing:
|
||||||
try:
|
try:
|
||||||
# Version is the trailing integer after the separator. Using
|
ver = int(p.stem.split("-v")[1])
|
||||||
# rsplit keeps this correct even when the prefix itself contains
|
|
||||||
# the separator char (e.g. "טיוטה-טענות_הצדדים" with sep="_").
|
|
||||||
ver = int(p.stem.rsplit(sep, 1)[1])
|
|
||||||
next_ver = max(next_ver, ver + 1)
|
next_ver = max(next_ver, ver + 1)
|
||||||
except (IndexError, ValueError):
|
except (IndexError, ValueError):
|
||||||
pass
|
pass
|
||||||
output_path = str(export_dir / f"{prefix}{sep}{next_ver}.docx")
|
output_path = str(export_dir / f"{prefix}-v{next_ver}.docx")
|
||||||
|
|
||||||
# Persist through the storage layer (INV-STG1). Under the filesystem
|
# Persist through the storage layer (INV-STG1). Under the filesystem
|
||||||
# backend the bytes land at output_path exactly as before; a caller-
|
# backend the bytes land at output_path exactly as before; a caller-
|
||||||
|
|||||||
@@ -259,25 +259,13 @@ async def _extract_header(protocol_text: str, case_id: UUID) -> dict:
|
|||||||
except ValueError:
|
except ValueError:
|
||||||
logger.info("protocol header: unparseable hearing_date %r", hearing_date)
|
logger.info("protocol header: unparseable hearing_date %r", hearing_date)
|
||||||
|
|
||||||
# Attendees → cases.hearing_attendees (#226). Unlike hearing_date there is no
|
|
||||||
# chair-entry path to protect, and re-running to point at the correct ערר
|
|
||||||
# protocol (#223) must refresh who appeared — so write whenever the operative
|
|
||||||
# protocol yielded any names, but never clobber good data with an empty
|
|
||||||
# extraction (all-empty feed → leave the prior snapshot intact).
|
|
||||||
attendees = {
|
|
||||||
"panel_members": feed.get("panel_members") or [],
|
|
||||||
"appellants_present": feed.get("appellants_present") or [],
|
|
||||||
"respondents_present": feed.get("respondents_present") or [],
|
|
||||||
}
|
|
||||||
if any(attendees.values()):
|
|
||||||
await db.update_case(case_id, hearing_attendees=attendees)
|
|
||||||
applied["hearing_attendees"] = True
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
"status": "ok",
|
"status": "ok",
|
||||||
"feed": {
|
"feed": {
|
||||||
"hearing_date": hearing_date,
|
"hearing_date": hearing_date,
|
||||||
**attendees,
|
"panel_members": feed.get("panel_members") or [],
|
||||||
|
"appellants_present": feed.get("appellants_present") or [],
|
||||||
|
"respondents_present": feed.get("respondents_present") or [],
|
||||||
},
|
},
|
||||||
"applied_to_case": applied,
|
"applied_to_case": applied,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -716,7 +716,7 @@ async def write_interim_draft(case_number: str, instructions: str = "") -> str:
|
|||||||
async def export_interim_draft(case_number: str, output_path: str = "") -> str:
|
async def export_interim_draft(case_number: str, output_path: str = "") -> str:
|
||||||
"""ייצוא טיוטת ביניים ל-DOCX — אותו עיצוב של טיוטה רגילה (David, RTL,
|
"""ייצוא טיוטת ביניים ל-DOCX — אותו עיצוב של טיוטה רגילה (David, RTL,
|
||||||
bookmarks), אבל בסדר חדש: רקע → תכניות+היתרים → טענות → הליכים, ללא
|
bookmarks), אבל בסדר חדש: רקע → תכניות+היתרים → טענות → הליכים, ללא
|
||||||
דיון/סיכום/חתימות. שם הקובץ: טיוטה-טענות_הצדדים_{N}.docx.
|
דיון/סיכום/חתימות. שם הקובץ: טיוטת-ביניים-v{N}.docx.
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
case_number: מספר תיק הערר
|
case_number: מספר תיק הערר
|
||||||
|
|||||||
@@ -287,6 +287,7 @@ description: This skill should be used when writing legal decisions (החלטו
|
|||||||
|
|
||||||
**ערר היטל השבחה — הכרעה מפוצלת (שמאי מייעץ):**
|
**ערר היטל השבחה — הכרעה מפוצלת (שמאי מייעץ):**
|
||||||
תת-מסלול חוזר: הוועדה מאשרת את עצם החבות אך אינה קובעת את גובה ההיטל — ממנה שמאי מייעץ. פתיחה: זהה למסלול הכללי — "עניינו של ערר זה בדרישת תשלום היטל השבחה...". ללא סיפור תכנוני רחב. דיון — שלב משפטי: הכרעה בשאלת עצם החבות. ניתוח הטענה המרכזית (בד"כ "זכות מוקנית") מול ההקלה שהתבקשה. ציטוטי פסיקה inline — הפניה להחלטות ועדת ערר קודמות ללא בלוק ציטוט מלא. ביטויי מפתח: "אנו סבורים כי...", "בניגוד לעמדת העורר...", "לא ניתן לטעון כי...". מעבר לשלב השמאי — 3 ביטויי גישור: (א) "בכל הנוגע לטענות לגבי מקדמים... וכל טענה בעלת אופי שמאי **ניתן יהיה לעלות בפני השמאי המייעץ**." (ב) "על כן, לאור האמור **אנו ממנים שמאי מייעץ** אשר יערוך שומה להערכת ההשבחה במקרקעין כתוצאה מאישור ההקלה..." (ג) "השמאי המייעץ ינהל את הדיון **בהתאם לתקנות התכנון והבניה (סדרי דין בבקשה להכרעה לפני שמאי מכריע או שמאי מייעץ), התשס"ט-2008**." — נוסחה קבועה. הוראות המשך: "לאחר קבלת השומה המייעצת יהיו רשאים הצדדים להגיש את השגותיהם בתוך 30 יום לוועדת הערר ולאחר מכן תתקבל החלטה באשר לאופן קידום ההליך." סיום: **ללא** כותרת "סיכום" / "סוף דבר" — זורם ישירות מהוראות המינוי לחתימה "ניתנה פה אחד היום...". הוצאות: לא מוזכרות (ההליך טרם הסתיים). ראה: נווה יעקב 8070/25.
|
תת-מסלול חוזר: הוועדה מאשרת את עצם החבות אך אינה קובעת את גובה ההיטל — ממנה שמאי מייעץ. פתיחה: זהה למסלול הכללי — "עניינו של ערר זה בדרישת תשלום היטל השבחה...". ללא סיפור תכנוני רחב. דיון — שלב משפטי: הכרעה בשאלת עצם החבות. ניתוח הטענה המרכזית (בד"כ "זכות מוקנית") מול ההקלה שהתבקשה. ציטוטי פסיקה inline — הפניה להחלטות ועדת ערר קודמות ללא בלוק ציטוט מלא. ביטויי מפתח: "אנו סבורים כי...", "בניגוד לעמדת העורר...", "לא ניתן לטעון כי...". מעבר לשלב השמאי — 3 ביטויי גישור: (א) "בכל הנוגע לטענות לגבי מקדמים... וכל טענה בעלת אופי שמאי **ניתן יהיה לעלות בפני השמאי המייעץ**." (ב) "על כן, לאור האמור **אנו ממנים שמאי מייעץ** אשר יערוך שומה להערכת ההשבחה במקרקעין כתוצאה מאישור ההקלה..." (ג) "השמאי המייעץ ינהל את הדיון **בהתאם לתקנות התכנון והבניה (סדרי דין בבקשה להכרעה לפני שמאי מכריע או שמאי מייעץ), התשס"ט-2008**." — נוסחה קבועה. הוראות המשך: "לאחר קבלת השומה המייעצת יהיו רשאים הצדדים להגיש את השגותיהם בתוך 30 יום לוועדת הערר ולאחר מכן תתקבל החלטה באשר לאופן קידום ההליך." סיום: **ללא** כותרת "סיכום" / "סוף דבר" — זורם ישירות מהוראות המינוי לחתימה "ניתנה פה אחד היום...". הוצאות: לא מוזכרות (ההליך טרם הסתיים). ראה: נווה יעקב 8070/25.
|
||||||
|
*הכרעות-מהות בתת-מסלול זה (מחיר-למשתכן / שומה סמוכה — 8125-09-24, ראה `docs/legal-decision-lessons.md` #47–#50):* (א) "הסבת שטחים" ממחיר-למשתכן לשוק-חופשי בעקבות הקלת תוספת יח"ד = **השבחה תכנונית בת-חיוב** — להכריע בחיוב, לא לגדֵר כשאלה פתוחה או להטיל ספק מכוח קשר-סיבתי (בית הכרם/פמיני). (ב) שומה מכרעת חלוטה סמוכה = **משכנעת, לא מחייבת**; שומה מנומקת רשאית לסטות ("לא נוכל להיאחז בשומה מכרעת אחרת רק מכיוון והיא קיימת") — לא להעמיס דוקטרינת שוויון לטובת העוררת. (ג) שמאי מכריע פרש → מינוי **שמאי מייעץ חדש** (סמכות אשקלוני/גנדליס).
|
||||||
|
|
||||||
**ערר היטל השבחה — מסגרת תלת-שכבתית לניתוח "תכנית צל":**
|
**ערר היטל השבחה — מסגרת תלת-שכבתית לניתוח "תכנית צל":**
|
||||||
כשעורר טוען ש"תכנית צל" מאושרת הופכת זכויות להקלה לזכויות מוקנות, הניתוח מתבצע בשלוש שכבות נפרדות:
|
כשעורר טוען ש"תכנית צל" מאושרת הופכת זכויות להקלה לזכויות מוקנות, הניתוח מתבצע בשלוש שכבות נפרדות:
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ import { DraftsPanel } from "@/components/cases/drafts-panel";
|
|||||||
import { DecisionBlocksPanel } from "@/components/cases/decision-blocks-panel";
|
import { DecisionBlocksPanel } from "@/components/cases/decision-blocks-panel";
|
||||||
import { LegalArgumentsPanel } from "@/components/cases/legal-arguments-panel";
|
import { LegalArgumentsPanel } from "@/components/cases/legal-arguments-panel";
|
||||||
import { PositionsPanel } from "@/components/cases/positions-panel";
|
import { PositionsPanel } from "@/components/cases/positions-panel";
|
||||||
import { HearingChangesPanel } from "@/components/cases/hearing-changes-panel";
|
|
||||||
import { CitationVerificationPanel } from "@/components/compose/citation-verification-panel";
|
import { CitationVerificationPanel } from "@/components/compose/citation-verification-panel";
|
||||||
import { AgentActivityFeed } from "@/components/cases/agent-activity-feed";
|
import { AgentActivityFeed } from "@/components/cases/agent-activity-feed";
|
||||||
import { AgentActivityPreview } from "@/components/cases/agent-activity-preview";
|
import { AgentActivityPreview } from "@/components/cases/agent-activity-preview";
|
||||||
@@ -157,28 +156,11 @@ export default function CaseDetailPage({
|
|||||||
issues, with the aggregated by-party arguments collapsible below
|
issues, with the aggregated by-party arguments collapsible below
|
||||||
(merged from the deleted /compose editor, mockup 18f). */}
|
(merged from the deleted /compose editor, mockup 18f). */}
|
||||||
<TabsContent value="arguments" className="mt-0 space-y-4">
|
<TabsContent value="arguments" className="mt-0 space-y-4">
|
||||||
{/* עמדות וטענות — collapsed by default (chair preference #226),
|
<Card className="bg-surface border-rule shadow-sm">
|
||||||
mirroring the two accordions below. */}
|
<CardContent className="px-6 py-5">
|
||||||
<Accordion type="single" collapsible>
|
|
||||||
<AccordionItem
|
|
||||||
value="positions"
|
|
||||||
className="overflow-hidden rounded-xl border border-rule bg-surface shadow-sm"
|
|
||||||
>
|
|
||||||
<AccordionTrigger className="px-6 py-4 hover:no-underline">
|
|
||||||
<span className="flex flex-1 flex-col items-start">
|
|
||||||
<span className="text-navy text-[0.95rem] font-bold">
|
|
||||||
עמדות וטענות
|
|
||||||
</span>
|
|
||||||
<span className="text-ink-muted text-[0.78rem]">
|
|
||||||
סוגיות-המחלוקת ועמדות הצדדים · עורך עמדת-היו״ר מזין את בלוק י׳
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</AccordionTrigger>
|
|
||||||
<AccordionContent className="px-6 pb-5 pt-0">
|
|
||||||
<PositionsPanel caseNumber={caseNumber} />
|
<PositionsPanel caseNumber={caseNumber} />
|
||||||
</AccordionContent>
|
</CardContent>
|
||||||
</AccordionItem>
|
</Card>
|
||||||
</Accordion>
|
|
||||||
<Accordion type="single" collapsible>
|
<Accordion type="single" collapsible>
|
||||||
<AccordionItem
|
<AccordionItem
|
||||||
value="byparty"
|
value="byparty"
|
||||||
@@ -199,30 +181,6 @@ export default function CaseDetailPage({
|
|||||||
</AccordionContent>
|
</AccordionContent>
|
||||||
</AccordionItem>
|
</AccordionItem>
|
||||||
</Accordion>
|
</Accordion>
|
||||||
{/* מה קרה בדיון — comparative analysis of the hearing protocol vs.
|
|
||||||
the written pleadings (#226). Sits below the aggregated arguments
|
|
||||||
because it speaks to those same arguments in their oral gloss.
|
|
||||||
Collapsed by default, mirroring the "by-party" accordion above. */}
|
|
||||||
<Accordion type="single" collapsible>
|
|
||||||
<AccordionItem
|
|
||||||
value="hearing"
|
|
||||||
className="overflow-hidden rounded-xl border border-rule bg-surface shadow-sm"
|
|
||||||
>
|
|
||||||
<AccordionTrigger className="px-6 py-4 hover:no-underline">
|
|
||||||
<span className="flex flex-1 flex-col items-start">
|
|
||||||
<span className="text-navy text-[0.95rem] font-bold">
|
|
||||||
מה קרה בדיון
|
|
||||||
</span>
|
|
||||||
<span className="text-ink-muted text-[0.78rem]">
|
|
||||||
השוואת הטענות בכתב מול הדיון בעל-פה — מה התחזק ומה נטען לראשונה
|
|
||||||
</span>
|
|
||||||
</span>
|
|
||||||
</AccordionTrigger>
|
|
||||||
<AccordionContent className="px-6 pb-5 pt-0">
|
|
||||||
<HearingChangesPanel caseNumber={caseNumber} />
|
|
||||||
</AccordionContent>
|
|
||||||
</AccordionItem>
|
|
||||||
</Accordion>
|
|
||||||
</TabsContent>
|
</TabsContent>
|
||||||
|
|
||||||
{/* אימות פסיקה — per-argument supporting-precedent verify gate (#154),
|
{/* אימות פסיקה — per-argument supporting-precedent verify gate (#154),
|
||||||
|
|||||||
@@ -31,9 +31,7 @@ import {
|
|||||||
usePartyClaimsSummary,
|
usePartyClaimsSummary,
|
||||||
useGeneratePartyClaimsSummary,
|
useGeneratePartyClaimsSummary,
|
||||||
useGenerateInterimDraft,
|
useGenerateInterimDraft,
|
||||||
useGenerateStatus,
|
|
||||||
} from "@/lib/api/generate";
|
} from "@/lib/api/generate";
|
||||||
import { GenerateStatusChip } from "@/components/cases/generate-status-chip";
|
|
||||||
import {
|
import {
|
||||||
useCaseFeedback,
|
useCaseFeedback,
|
||||||
useCreateFeedback,
|
useCreateFeedback,
|
||||||
@@ -91,7 +89,7 @@ function formatDate(epoch: number): string {
|
|||||||
/**
|
/**
|
||||||
* Pick the newest export file whose name starts with `prefix`, preferring the
|
* Pick the newest export file whose name starts with `prefix`, preferring the
|
||||||
* highest v-number and falling back to the latest created_at. Used by the
|
* highest v-number and falling back to the latest created_at. Used by the
|
||||||
* "הפקת מסמכים" card to surface the most recent טיוטה-טענות_הצדדים_* file (#214).
|
* "הפקת מסמכים" card to surface the most recent טיוטת-ביניים-* file (#214).
|
||||||
*/
|
*/
|
||||||
function pickLatestVersioned(
|
function pickLatestVersioned(
|
||||||
files: ExportFile[] | undefined,
|
files: ExportFile[] | undefined,
|
||||||
@@ -100,10 +98,7 @@ function pickLatestVersioned(
|
|||||||
const matches = (files ?? []).filter((f) => f.filename.startsWith(prefix));
|
const matches = (files ?? []).filter((f) => f.filename.startsWith(prefix));
|
||||||
if (!matches.length) return null;
|
if (!matches.length) return null;
|
||||||
const withVer = matches.map((f) => {
|
const withVer = matches.map((f) => {
|
||||||
// Version is the trailing integer, after either "-v" (final) or "_"
|
const m = f.filename.match(/v(\d+)/);
|
||||||
// (interim: טיוטה-טענות_הצדדים_{N}). Anchor to the end so the "_" inside
|
|
||||||
// the interim prefix isn't mistaken for the version separator.
|
|
||||||
const m = f.filename.match(/[_v](\d+)(?:\.\w+)?$/);
|
|
||||||
return { ...f, version: m ? parseInt(m[1], 10) : null };
|
return { ...f, version: m ? parseInt(m[1], 10) : null };
|
||||||
});
|
});
|
||||||
withVer.sort((a, b) => {
|
withVer.sort((a, b) => {
|
||||||
@@ -138,9 +133,6 @@ export function DraftsPanel({
|
|||||||
const { data: summary } = usePartyClaimsSummary(caseNumber);
|
const { data: summary } = usePartyClaimsSummary(caseNumber);
|
||||||
const genSummary = useGeneratePartyClaimsSummary(caseNumber);
|
const genSummary = useGeneratePartyClaimsSummary(caseNumber);
|
||||||
const genInterim = useGenerateInterimDraft(caseNumber);
|
const genInterim = useGenerateInterimDraft(caseNumber);
|
||||||
// Server-derived background-run status (#227 ג) — survives navigation/reload.
|
|
||||||
const summaryStatus = useGenerateStatus(caseNumber, "party_claims_summary");
|
|
||||||
const interimStatus = useGenerateStatus(caseNumber, "interim_draft");
|
|
||||||
const qc = useQueryClient();
|
const qc = useQueryClient();
|
||||||
|
|
||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
@@ -175,8 +167,8 @@ export function DraftsPanel({
|
|||||||
|
|
||||||
// ── "הפקת מסמכים" derived state (#214) ──
|
// ── "הפקת מסמכים" derived state (#214) ──
|
||||||
// Latest interim ("party-claims") partial draft in the exports table — the poll
|
// Latest interim ("party-claims") partial draft in the exports table — the poll
|
||||||
// target for button 2. The CEO writes it as טיוטה-טענות_הצדדים_{N}.docx.
|
// target for button 2. The CEO writes it as טיוטת-ביניים-{case}-vN.docx.
|
||||||
const latestInterim = pickLatestVersioned(exports, "טיוטה-טענות_הצדדים_");
|
const latestInterim = pickLatestVersioned(exports, "טיוטת-ביניים-");
|
||||||
const summaryReady = Boolean(summary?.markdown);
|
const summaryReady = Boolean(summary?.markdown);
|
||||||
|
|
||||||
function handleGenerateSummary() {
|
function handleGenerateSummary() {
|
||||||
@@ -350,11 +342,6 @@ export function DraftsPanel({
|
|||||||
"הפק"
|
"הפק"
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<GenerateStatusChip
|
|
||||||
status={summaryStatus.data}
|
|
||||||
onRetry={handleGenerateSummary}
|
|
||||||
retrying={genSummary.isPending}
|
|
||||||
/>
|
|
||||||
{summaryReady && (
|
{summaryReady && (
|
||||||
<>
|
<>
|
||||||
<Button
|
<Button
|
||||||
@@ -423,11 +410,6 @@ export function DraftsPanel({
|
|||||||
"הפק"
|
"הפק"
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<GenerateStatusChip
|
|
||||||
status={interimStatus.data}
|
|
||||||
onRetry={handleGenerateInterim}
|
|
||||||
retrying={genInterim.isPending}
|
|
||||||
/>
|
|
||||||
{latestInterim && (
|
{latestInterim && (
|
||||||
<span className="text-[0.7rem] text-ink-muted">
|
<span className="text-[0.7rem] text-ink-muted">
|
||||||
{latestInterim.version
|
{latestInterim.version
|
||||||
|
|||||||
@@ -1,127 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useEffect, useState } from "react";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { CheckCircle2, Clock, Loader2, RotateCw, XCircle } from "lucide-react";
|
|
||||||
import type { GenerateStatus } from "@/lib/api/generate";
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Background-run status chip for the "הפקת מסמכים" generation actions (#227 ג).
|
|
||||||
*
|
|
||||||
* The chip is driven entirely by the server-derived {@link GenerateStatus} — it
|
|
||||||
* holds no run state of its own, so it renders correctly after the chair
|
|
||||||
* navigates away and back. The running timer is anchored to the server
|
|
||||||
* `started_at`, not a click-time counter, so the elapsed value is right on
|
|
||||||
* return too.
|
|
||||||
*/
|
|
||||||
|
|
||||||
function useElapsedSeconds(startedAt: string | null, active: boolean): number | null {
|
|
||||||
const [now, setNow] = useState(() => Date.now());
|
|
||||||
useEffect(() => {
|
|
||||||
if (!active) return;
|
|
||||||
const id = setInterval(() => setNow(Date.now()), 1_000);
|
|
||||||
return () => clearInterval(id);
|
|
||||||
}, [active]);
|
|
||||||
if (!startedAt) return null;
|
|
||||||
const start = Date.parse(startedAt);
|
|
||||||
if (Number.isNaN(start)) return null;
|
|
||||||
return Math.max(0, Math.floor((now - start) / 1000));
|
|
||||||
}
|
|
||||||
|
|
||||||
function fmtDuration(sec: number): string {
|
|
||||||
const m = Math.floor(sec / 60);
|
|
||||||
const s = sec % 60;
|
|
||||||
if (m >= 60) {
|
|
||||||
const h = Math.floor(m / 60);
|
|
||||||
return `${h}:${String(m % 60).padStart(2, "0")}:${String(s).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
return `${m}:${String(s).padStart(2, "0")}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function relativeTime(iso: string | null): string {
|
|
||||||
if (!iso) return "";
|
|
||||||
const t = Date.parse(iso);
|
|
||||||
if (Number.isNaN(t)) return "";
|
|
||||||
const sec = Math.max(0, Math.floor((Date.now() - t) / 1000));
|
|
||||||
if (sec < 60) return "הרגע";
|
|
||||||
const min = Math.floor(sec / 60);
|
|
||||||
if (min < 60) return `לפני ${min} דק׳`;
|
|
||||||
const hr = Math.floor(min / 60);
|
|
||||||
if (hr < 24) return `לפני ${hr} שע׳`;
|
|
||||||
return `לפני ${Math.floor(hr / 24)} ימים`;
|
|
||||||
}
|
|
||||||
|
|
||||||
const CHIP_BASE =
|
|
||||||
"inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-semibold whitespace-nowrap";
|
|
||||||
|
|
||||||
export function GenerateStatusChip({
|
|
||||||
status,
|
|
||||||
onRetry,
|
|
||||||
retrying,
|
|
||||||
}: {
|
|
||||||
status: GenerateStatus | undefined;
|
|
||||||
onRetry?: () => void;
|
|
||||||
retrying?: boolean;
|
|
||||||
}) {
|
|
||||||
const state = status?.state ?? "idle";
|
|
||||||
const elapsed = useElapsedSeconds(status?.started_at ?? null, state === "running");
|
|
||||||
|
|
||||||
if (!status || state === "idle") return null;
|
|
||||||
|
|
||||||
if (state === "queued") {
|
|
||||||
return (
|
|
||||||
<span className={`${CHIP_BASE} bg-rule-soft text-ink-soft border-rule`}>
|
|
||||||
<Clock className="size-3.5" aria-hidden />
|
|
||||||
בתור…
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state === "running") {
|
|
||||||
return (
|
|
||||||
<span className={`${CHIP_BASE} bg-info-bg text-info border-info/35`}>
|
|
||||||
<Loader2 className="size-3.5 animate-spin" aria-hidden />
|
|
||||||
רץ ברקע
|
|
||||||
{elapsed !== null && (
|
|
||||||
<span className="tabular-nums">· {fmtDuration(elapsed)}</span>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (state === "done") {
|
|
||||||
const rel = relativeTime(status.finished_at);
|
|
||||||
return (
|
|
||||||
<span className={`${CHIP_BASE} bg-success-bg text-success border-success/35`}>
|
|
||||||
<CheckCircle2 className="size-3.5" aria-hidden />
|
|
||||||
הושלם{rel && ` · ${rel}`}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
// failed
|
|
||||||
return (
|
|
||||||
<span className="inline-flex items-center gap-2">
|
|
||||||
<span className={`${CHIP_BASE} bg-danger-bg text-danger border-danger/35`}>
|
|
||||||
<XCircle className="size-3.5" aria-hidden />
|
|
||||||
{status.detail || "נכשל"}
|
|
||||||
</span>
|
|
||||||
{onRetry && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="sm"
|
|
||||||
className="h-7 px-2 text-gold-deep"
|
|
||||||
disabled={retrying}
|
|
||||||
onClick={onRetry}
|
|
||||||
>
|
|
||||||
{retrying ? (
|
|
||||||
<Loader2 className="size-3.5 animate-spin me-1" />
|
|
||||||
) : (
|
|
||||||
<RotateCw className="size-3.5 me-1" />
|
|
||||||
)}
|
|
||||||
נסה שוב
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</span>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,360 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useMemo, useState } from "react";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Skeleton } from "@/components/ui/skeleton";
|
|
||||||
import {
|
|
||||||
ArrowDown,
|
|
||||||
ArrowUp,
|
|
||||||
CalendarDays,
|
|
||||||
HelpCircle,
|
|
||||||
Link2,
|
|
||||||
Loader2,
|
|
||||||
Plus,
|
|
||||||
RotateCw,
|
|
||||||
Sparkles,
|
|
||||||
} from "lucide-react";
|
|
||||||
import { toast } from "sonner";
|
|
||||||
import {
|
|
||||||
CHANGE_LABELS_HE,
|
|
||||||
PROTOCOL_PARTY_LABELS_HE,
|
|
||||||
PROTOCOL_PARTY_ORDER,
|
|
||||||
useAnalyzeProtocol,
|
|
||||||
useProtocolAnalysis,
|
|
||||||
type ProtocolAnalysisRow,
|
|
||||||
type ProtocolChangeType,
|
|
||||||
type ProtocolPartyRole,
|
|
||||||
} from "@/lib/api/protocol-analysis";
|
|
||||||
|
|
||||||
const PARTY_MARK_TONE: Record<ProtocolPartyRole, string> = {
|
|
||||||
appellant: "bg-info",
|
|
||||||
respondent: "bg-gold-deep",
|
|
||||||
committee: "bg-success",
|
|
||||||
permit_applicant: "bg-warn",
|
|
||||||
unknown: "bg-ink-muted",
|
|
||||||
"": "bg-ink-muted",
|
|
||||||
};
|
|
||||||
|
|
||||||
const CHANGE_BADGE_TONE: Record<ProtocolChangeType, string> = {
|
|
||||||
strengthened: "bg-gold-wash text-gold-deep border-gold/40",
|
|
||||||
newly_raised: "bg-emerald-50 text-emerald-900 border-emerald-200",
|
|
||||||
dropped: "bg-rule-soft text-ink-soft border-rule",
|
|
||||||
};
|
|
||||||
|
|
||||||
const CHANGE_ACCENT: Record<ProtocolChangeType, string> = {
|
|
||||||
strengthened: "border-s-gold",
|
|
||||||
newly_raised: "border-s-emerald-500",
|
|
||||||
dropped: "border-s-rule",
|
|
||||||
};
|
|
||||||
|
|
||||||
function ChangeIcon({ type }: { type: ProtocolChangeType }) {
|
|
||||||
if (type === "strengthened") return <ArrowUp className="size-3.5" aria-hidden />;
|
|
||||||
if (type === "newly_raised") return <Plus className="size-3.5" aria-hidden />;
|
|
||||||
return <ArrowDown className="size-3.5" aria-hidden />;
|
|
||||||
}
|
|
||||||
|
|
||||||
type FilterKey = "all" | ProtocolChangeType;
|
|
||||||
|
|
||||||
function AttendeeColumn({
|
|
||||||
label,
|
|
||||||
dotTone,
|
|
||||||
names,
|
|
||||||
}: {
|
|
||||||
label: string;
|
|
||||||
dotTone: string;
|
|
||||||
names: string[];
|
|
||||||
}) {
|
|
||||||
if (!names.length) return null;
|
|
||||||
return (
|
|
||||||
<div className="min-w-[210px] flex-1">
|
|
||||||
<div className="text-gold-deep mb-1.5 flex items-center gap-1.5 text-[0.7rem] font-bold">
|
|
||||||
<span className={`size-1.5 flex-none rounded-full ${dotTone}`} aria-hidden />
|
|
||||||
{label}
|
|
||||||
</div>
|
|
||||||
<div className="text-ink-soft text-xs leading-relaxed">
|
|
||||||
{names.join(" · ")}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function DevelopmentCard({ row }: { row: ProtocolAnalysisRow }) {
|
|
||||||
return (
|
|
||||||
<div
|
|
||||||
className={`bg-surface border-rule overflow-hidden rounded-lg border border-s-4 shadow-sm ${CHANGE_ACCENT[row.change_type]}`}
|
|
||||||
>
|
|
||||||
<div className="space-y-2.5 px-4 py-3.5">
|
|
||||||
<div className="flex flex-wrap items-start gap-2.5">
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className={`${CHANGE_BADGE_TONE[row.change_type]} flex-none gap-1 text-[0.72rem] font-bold`}
|
|
||||||
>
|
|
||||||
<ChangeIcon type={row.change_type} />
|
|
||||||
{CHANGE_LABELS_HE[row.change_type]}
|
|
||||||
</Badge>
|
|
||||||
<span className="text-navy flex-1 text-sm font-bold leading-snug">
|
|
||||||
{row.argument_title}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{row.summary && (
|
|
||||||
<p className="text-ink-soft text-[0.82rem] leading-relaxed">
|
|
||||||
{row.summary}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{row.sharpened_question && (
|
|
||||||
<div className="bg-parchment border-rule-soft rounded-md border px-3 py-2">
|
|
||||||
<div className="text-gold-deep mb-1 flex items-center gap-1.5 text-[0.66rem] font-bold">
|
|
||||||
<HelpCircle className="size-3" aria-hidden />
|
|
||||||
השאלה שהתחדדה
|
|
||||||
</div>
|
|
||||||
<div className="text-ink text-xs leading-relaxed">
|
|
||||||
{row.sharpened_question}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{row.evidence_quote && (
|
|
||||||
<blockquote className="border-rule text-ink-muted border-s-[3px] px-3 text-xs italic leading-relaxed">
|
|
||||||
“{row.evidence_quote}”
|
|
||||||
<span className="text-ink-muted mt-1 block text-[0.68rem] not-italic font-semibold">
|
|
||||||
— מתוך פרוטוקול הדיון
|
|
||||||
</span>
|
|
||||||
</blockquote>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-center gap-2 pt-0.5">
|
|
||||||
{row.change_type === "newly_raised" ? (
|
|
||||||
<span className="text-emerald-800 inline-flex items-center gap-1.5 text-[0.72rem] font-semibold">
|
|
||||||
<Sparkles className="size-3.5" aria-hidden />
|
|
||||||
אין מקבילה בכתב — עלה לראשונה בדיון
|
|
||||||
</span>
|
|
||||||
) : row.argument_id ? (
|
|
||||||
<span className="text-ink-muted inline-flex items-center gap-1.5 text-[0.72rem] font-semibold">
|
|
||||||
<Link2 className="size-3.5" aria-hidden />
|
|
||||||
מבוסס על טיעון כתוב קיים
|
|
||||||
</span>
|
|
||||||
) : null}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
type HearingChangesPanelProps = {
|
|
||||||
caseNumber: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function HearingChangesPanel({ caseNumber }: HearingChangesPanelProps) {
|
|
||||||
const { data, isPending, isError, error } = useProtocolAnalysis(caseNumber);
|
|
||||||
const analyze = useAnalyzeProtocol(caseNumber);
|
|
||||||
const [filter, setFilter] = useState<FilterKey>("all");
|
|
||||||
|
|
||||||
const handleAnalyze = () => {
|
|
||||||
analyze.mutate(undefined, {
|
|
||||||
onSuccess: (res) => {
|
|
||||||
if (res.status === "queued") {
|
|
||||||
toast.success("נשלח למנתח המשפטי — הניתוח ירוץ ברקע; רענן בעוד כמה דקות.");
|
|
||||||
} else {
|
|
||||||
toast.warning(
|
|
||||||
`לא ניתן להריץ אוטומטית (${res.reason}). ניתן להריץ ידנית מ-Claude Code.`,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
},
|
|
||||||
onError: (e) => toast.error(`שגיאה: ${(e as Error).message}`),
|
|
||||||
});
|
|
||||||
};
|
|
||||||
|
|
||||||
const header = data?.header;
|
|
||||||
const counts = data?.by_change ?? {};
|
|
||||||
const strengthened = counts.strengthened ?? 0;
|
|
||||||
const newlyRaised = counts.newly_raised ?? 0;
|
|
||||||
const dropped = counts.dropped ?? 0;
|
|
||||||
|
|
||||||
const sections = useMemo(() => {
|
|
||||||
if (!data) return [];
|
|
||||||
return PROTOCOL_PARTY_ORDER.map((role) => {
|
|
||||||
const rows = (data.by_party[role] ?? []).filter(
|
|
||||||
(r) => filter === "all" || r.change_type === filter,
|
|
||||||
);
|
|
||||||
return { role, rows };
|
|
||||||
}).filter((s) => s.rows.length > 0);
|
|
||||||
}, [data, filter]);
|
|
||||||
|
|
||||||
const runButton = (
|
|
||||||
<Button
|
|
||||||
variant="outline"
|
|
||||||
size="sm"
|
|
||||||
disabled={analyze.isPending}
|
|
||||||
onClick={handleAnalyze}
|
|
||||||
>
|
|
||||||
{analyze.isPending ? (
|
|
||||||
<Loader2 className="me-1.5 size-3.5 animate-spin" />
|
|
||||||
) : (
|
|
||||||
<RotateCw className="me-1.5 size-3.5" />
|
|
||||||
)}
|
|
||||||
{data?.total ? "נתח מחדש" : "נתח את פרוטוקול הדיון"}
|
|
||||||
</Button>
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-4">
|
|
||||||
{isPending ? (
|
|
||||||
<div className="space-y-2">
|
|
||||||
<Skeleton className="h-20 w-full" />
|
|
||||||
<Skeleton className="h-24 w-full" />
|
|
||||||
</div>
|
|
||||||
) : isError ? (
|
|
||||||
<p className="text-danger text-sm">
|
|
||||||
שגיאה בטעינת ניתוח-הפרוטוקול: {(error as Error).message}
|
|
||||||
</p>
|
|
||||||
) : !data?.total ? (
|
|
||||||
<div className="bg-surface border-rule rounded-lg border border-dashed px-6 py-8 text-center">
|
|
||||||
<h3 className="text-navy text-sm font-bold">טרם נותח פרוטוקול</h3>
|
|
||||||
<p className="text-ink-muted mx-auto mt-1.5 max-w-md text-xs leading-relaxed">
|
|
||||||
כשיש בתיק פרוטוקול של ועדת-הערר וטיעונים מאוגדים, הניתוח מזהה מה
|
|
||||||
התחזק ומה נטען לראשונה בדיון. ההרצה נשלחת למנתח המשפטי ורצה ברקע.
|
|
||||||
</p>
|
|
||||||
<div className="mt-4 flex justify-center">{runButton}</div>
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<div className="flex justify-end">{runButton}</div>
|
|
||||||
{/* hearing header strip */}
|
|
||||||
{header && (
|
|
||||||
<div className="bg-parchment border-rule rounded-lg border px-5 py-4 shadow-sm">
|
|
||||||
<div className="flex flex-wrap items-center gap-3">
|
|
||||||
<span className="bg-gold-wash border-rule flex size-9 flex-none items-center justify-center rounded-lg border">
|
|
||||||
<CalendarDays className="text-gold-deep size-5" aria-hidden />
|
|
||||||
</span>
|
|
||||||
<div className="flex-1">
|
|
||||||
<div className="text-navy text-[0.95rem] font-bold">
|
|
||||||
{header.protocol_title || "פרוטוקול דיון"}
|
|
||||||
</div>
|
|
||||||
<div className="text-ink-muted mt-0.5 text-xs">
|
|
||||||
{header.hearing_date
|
|
||||||
? `תאריך דיון: ${header.hearing_date}`
|
|
||||||
: "תאריך דיון לא זוהה"}
|
|
||||||
{header.panel_members.length > 0 &&
|
|
||||||
` · מותב: ${header.panel_members.join(", ")}`}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
<Badge
|
|
||||||
variant="outline"
|
|
||||||
className="bg-info-bg text-info border-info/30 flex-none rounded-full text-[0.72rem] font-semibold"
|
|
||||||
>
|
|
||||||
פרוטוקול ועדת-הערר
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
{(header.appellants_present.length > 0 ||
|
|
||||||
header.respondents_present.length > 0) && (
|
|
||||||
<div className="border-rule-soft mt-3 flex flex-wrap gap-6 border-t pt-3">
|
|
||||||
<AttendeeColumn
|
|
||||||
label="נכחו מטעם העוררים"
|
|
||||||
dotTone="bg-info"
|
|
||||||
names={header.appellants_present}
|
|
||||||
/>
|
|
||||||
<AttendeeColumn
|
|
||||||
label="נכחו מטעם המשיבים"
|
|
||||||
dotTone="bg-gold-deep"
|
|
||||||
names={header.respondents_present}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{/* filter pills */}
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<FilterPill
|
|
||||||
active={filter === "all"}
|
|
||||||
onClick={() => setFilter("all")}
|
|
||||||
label="הכל"
|
|
||||||
count={data.total}
|
|
||||||
/>
|
|
||||||
{strengthened > 0 && (
|
|
||||||
<FilterPill
|
|
||||||
active={filter === "strengthened"}
|
|
||||||
onClick={() => setFilter("strengthened")}
|
|
||||||
label="התחזקו"
|
|
||||||
count={strengthened}
|
|
||||||
icon={<ArrowUp className="size-3.5" aria-hidden />}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{newlyRaised > 0 && (
|
|
||||||
<FilterPill
|
|
||||||
active={filter === "newly_raised"}
|
|
||||||
onClick={() => setFilter("newly_raised")}
|
|
||||||
label="נטענו לראשונה"
|
|
||||||
count={newlyRaised}
|
|
||||||
icon={<Plus className="size-3.5" aria-hidden />}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
{dropped > 0 && (
|
|
||||||
<FilterPill
|
|
||||||
active={filter === "dropped"}
|
|
||||||
onClick={() => setFilter("dropped")}
|
|
||||||
label="נזנחו"
|
|
||||||
count={dropped}
|
|
||||||
icon={<ArrowDown className="size-3.5" aria-hidden />}
|
|
||||||
/>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
|
|
||||||
{/* per-party sections */}
|
|
||||||
{sections.map(({ role, rows }) => (
|
|
||||||
<div key={role || "unassigned"} className="space-y-2.5">
|
|
||||||
<div className="flex items-center gap-2.5">
|
|
||||||
<span
|
|
||||||
className={`h-5 w-1.5 flex-none rounded ${PARTY_MARK_TONE[role]}`}
|
|
||||||
aria-hidden
|
|
||||||
/>
|
|
||||||
<span className="text-navy text-[0.95rem] font-bold">
|
|
||||||
{PROTOCOL_PARTY_LABELS_HE[role]}
|
|
||||||
</span>
|
|
||||||
<span className="text-ink-muted text-xs">{rows.length}</span>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-2.5">
|
|
||||||
{rows.map((r) => (
|
|
||||||
<DevelopmentCard key={r.id} row={r} />
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
function FilterPill({
|
|
||||||
active,
|
|
||||||
onClick,
|
|
||||||
label,
|
|
||||||
count,
|
|
||||||
icon,
|
|
||||||
}: {
|
|
||||||
active: boolean;
|
|
||||||
onClick: () => void;
|
|
||||||
label: string;
|
|
||||||
count: number;
|
|
||||||
icon?: React.ReactNode;
|
|
||||||
}) {
|
|
||||||
return (
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
onClick={onClick}
|
|
||||||
className={`inline-flex items-center gap-1.5 rounded-full border px-3.5 py-1.5 text-xs font-semibold transition-colors ${
|
|
||||||
active
|
|
||||||
? "bg-navy border-navy text-white"
|
|
||||||
: "bg-surface border-rule text-ink-soft hover:bg-parchment"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{icon}
|
|
||||||
{label}
|
|
||||||
<span className="font-bold">{count}</span>
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -8,6 +8,10 @@ import { SubsectionCard } from "@/components/compose/subsection-card";
|
|||||||
import { PrecedentsSection } from "@/components/compose/precedents-section";
|
import { PrecedentsSection } from "@/components/compose/precedents-section";
|
||||||
import { Markdown } from "@/components/ui/markdown";
|
import { Markdown } from "@/components/ui/markdown";
|
||||||
import { useCase } from "@/lib/api/cases";
|
import { useCase } from "@/lib/api/cases";
|
||||||
|
import {
|
||||||
|
useCaseLearningStatus,
|
||||||
|
type CaseLearningStatus,
|
||||||
|
} from "@/lib/api/learning";
|
||||||
import { useResearchAnalysis } from "@/lib/api/research";
|
import { useResearchAnalysis } from "@/lib/api/research";
|
||||||
import { useCasePrecedents } from "@/lib/api/precedents";
|
import { useCasePrecedents } from "@/lib/api/precedents";
|
||||||
|
|
||||||
@@ -20,6 +24,45 @@ import { useCasePrecedents } from "@/lib/api/precedents";
|
|||||||
* verification moved to their own top-level tabs; /compose was deleted.
|
* verification moved to their own top-level tabs; /compose was deleted.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
// ── Staged-pipeline indicator text — derived from the live learning-status,
|
||||||
|
// same source as the drafts-panel LearningStatusBadges. ──────────────────────
|
||||||
|
function voiceLearningText(s?: CaseLearningStatus): string {
|
||||||
|
if (!s?.final_uploaded) return "ממתין להעלאת הסופי";
|
||||||
|
const v = s.voice_learning;
|
||||||
|
if (v.outcome === "succeeded") {
|
||||||
|
const bits = [`${v.lessons_count} לקחים הופקו`];
|
||||||
|
if (v.lessons_proposed > 0) bits.push(`${v.lessons_proposed} הוצעו לאישור`);
|
||||||
|
return `✓ הושלם · ${bits.join(" · ")}`;
|
||||||
|
}
|
||||||
|
if (v.outcome === "failed") return v.error ? `✗ נכשל — ${v.error}` : "✗ נכשל";
|
||||||
|
return "ממתין להרצה";
|
||||||
|
}
|
||||||
|
|
||||||
|
function halachaExtractionText(s?: CaseLearningStatus): string {
|
||||||
|
if (!s?.final_uploaded) return "ממתין להעלאת הסופי";
|
||||||
|
const h = s.halacha_extraction;
|
||||||
|
if (!h.enrolled_in_corpus)
|
||||||
|
return h.not_enrolled_reason ?? "לא נכנס לקורפוס-הפסיקה";
|
||||||
|
switch (h.status) {
|
||||||
|
case "completed":
|
||||||
|
return `✓ הושלם · חולצו ${h.halachot_count} · ${h.approved} אושרו · ${h.rejected} נדחו`;
|
||||||
|
case "processing":
|
||||||
|
return "רץ עכשיו…";
|
||||||
|
case "pending":
|
||||||
|
case "busy":
|
||||||
|
return "בתור";
|
||||||
|
case "partial":
|
||||||
|
return `חלקי · חולצו ${h.halachot_count}`;
|
||||||
|
case "failed":
|
||||||
|
case "extraction_failed":
|
||||||
|
return "✗ נכשל";
|
||||||
|
case "no_chunks":
|
||||||
|
return "אין טקסט לחילוץ";
|
||||||
|
default:
|
||||||
|
return "ממתין להרצה";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
function ProseSection({ title, content }: { title: string; content?: string }) {
|
function ProseSection({ title, content }: { title: string; content?: string }) {
|
||||||
if (!content?.trim()) return null;
|
if (!content?.trim()) return null;
|
||||||
return (
|
return (
|
||||||
@@ -32,9 +75,7 @@ function ProseSection({ title, content }: { title: string; content?: string }) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── "ייצוא ועדכון הניתוח" rail card — round-trips the analysis-and-research.md
|
// ── "השלמה והעברה" rail card — DOCX export, analysis upload/download (real) ──
|
||||||
// research analysis: export DOCX, upload an updated version, download the raw MD.
|
|
||||||
// (Post-final learning status lives on the drafts tab, not here — #226.) ──────
|
|
||||||
function FinishRail({
|
function FinishRail({
|
||||||
caseNumber,
|
caseNumber,
|
||||||
hasAnalysis,
|
hasAnalysis,
|
||||||
@@ -47,6 +88,7 @@ function FinishRail({
|
|||||||
const fileRef = useRef<HTMLInputElement>(null);
|
const fileRef = useRef<HTMLInputElement>(null);
|
||||||
const [uploading, setUploading] = useState(false);
|
const [uploading, setUploading] = useState(false);
|
||||||
const [uploadMsg, setUploadMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
const [uploadMsg, setUploadMsg] = useState<{ ok: boolean; text: string } | null>(null);
|
||||||
|
const learning = useCaseLearningStatus(caseNumber);
|
||||||
|
|
||||||
async function handleUpload(file: File) {
|
async function handleUpload(file: File) {
|
||||||
setUploading(true);
|
setUploading(true);
|
||||||
@@ -77,12 +119,9 @@ function FinishRail({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Card className="bg-surface border-rule shadow-sm h-full">
|
<Card className="bg-surface border-rule shadow-sm">
|
||||||
<CardContent className="px-4 py-4">
|
<CardContent className="px-4 py-4">
|
||||||
<h3 className="text-navy text-[0.9rem] font-semibold mb-1">ייצוא ועדכון הניתוח</h3>
|
<h3 className="text-navy text-[0.9rem] font-semibold mb-3">השלמה והעברה</h3>
|
||||||
<p className="text-[0.72rem] text-ink-muted mb-3">
|
|
||||||
פעולות על קובץ ניתוח-המחקר (analysis-and-research.md).
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<input
|
<input
|
||||||
ref={fileRef}
|
ref={fileRef}
|
||||||
@@ -137,6 +176,16 @@ function FinishRail({
|
|||||||
{uploadMsg.text}
|
{uploadMsg.text}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{/* stage indicators — informational pointers, not actions */}
|
||||||
|
<div className="mt-3 space-y-0">
|
||||||
|
<div className="text-[0.78rem] text-ink-muted pt-2 border-t border-rule-soft">
|
||||||
|
<b className="text-navy">הרץ למידת-קול</b> — {voiceLearningText(learning.data)}
|
||||||
|
</div>
|
||||||
|
<div className="text-[0.78rem] text-ink-muted pt-2 mt-2 border-t border-rule-soft">
|
||||||
|
<b className="text-navy">הרץ אימות-הלכות</b> — {halachaExtractionText(learning.data)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
);
|
);
|
||||||
@@ -165,6 +214,10 @@ export function PositionsPanel({ caseNumber }: { caseNumber: string }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
<p className="text-ink-muted text-[0.78rem]">
|
||||||
|
סוגיות-המחלוקת ועמדות הצדדים. עורך עמדת-היו״ר נשמר אוטומטית ומזין את בלוק י׳ (דיון והכרעה).
|
||||||
|
</p>
|
||||||
|
|
||||||
{analysis.isPending ? (
|
{analysis.isPending ? (
|
||||||
<Card className="bg-surface border-rule shadow-sm">
|
<Card className="bg-surface border-rule shadow-sm">
|
||||||
<CardContent className="px-6 py-5 space-y-3">
|
<CardContent className="px-6 py-5 space-y-3">
|
||||||
@@ -269,10 +322,9 @@ export function PositionsPanel({ caseNumber }: { caseNumber: string }) {
|
|||||||
</div>
|
</div>
|
||||||
) : null}
|
) : null}
|
||||||
|
|
||||||
{/* case-level פסיקה מצורפת + analysis export/update (INV-IA3: not removed).
|
{/* case-level פסיקה מצורפת + finish/export gates (INV-IA3: not removed) */}
|
||||||
items-stretch keeps both cards the same height (#226). */}
|
<div className="grid gap-4 lg:grid-cols-2 items-start pt-2">
|
||||||
<div className="grid gap-4 lg:grid-cols-2 items-stretch pt-2">
|
<Card className="bg-surface border-rule shadow-sm">
|
||||||
<Card className="bg-surface border-rule shadow-sm h-full">
|
|
||||||
<CardContent className="px-5 py-4">
|
<CardContent className="px-5 py-4">
|
||||||
<h3 className="text-navy text-[0.9rem] font-semibold mb-1">פסיקה מצורפת</h3>
|
<h3 className="text-navy text-[0.9rem] font-semibold mb-1">פסיקה מצורפת</h3>
|
||||||
<p className="text-[0.72rem] text-ink-muted mb-3">
|
<p className="text-[0.72rem] text-ink-muted mb-3">
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
* Generation runs on the host (claude_session → claude -p), NOT in the container,
|
* Generation runs on the host (claude_session → claude -p), NOT in the container,
|
||||||
* so the trigger endpoints return 202-accepted and the UI POLLS for completion:
|
* so the trigger endpoints return 202-accepted and the UI POLLS for completion:
|
||||||
* • summary → GET /api/cases/{n}/research/party-claims-summary (200 = ready)
|
* • summary → GET /api/cases/{n}/research/party-claims-summary (200 = ready)
|
||||||
* • interim draft → the exports list grows a "טיוטה-טענות_הצדדים_{N}.docx" file
|
* • interim draft → the exports list grows a "טיוטת-ביניים-{n}-vN.docx" file
|
||||||
* (polled via useExports — see exports.ts).
|
* (polled via useExports — see exports.ts).
|
||||||
*
|
*
|
||||||
* The full-decision export ("הפק טיוטת החלטה מלאה") is NOT here — it reuses the
|
* The full-decision export ("הפק טיוטת החלטה מלאה") is NOT here — it reuses the
|
||||||
@@ -29,58 +29,12 @@ export type GenerateTriggerResult = {
|
|||||||
error?: string;
|
error?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
/** The two host-side background generation actions (poll target of the status chip). */
|
|
||||||
export type GenerateAction = "party_claims_summary" | "interim_draft";
|
|
||||||
|
|
||||||
export const generateKeys = {
|
export const generateKeys = {
|
||||||
all: ["generate"] as const,
|
all: ["generate"] as const,
|
||||||
partyClaimsSummary: (caseNumber: string) =>
|
partyClaimsSummary: (caseNumber: string) =>
|
||||||
[...generateKeys.all, "party-claims-summary", caseNumber] as const,
|
[...generateKeys.all, "party-claims-summary", caseNumber] as const,
|
||||||
status: (caseNumber: string, action: GenerateAction) =>
|
|
||||||
[...generateKeys.all, "status", action, caseNumber] as const,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
|
||||||
* Server-derived background-run status (#227 ג). Reconstructed on the backend
|
|
||||||
* from the CEO child issue + its heartbeat_run + the output artifact — so it is
|
|
||||||
* correct after navigating away and back; it never depends on the browser having
|
|
||||||
* stayed on the page. `started_at`/`finished_at` are server ISO-8601 UTC stamps,
|
|
||||||
* so the client renders a correct elapsed time on return.
|
|
||||||
*/
|
|
||||||
export type GenerateState = "idle" | "queued" | "running" | "done" | "failed";
|
|
||||||
|
|
||||||
export type GenerateStatus = {
|
|
||||||
case_number: string;
|
|
||||||
action: GenerateAction;
|
|
||||||
state: GenerateState;
|
|
||||||
started_at: string | null;
|
|
||||||
finished_at: string | null;
|
|
||||||
output_ready: boolean;
|
|
||||||
detail: string;
|
|
||||||
issue_id: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useGenerateStatus(
|
|
||||||
caseNumber: string | undefined,
|
|
||||||
action: GenerateAction,
|
|
||||||
) {
|
|
||||||
return useQuery<GenerateStatus>({
|
|
||||||
queryKey: generateKeys.status(caseNumber ?? "", action),
|
|
||||||
queryFn: ({ signal }) =>
|
|
||||||
apiRequest<GenerateStatus>(
|
|
||||||
`/api/cases/${caseNumber}/generate/${action}/status`,
|
|
||||||
{ signal },
|
|
||||||
),
|
|
||||||
enabled: Boolean(caseNumber),
|
|
||||||
// Poll only while a run is in flight; a terminal state stops the interval.
|
|
||||||
refetchInterval: (query) => {
|
|
||||||
const s = query.state.data?.state;
|
|
||||||
return s === "running" || s === "queued" ? 5_000 : false;
|
|
||||||
},
|
|
||||||
staleTime: 2_000,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/* ── Read: party-claims executive summary (poll target for button 1) ──
|
/* ── Read: party-claims executive summary (poll target for button 1) ──
|
||||||
404 (not generated yet) is a normal "not ready" state, not an error — we
|
404 (not generated yet) is a normal "not ready" state, not an error — we
|
||||||
coerce it to null so the panel renders the empty/idle state cleanly. */
|
coerce it to null so the panel renders the empty/idle state cleanly. */
|
||||||
@@ -116,33 +70,23 @@ export function useGeneratePartyClaimsSummary(caseNumber: string) {
|
|||||||
{ method: "POST" },
|
{ method: "POST" },
|
||||||
),
|
),
|
||||||
onSuccess: () => {
|
onSuccess: () => {
|
||||||
// Start polling fresh — the file will appear after the host run completes,
|
// Start polling fresh — the file will appear after the host run completes.
|
||||||
// and the status chip should pick up the new queued/running run.
|
|
||||||
qc.invalidateQueries({
|
qc.invalidateQueries({
|
||||||
queryKey: generateKeys.partyClaimsSummary(caseNumber),
|
queryKey: generateKeys.partyClaimsSummary(caseNumber),
|
||||||
});
|
});
|
||||||
qc.invalidateQueries({
|
|
||||||
queryKey: generateKeys.status(caseNumber, "party_claims_summary"),
|
|
||||||
});
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/* ── Trigger: interim ("party-claims") partial draft (button 2) ── */
|
/* ── Trigger: interim ("party-claims") partial draft (button 2) ── */
|
||||||
export function useGenerateInterimDraft(caseNumber: string) {
|
export function useGenerateInterimDraft(caseNumber: string) {
|
||||||
const qc = useQueryClient();
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: () =>
|
mutationFn: () =>
|
||||||
apiRequest<GenerateTriggerResult>(
|
apiRequest<GenerateTriggerResult>(
|
||||||
`/api/cases/${caseNumber}/generate/interim-draft`,
|
`/api/cases/${caseNumber}/generate/interim-draft`,
|
||||||
{ method: "POST" },
|
{ method: "POST" },
|
||||||
),
|
),
|
||||||
// The result lands in the exports list (טיוטה-טענות_הצדדים_*.docx, polled by
|
// The result lands in the exports list (טיוטת-ביניים-*.docx); useExports
|
||||||
// useExports); re-arm the status chip so it shows the new run immediately.
|
// already polls on a 5s interval, so no extra invalidation is needed here.
|
||||||
onSuccess: () => {
|
|
||||||
qc.invalidateQueries({
|
|
||||||
queryKey: generateKeys.status(caseNumber, "interim_draft"),
|
|
||||||
});
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,134 +0,0 @@
|
|||||||
/**
|
|
||||||
* Protocol comparative analysis — the "מה קרה בדיון" panel (#226).
|
|
||||||
*
|
|
||||||
* `analyze_protocol` compares the ערר hearing protocol against the written
|
|
||||||
* pleadings and records, per argument, whether it was strengthened, newly
|
|
||||||
* raised, or dropped at the hearing — plus the sharpened legal question and a
|
|
||||||
* verbatim evidence quote. This module exposes the read + trigger endpoints.
|
|
||||||
*/
|
|
||||||
|
|
||||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
|
|
||||||
import { apiRequest } from "./client";
|
|
||||||
import type { LegalArgumentParty } from "./legal-arguments";
|
|
||||||
|
|
||||||
export type ProtocolChangeType = "strengthened" | "newly_raised" | "dropped";
|
|
||||||
|
|
||||||
/** Empty string = an unassigned party_role on a verdict row. */
|
|
||||||
export type ProtocolPartyRole = LegalArgumentParty | "";
|
|
||||||
|
|
||||||
export type ProtocolAnalysisRow = {
|
|
||||||
id: string;
|
|
||||||
case_id: string;
|
|
||||||
document_id: string;
|
|
||||||
party_role: ProtocolPartyRole;
|
|
||||||
change_type: ProtocolChangeType;
|
|
||||||
/** The pleaded argument this verdict matched (strengthened/dropped); null for newly_raised. */
|
|
||||||
argument_id: string | null;
|
|
||||||
argument_title: string;
|
|
||||||
summary: string;
|
|
||||||
sharpened_question: string;
|
|
||||||
evidence_quote: string;
|
|
||||||
page_number: number | null;
|
|
||||||
created_at?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ProtocolHeader = {
|
|
||||||
hearing_date: string | null;
|
|
||||||
protocol_title: string;
|
|
||||||
protocol_document_id: string;
|
|
||||||
panel_members: string[];
|
|
||||||
appellants_present: string[];
|
|
||||||
respondents_present: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ProtocolAnalysisResponse = {
|
|
||||||
case_number: string;
|
|
||||||
total: number;
|
|
||||||
header: ProtocolHeader;
|
|
||||||
by_change: Partial<Record<ProtocolChangeType, number>>;
|
|
||||||
by_party: Partial<Record<ProtocolPartyRole, ProtocolAnalysisRow[]>>;
|
|
||||||
analysis: ProtocolAnalysisRow[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export const protocolAnalysisKeys = {
|
|
||||||
all: ["protocol-analysis"] as const,
|
|
||||||
byCase: (caseNumber: string) =>
|
|
||||||
[...protocolAnalysisKeys.all, caseNumber] as const,
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useProtocolAnalysis(caseNumber: string | undefined) {
|
|
||||||
return useQuery({
|
|
||||||
queryKey: protocolAnalysisKeys.byCase(caseNumber ?? ""),
|
|
||||||
queryFn: ({ signal }) =>
|
|
||||||
apiRequest<ProtocolAnalysisResponse>(
|
|
||||||
`/api/cases/${caseNumber}/protocol-analysis`,
|
|
||||||
{ signal },
|
|
||||||
),
|
|
||||||
enabled: Boolean(caseNumber),
|
|
||||||
staleTime: 10_000,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* The analysis runs on the legal-analyst agent (host-side, where the `claude`
|
|
||||||
* CLI lives) — NOT inline in the FastAPI container. The endpoint delegates via
|
|
||||||
* a Paperclip wakeup (`queued`), or reports `skipped` when no analyst route is
|
|
||||||
* available (the chair can then run the MCP tool manually).
|
|
||||||
*/
|
|
||||||
export type AnalyzeProtocolResult =
|
|
||||||
| {
|
|
||||||
status: "queued";
|
|
||||||
sub_issue_id: string;
|
|
||||||
analyst_id: string;
|
|
||||||
main_issue_id: string;
|
|
||||||
}
|
|
||||||
| {
|
|
||||||
status: "skipped";
|
|
||||||
reason: "no_api_key" | "no_analyst" | "no_issue" | string;
|
|
||||||
company_id?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function useAnalyzeProtocol(caseNumber: string | undefined) {
|
|
||||||
const qc = useQueryClient();
|
|
||||||
return useMutation({
|
|
||||||
mutationFn: (documentId?: string) =>
|
|
||||||
apiRequest<AnalyzeProtocolResult>(
|
|
||||||
`/api/cases/${caseNumber}/analyze-protocol${
|
|
||||||
documentId ? `?document_id=${encodeURIComponent(documentId)}` : ""
|
|
||||||
}`,
|
|
||||||
{ method: "POST" },
|
|
||||||
),
|
|
||||||
onSuccess: () => {
|
|
||||||
if (caseNumber) {
|
|
||||||
qc.invalidateQueries({
|
|
||||||
queryKey: protocolAnalysisKeys.byCase(caseNumber),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
},
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
export const CHANGE_LABELS_HE: Record<ProtocolChangeType, string> = {
|
|
||||||
strengthened: "התחזק בדיון",
|
|
||||||
newly_raised: "נטען לראשונה",
|
|
||||||
dropped: "נזנח בדיון",
|
|
||||||
};
|
|
||||||
|
|
||||||
export const PROTOCOL_PARTY_LABELS_HE: Record<ProtocolPartyRole, string> = {
|
|
||||||
appellant: "עוררים",
|
|
||||||
respondent: "משיבים",
|
|
||||||
committee: "ועדה מקומית",
|
|
||||||
permit_applicant: "מבקשי היתר",
|
|
||||||
unknown: "צד לא מזוהה",
|
|
||||||
"": "צד לא מסווג",
|
|
||||||
};
|
|
||||||
|
|
||||||
/** Display order for the per-party sections. */
|
|
||||||
export const PROTOCOL_PARTY_ORDER: ProtocolPartyRole[] = [
|
|
||||||
"appellant",
|
|
||||||
"committee",
|
|
||||||
"respondent",
|
|
||||||
"permit_applicant",
|
|
||||||
"unknown",
|
|
||||||
"",
|
|
||||||
];
|
|
||||||
@@ -60,8 +60,6 @@ from web.paperclip_client import (
|
|||||||
update_project_name as pc_update_project_name,
|
update_project_name as pc_update_project_name,
|
||||||
wake_analyst_for_appraiser_facts as pc_wake_analyst_for_appraiser_facts,
|
wake_analyst_for_appraiser_facts as pc_wake_analyst_for_appraiser_facts,
|
||||||
wake_analyst_for_argument_aggregation as pc_wake_analyst_for_argument_aggregation,
|
wake_analyst_for_argument_aggregation as pc_wake_analyst_for_argument_aggregation,
|
||||||
wake_analyst_for_protocol_analysis as pc_wake_analyst_for_protocol_analysis,
|
|
||||||
get_generation_run_status as pc_get_generation_run_status,
|
|
||||||
wake_ceo_agent as pc_wake_ceo,
|
wake_ceo_agent as pc_wake_ceo,
|
||||||
wake_ceo_for_action as pc_wake_ceo_for_action,
|
wake_ceo_for_action as pc_wake_ceo_for_action,
|
||||||
wake_ceo_for_feedback_fold as pc_wake_ceo_for_feedback_fold,
|
wake_ceo_for_feedback_fold as pc_wake_ceo_for_feedback_fold,
|
||||||
@@ -108,8 +106,6 @@ __all__ = [
|
|||||||
"pc_wake_for_precedent_extraction",
|
"pc_wake_for_precedent_extraction",
|
||||||
"pc_wake_analyst_for_appraiser_facts",
|
"pc_wake_analyst_for_appraiser_facts",
|
||||||
"pc_wake_analyst_for_argument_aggregation",
|
"pc_wake_analyst_for_argument_aggregation",
|
||||||
"pc_wake_analyst_for_protocol_analysis",
|
|
||||||
"pc_get_generation_run_status",
|
|
||||||
# comments / interactions
|
# comments / interactions
|
||||||
"pc_post_comment",
|
"pc_post_comment",
|
||||||
"pc_get_issue_comments",
|
"pc_get_issue_comments",
|
||||||
|
|||||||
186
web/app.py
186
web/app.py
@@ -79,8 +79,6 @@ from web.agent_platform_port import (
|
|||||||
pc_restore_project,
|
pc_restore_project,
|
||||||
pc_wake_analyst_for_appraiser_facts,
|
pc_wake_analyst_for_appraiser_facts,
|
||||||
pc_wake_analyst_for_argument_aggregation,
|
pc_wake_analyst_for_argument_aggregation,
|
||||||
pc_wake_analyst_for_protocol_analysis,
|
|
||||||
pc_get_generation_run_status,
|
|
||||||
rename_case_project,
|
rename_case_project,
|
||||||
pc_wake_ceo,
|
pc_wake_ceo,
|
||||||
pc_wake_ceo_for_action,
|
pc_wake_ceo_for_action,
|
||||||
@@ -2661,97 +2659,6 @@ async def api_get_legal_arguments(case_number: str, party: str = ""):
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/cases/{case_number}/protocol-analysis")
|
|
||||||
async def api_get_protocol_analysis(case_number: str):
|
|
||||||
"""Hearing-protocol comparative analysis for the "מה קרה בדיון" panel (#226).
|
|
||||||
|
|
||||||
Read-only surface over the case-knowledge produced by ``analyze_protocol``:
|
|
||||||
the hearing header (date + who appeared, from the canonical case columns)
|
|
||||||
plus the per-argument verdicts (strengthened / newly_raised / dropped)
|
|
||||||
grouped by party. Container-safe — pure DB reads, no LLM. Returns an empty
|
|
||||||
analysis (not an error) when the analysis has not been run yet.
|
|
||||||
"""
|
|
||||||
case = await db.get_case_by_number(case_number)
|
|
||||||
if not case:
|
|
||||||
raise HTTPException(404, f"תיק {case_number} לא נמצא")
|
|
||||||
|
|
||||||
case_id = UUID(case["id"])
|
|
||||||
rows = await db.list_protocol_analysis(case_id)
|
|
||||||
|
|
||||||
# Protocol title comes from the analysed document (all rows share one
|
|
||||||
# document_id per idempotent replace). Resolve it via the case's documents.
|
|
||||||
protocol_title = ""
|
|
||||||
protocol_document_id = ""
|
|
||||||
if rows:
|
|
||||||
protocol_document_id = rows[0].get("document_id") or ""
|
|
||||||
docs = await db.list_documents(case_id)
|
|
||||||
match = next(
|
|
||||||
(d for d in docs if str(d.get("id")) == protocol_document_id), None,
|
|
||||||
)
|
|
||||||
if match:
|
|
||||||
protocol_title = match.get("title") or ""
|
|
||||||
|
|
||||||
attendees = case.get("hearing_attendees") or {}
|
|
||||||
hearing_date = case.get("hearing_date")
|
|
||||||
header = {
|
|
||||||
"hearing_date": hearing_date.isoformat() if hearing_date else None,
|
|
||||||
"protocol_title": protocol_title,
|
|
||||||
"protocol_document_id": protocol_document_id,
|
|
||||||
"panel_members": attendees.get("panel_members") or [],
|
|
||||||
"appellants_present": attendees.get("appellants_present") or [],
|
|
||||||
"respondents_present": attendees.get("respondents_present") or [],
|
|
||||||
}
|
|
||||||
|
|
||||||
# Group verdicts by party for the panel's per-side sections, in display order.
|
|
||||||
by_party: dict[str, list[dict]] = {}
|
|
||||||
by_change: dict[str, int] = {}
|
|
||||||
for r in rows:
|
|
||||||
by_party.setdefault(r.get("party_role") or "", []).append(r)
|
|
||||||
ct = r.get("change_type", "")
|
|
||||||
by_change[ct] = by_change.get(ct, 0) + 1
|
|
||||||
|
|
||||||
return {
|
|
||||||
"case_number": case_number,
|
|
||||||
"total": len(rows),
|
|
||||||
"header": header,
|
|
||||||
"by_change": by_change,
|
|
||||||
"by_party": by_party,
|
|
||||||
"analysis": rows,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/cases/{case_number}/analyze-protocol")
|
|
||||||
async def api_analyze_protocol(case_number: str, document_id: str = ""):
|
|
||||||
"""Queue hearing-protocol analysis by waking the legal-analyst agent (#226).
|
|
||||||
|
|
||||||
Same delegation rationale as ``aggregate-arguments``: ``analyze_protocol``
|
|
||||||
calls the local ``claude`` CLI, absent in this container, so we route to the
|
|
||||||
company's analyst rather than running a doomed in-container BackgroundTask.
|
|
||||||
|
|
||||||
Response: {"status": "queued", ...} or {"status": "skipped", "reason": ...}.
|
|
||||||
"""
|
|
||||||
case = await db.get_case_by_number(case_number)
|
|
||||||
if not case:
|
|
||||||
raise HTTPException(404, f"תיק {case_number} לא נמצא")
|
|
||||||
|
|
||||||
prefix = case_number[:1]
|
|
||||||
company_id = (
|
|
||||||
PAPERCLIP_COMPANIES["licensing"] if prefix == "1"
|
|
||||||
else PAPERCLIP_COMPANIES["betterment"] if prefix in ("8", "9")
|
|
||||||
else ""
|
|
||||||
)
|
|
||||||
|
|
||||||
try:
|
|
||||||
result = await pc_wake_analyst_for_protocol_analysis(
|
|
||||||
case_number, company_id=company_id, document_id=document_id,
|
|
||||||
)
|
|
||||||
except Exception as e:
|
|
||||||
logger.exception("analyst wakeup failed for protocol analysis %s", case_number)
|
|
||||||
raise HTTPException(500, f"לא ניתן לשלוח לאנליטיקאי: {e}")
|
|
||||||
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/api/cases/{case_number}/direction")
|
@app.post("/api/cases/{case_number}/direction")
|
||||||
async def api_set_direction(case_number: str, req: DirectionRequest):
|
async def api_set_direction(case_number: str, req: DirectionRequest):
|
||||||
"""Save the approved direction document for the discussion block."""
|
"""Save the approved direction document for the discussion block."""
|
||||||
@@ -3213,7 +3120,7 @@ async def api_party_claims_summary(case_number: str):
|
|||||||
# Wakeup goes through the Paperclip API helper (pc_wake_ceo_for_action → the
|
# Wakeup goes through the Paperclip API helper (pc_wake_ceo_for_action → the
|
||||||
# platform Port → POST /api/agents/{id}/wakeup), NEVER a direct DB insert.
|
# platform Port → POST /api/agents/{id}/wakeup), NEVER a direct DB insert.
|
||||||
# Polling for completion uses the existing read endpoints (research/party-claims-
|
# Polling for completion uses the existing read endpoints (research/party-claims-
|
||||||
# summary for the summary; the exports list for the טיוטה-טענות_הצדדים_*.docx file).
|
# summary for the summary; the exports list for the טיוטת-ביניים-*.docx file).
|
||||||
|
|
||||||
|
|
||||||
async def _wake_ceo_action(case_number: str, action: str) -> dict:
|
async def _wake_ceo_action(case_number: str, action: str) -> dict:
|
||||||
@@ -3246,99 +3153,10 @@ async def api_generate_party_claims_summary(case_number: str):
|
|||||||
async def api_generate_interim_draft(case_number: str):
|
async def api_generate_interim_draft(case_number: str):
|
||||||
"""Fire-and-accept: wake the CEO to generate the partial "party-claims" draft
|
"""Fire-and-accept: wake the CEO to generate the partial "party-claims" draft
|
||||||
(שלב H → write_interim_draft + export_interim_draft). Runs host-side; poll the
|
(שלב H → write_interim_draft + export_interim_draft). Runs host-side; poll the
|
||||||
exports list for the new טיוטה-טענות_הצדדים_{N}.docx."""
|
exports list for the new טיוטת-ביניים-{case}-vN.docx."""
|
||||||
return await _wake_ceo_action(case_number, "interim_draft")
|
return await _wake_ceo_action(case_number, "interim_draft")
|
||||||
|
|
||||||
|
|
||||||
_GENERATE_ACTIONS = {"party_claims_summary", "interim_draft"}
|
|
||||||
# Run statuses (Paperclip heartbeat_runs.status) grouped for state mapping.
|
|
||||||
_RUN_ACTIVE = {"running", "in_progress", "queued", "pending", "scheduled", "created"}
|
|
||||||
_RUN_FAILED = {"cancelled", "failed", "error", "timed_out", "lost"}
|
|
||||||
|
|
||||||
|
|
||||||
def _generation_output_ready(case_number: str, action: str) -> bool:
|
|
||||||
"""Whether the generation artifact already exists on disk (host-side)."""
|
|
||||||
if action == "party_claims_summary":
|
|
||||||
from legal_mcp.services import party_claims_summary as pcs
|
|
||||||
return pcs.summary_file_path(case_number).exists()
|
|
||||||
# interim_draft → a "טיוטה-טענות_הצדדים_*.docx" file in the case exports dir.
|
|
||||||
export_dir = config.find_case_dir(case_number) / "exports"
|
|
||||||
if not export_dir.exists():
|
|
||||||
return False
|
|
||||||
return any(
|
|
||||||
f.is_file() and f.suffix.lower() == ".docx" and f.name.startswith("טיוטה-טענות_הצדדים_")
|
|
||||||
for f in export_dir.iterdir()
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/cases/{case_number}/generate/{action}/status")
|
|
||||||
async def api_generate_status(case_number: str, action: str):
|
|
||||||
"""Server-derived status of a "הפקת מסמכים" background generation (#227 ג).
|
|
||||||
|
|
||||||
Reconstructs {idle|queued|running|done|failed} from the CEO child issue + its
|
|
||||||
latest heartbeat_run (via the platform port) plus whether the output artifact
|
|
||||||
exists — so the UI indicator is correct after navigating away and back; it
|
|
||||||
never depends on the browser staying on the page. ``started_at``/``finished_at``
|
|
||||||
are server timestamps (ISO-8601 UTC) so the client renders a correct elapsed
|
|
||||||
time on return.
|
|
||||||
"""
|
|
||||||
if action not in _GENERATE_ACTIONS:
|
|
||||||
raise HTTPException(400, f"action לא תקין: {action}")
|
|
||||||
case = await db.get_case_by_number(case_number)
|
|
||||||
if not case:
|
|
||||||
raise HTTPException(404, f"תיק {case_number} לא נמצא")
|
|
||||||
|
|
||||||
output_ready = _generation_output_ready(case_number, action)
|
|
||||||
try:
|
|
||||||
run = await pc_get_generation_run_status(case_number, action)
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("generation status lookup failed for %s/%s: %s", case_number, action, e)
|
|
||||||
run = {"issue_id": None}
|
|
||||||
|
|
||||||
run_status = (run.get("run_status") or "").lower()
|
|
||||||
started_at = run.get("started_at")
|
|
||||||
active = run_status in _RUN_ACTIVE or (
|
|
||||||
run.get("issue_status") == "in_progress"
|
|
||||||
and run_status not in _RUN_FAILED
|
|
||||||
and run_status not in {"completed", "succeeded", "done"}
|
|
||||||
and not run.get("finished_at")
|
|
||||||
)
|
|
||||||
|
|
||||||
# Precedence: an in-flight run wins; then a produced artifact; then a failed
|
|
||||||
# run; else idle. (A produced file reads as "done" even if a later retry
|
|
||||||
# failed — the artifact exists.)
|
|
||||||
if active:
|
|
||||||
state = "running" if started_at else "queued"
|
|
||||||
elif output_ready:
|
|
||||||
state = "done"
|
|
||||||
elif run_status in _RUN_FAILED:
|
|
||||||
state = "failed"
|
|
||||||
elif run_status in {"completed", "succeeded", "done"}:
|
|
||||||
# Ran to completion but produced no artifact → treat as a failure so the
|
|
||||||
# chair isn't left thinking it worked.
|
|
||||||
state = "failed"
|
|
||||||
else:
|
|
||||||
state = "idle"
|
|
||||||
|
|
||||||
detail = ""
|
|
||||||
if state == "failed":
|
|
||||||
if run.get("error_code") == "issue_assignee_changed":
|
|
||||||
detail = "הריצה בוטלה (הוקצתה מחדש)"
|
|
||||||
else:
|
|
||||||
detail = run.get("error") or "הריצה נכשלה"
|
|
||||||
|
|
||||||
return {
|
|
||||||
"case_number": case_number,
|
|
||||||
"action": action,
|
|
||||||
"state": state,
|
|
||||||
"started_at": started_at,
|
|
||||||
"finished_at": run.get("finished_at"),
|
|
||||||
"output_ready": output_ready,
|
|
||||||
"detail": detail,
|
|
||||||
"issue_id": run.get("issue_id"),
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/api/cases/{case_number}/research/party-claims-summary/download")
|
@app.get("/api/cases/{case_number}/research/party-claims-summary/download")
|
||||||
async def api_party_claims_summary_download(case_number: str):
|
async def api_party_claims_summary_download(case_number: str):
|
||||||
"""Download the raw party-claims-summary.md file."""
|
"""Download the raw party-claims-summary.md file."""
|
||||||
|
|||||||
@@ -1258,58 +1258,25 @@ async def wake_ceo_agent(issue_id: str, case_number: str, company_id: str = "")
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
def _ceo_action_brief(action: str, case_number: str) -> tuple[str, str]:
|
|
||||||
"""(child-issue title, description) for a deterministic CEO generation action.
|
|
||||||
|
|
||||||
The instruction is self-contained in the description (like
|
|
||||||
``wake_analyst_for_argument_aggregation``) so the run does not depend on the
|
|
||||||
CEO parsing ``payload.action`` — it just runs the named tool and closes the
|
|
||||||
child. Both actions run host-side (claude_session → local claude CLI).
|
|
||||||
"""
|
|
||||||
if action == "party_claims_summary":
|
|
||||||
title = f"[ערר {case_number}] הפקת סיכום-מנהלים לטענות הצדדים"
|
|
||||||
description = (
|
|
||||||
f"חיים ביקש הפקת סיכום-מנהלים לטענות הצדדים בתיק {case_number}.\n\n"
|
|
||||||
f"הרץ `mcp__legal-ai__summarize_party_claims(case_number=\"{case_number}\")`, "
|
|
||||||
f"כתוב comment קצר בעברית עם תמצית התוצאה, וסגור issue זה כ-done. "
|
|
||||||
f"אם חסרים נתונים (אין טענות מחולצות) — דווח ב-comment מה חסר וסגור כ-blocked."
|
|
||||||
)
|
|
||||||
return title, description
|
|
||||||
# default: interim_draft
|
|
||||||
title = f"[ערר {case_number}] הפקת טיוטת טענות-הצדדים (טיוטת-ביניים)"
|
|
||||||
description = (
|
|
||||||
f"חיים ביקש הפקת טיוטת טענות-הצדדים (טיוטת-ביניים) בתיק {case_number}.\n\n"
|
|
||||||
f"הרץ `mcp__legal-ai__write_interim_draft(case_number=\"{case_number}\")` ואז "
|
|
||||||
f"`mcp__legal-ai__export_interim_draft(case_number=\"{case_number}\")`, כתוב comment "
|
|
||||||
f"קצר בעברית עם שם הקובץ שנוצר, וסגור issue זה כ-done. אם חסרים נתונים — דווח "
|
|
||||||
f"ב-comment וסגור כ-blocked."
|
|
||||||
)
|
|
||||||
return title, description
|
|
||||||
|
|
||||||
|
|
||||||
async def wake_ceo_for_action(
|
async def wake_ceo_for_action(
|
||||||
case_number: str,
|
case_number: str,
|
||||||
action: str,
|
action: str,
|
||||||
company_id: str = "",
|
company_id: str = "",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""Wake the CEO to run a deterministic generation action (TaskMaster #214).
|
"""Wake the CEO with a deterministic *structured action* on the case's MAIN issue.
|
||||||
|
|
||||||
Drives the UI "הפקת מסמכים" buttons:
|
Drives the UI "הפקת מסמכים" buttons (TaskMaster #214): the CEO reads
|
||||||
action="party_claims_summary" → summarize_party_claims (שלב H2)
|
``payload.action`` and routes deterministically to its שלב H / שלב H2
|
||||||
action="interim_draft" → write_interim_draft + export_interim_draft (שלב H)
|
side-quests (legal-ceo.md §"פעולות סטרוקטורליות") — no free-text parsing.
|
||||||
|
|
||||||
A **child issue assigned to the CEO** is created under the case's main issue
|
action="party_claims_summary" → שלב H2 (summarize_party_claims)
|
||||||
and the wakeup targets that child — NOT the main issue directly (#227). The
|
action="interim_draft" → שלב H (write_interim_draft + export_interim_draft)
|
||||||
main issue is usually ``in_review`` assigned to the chair (human) while a case
|
|
||||||
waits; waking the CEO *on* a human-owned issue makes Paperclip cancel the run
|
|
||||||
immediately (``issue_assignee_changed``) — the exact silent failure this
|
|
||||||
fixes. The CEO owns the child, so its run is never cancelled. Same delegation
|
|
||||||
shape as ``wake_analyst_for_argument_aggregation``.
|
|
||||||
|
|
||||||
Wakeup goes through the Paperclip API (``POST /api/agents/{id}/wakeup``), never
|
These are side-quests on the EXISTING ``[ערר {case_number}]`` issue — no child
|
||||||
a direct DB insert (CLAUDE.md hard rule). Returns
|
issue is created (the CEO must not change ``cases.status`` or spawn sub-agents).
|
||||||
``{"status": "ok", "issue_id"(=child), "ceo_id", ...}`` or
|
Wakeup goes through the Paperclip API (``POST /api/agents/{id}/wakeup``), never a
|
||||||
``{"status": "skipped", "reason": ...}``.
|
direct DB insert (CLAUDE.md hard rule). Returns
|
||||||
|
``{"status": "ok"|"skipped", ...}``.
|
||||||
"""
|
"""
|
||||||
if not PAPERCLIP_BOARD_API_KEY:
|
if not PAPERCLIP_BOARD_API_KEY:
|
||||||
logger.warning("PAPERCLIP_BOARD_API_KEY not set — skipping CEO action wakeup")
|
logger.warning("PAPERCLIP_BOARD_API_KEY not set — skipping CEO action wakeup")
|
||||||
@@ -1320,42 +1287,17 @@ async def wake_ceo_for_action(
|
|||||||
logger.warning("No Paperclip issues found for case %s — skipping CEO action", case_number)
|
logger.warning("No Paperclip issues found for case %s — skipping CEO action", case_number)
|
||||||
return {"status": "skipped", "reason": "no_issue"}
|
return {"status": "skipped", "reason": "no_issue"}
|
||||||
|
|
||||||
|
# The main case issue — prefer the in-progress one, else the canonical
|
||||||
|
# "[ערר {case_number}]" issue, else the oldest. (Same selection spirit as
|
||||||
|
# wake_curator_for_final, but we never spawn a child — it's a side-quest.)
|
||||||
main_issue = (
|
main_issue = (
|
||||||
next((i for i in issues if i.get("status") == "in_progress"), None)
|
next((i for i in issues if i.get("status") == "in_progress"), None)
|
||||||
or next((i for i in issues if f"[ערר {case_number}]" in (i.get("title") or "")), None)
|
or next((i for i in issues if f"[ערר {case_number}]" in (i.get("title") or "")), None)
|
||||||
or issues[0]
|
or issues[0]
|
||||||
)
|
)
|
||||||
main_issue_id = main_issue["id"]
|
main_issue_id = main_issue["id"]
|
||||||
|
|
||||||
ceo_id = CEO_AGENTS.get(company_id, CEO_AGENT_ID)
|
ceo_id = CEO_AGENTS.get(company_id, CEO_AGENT_ID)
|
||||||
|
|
||||||
# Child issue assigned to the CEO — so the queued run is owned by the CEO and
|
|
||||||
# not cancelled by the human assignee on the parent (#227).
|
|
||||||
title, description = _ceo_action_brief(action, case_number)
|
|
||||||
child_resp = await pc_request(
|
|
||||||
"POST",
|
|
||||||
f"/api/issues/{main_issue_id}/children",
|
|
||||||
json={
|
|
||||||
"title": title,
|
|
||||||
"description": description,
|
|
||||||
"status": "in_progress",
|
|
||||||
"priority": "medium",
|
|
||||||
"assigneeAgentId": ceo_id,
|
|
||||||
},
|
|
||||||
raise_on_error=True,
|
|
||||||
)
|
|
||||||
sub_issue = child_resp.json()
|
|
||||||
sub_issue_id = sub_issue["id"]
|
|
||||||
|
|
||||||
# Tag plugin_state so the case page surfaces this sub-issue too.
|
|
||||||
try:
|
|
||||||
conn = await asyncpg.connect(PAPERCLIP_DB_URL)
|
|
||||||
try:
|
|
||||||
await _link_case_to_issue(conn, sub_issue_id, case_number)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("plugin_state link failed for sub_issue=%s: %s", sub_issue_id, e)
|
|
||||||
|
|
||||||
wake_resp = await pc_request(
|
wake_resp = await pc_request(
|
||||||
"POST",
|
"POST",
|
||||||
f"/api/agents/{ceo_id}/wakeup",
|
f"/api/agents/{ceo_id}/wakeup",
|
||||||
@@ -1364,7 +1306,7 @@ async def wake_ceo_for_action(
|
|||||||
"triggerDetail": "manual",
|
"triggerDetail": "manual",
|
||||||
"reason": f"generate_{action}_{case_number}",
|
"reason": f"generate_{action}_{case_number}",
|
||||||
"payload": {
|
"payload": {
|
||||||
"issueId": sub_issue_id,
|
"issueId": main_issue_id,
|
||||||
"action": action,
|
"action": action,
|
||||||
"case_number": case_number,
|
"case_number": case_number,
|
||||||
},
|
},
|
||||||
@@ -1372,85 +1314,17 @@ async def wake_ceo_for_action(
|
|||||||
raise_on_error=True,
|
raise_on_error=True,
|
||||||
)
|
)
|
||||||
logger.info(
|
logger.info(
|
||||||
"CEO action wakeup for case %s: action=%s child_issue=%s ceo=%s status=%s",
|
"CEO action wakeup for case %s: action=%s issue=%s ceo=%s status=%s",
|
||||||
case_number, action, sub_issue_id, ceo_id, wake_resp.status_code,
|
case_number, action, main_issue_id, ceo_id, wake_resp.status_code,
|
||||||
)
|
)
|
||||||
return {
|
return {
|
||||||
"status": "ok",
|
"status": "ok",
|
||||||
"action": action,
|
"action": action,
|
||||||
"issue_id": sub_issue_id,
|
"issue_id": main_issue_id,
|
||||||
"main_issue_id": main_issue_id,
|
|
||||||
"ceo_id": ceo_id,
|
"ceo_id": ceo_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
# Substring of the generation child-issue title per action (see _ceo_action_brief).
|
|
||||||
GENERATION_TITLE_SUBSTR = {
|
|
||||||
"party_claims_summary": "סיכום-מנהלים",
|
|
||||||
"interim_draft": "טיוטת טענות-הצדדים",
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def get_generation_run_status(case_number: str, action: str) -> dict:
|
|
||||||
"""Server-derived run status for a "הפקת מסמכים" generation action (#227 ג).
|
|
||||||
|
|
||||||
Reconstructs the state of the most recent generation child issue for
|
|
||||||
(case, action) from Paperclip — the child issue + its latest heartbeat_run —
|
|
||||||
so the UI indicator survives navigation/reload (it never depends on the
|
|
||||||
browser having stayed on the page). Read-only Paperclip DB access, behind the
|
|
||||||
platform port (G12).
|
|
||||||
|
|
||||||
Returns a serializable dict::
|
|
||||||
|
|
||||||
{"issue_id", "issue_status", "run_status", "started_at", "finished_at",
|
|
||||||
"error", "error_code"}
|
|
||||||
|
|
||||||
with all timestamps as ISO-8601 UTC strings (or None). ``issue_id`` is None
|
|
||||||
when no generation child issue exists yet (→ the endpoint reports 'idle').
|
|
||||||
"""
|
|
||||||
substr = GENERATION_TITLE_SUBSTR.get(action)
|
|
||||||
if not substr:
|
|
||||||
return {"issue_id": None}
|
|
||||||
|
|
||||||
def _iso(dt) -> str | None:
|
|
||||||
return dt.isoformat() if dt is not None else None
|
|
||||||
|
|
||||||
conn = await asyncpg.connect(PAPERCLIP_DB_URL)
|
|
||||||
try:
|
|
||||||
issue = await conn.fetchrow(
|
|
||||||
"""SELECT id, status
|
|
||||||
FROM issues
|
|
||||||
WHERE title LIKE ('%' || $1 || '%') AND title LIKE ('%' || $2 || '%')
|
|
||||||
ORDER BY created_at DESC
|
|
||||||
LIMIT 1""",
|
|
||||||
case_number, substr,
|
|
||||||
)
|
|
||||||
if issue is None:
|
|
||||||
return {"issue_id": None}
|
|
||||||
|
|
||||||
run = await conn.fetchrow(
|
|
||||||
"""SELECT hr.status, hr.started_at, hr.finished_at, hr.error, hr.error_code
|
|
||||||
FROM heartbeat_runs hr
|
|
||||||
JOIN agent_wakeup_requests awr ON hr.wakeup_request_id = awr.id
|
|
||||||
WHERE awr.payload->>'issueId' = $1
|
|
||||||
ORDER BY hr.created_at DESC
|
|
||||||
LIMIT 1""",
|
|
||||||
str(issue["id"]),
|
|
||||||
)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
|
|
||||||
return {
|
|
||||||
"issue_id": str(issue["id"]),
|
|
||||||
"issue_status": issue["status"],
|
|
||||||
"run_status": run["status"] if run else None,
|
|
||||||
"started_at": _iso(run["started_at"]) if run else None,
|
|
||||||
"finished_at": _iso(run["finished_at"]) if run else None,
|
|
||||||
"error": (run["error"] if run else None) or None,
|
|
||||||
"error_code": (run["error_code"] if run else None) or None,
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
def _curator_task_brief(task: str, case_number: str, final_filename: str) -> tuple[str, str]:
|
def _curator_task_brief(task: str, case_number: str, final_filename: str) -> tuple[str, str]:
|
||||||
"""Build the (sub-issue title, description) for a staged final-decision task.
|
"""Build the (sub-issue title, description) for a staged final-decision task.
|
||||||
|
|
||||||
@@ -1810,109 +1684,3 @@ async def wake_analyst_for_argument_aggregation(
|
|||||||
"analyst_id": analyst_id,
|
"analyst_id": analyst_id,
|
||||||
"main_issue_id": main_issue_id,
|
"main_issue_id": main_issue_id,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
async def wake_analyst_for_protocol_analysis(
|
|
||||||
case_number: str,
|
|
||||||
company_id: str,
|
|
||||||
document_id: str = "",
|
|
||||||
) -> dict:
|
|
||||||
"""Wake the legal-analyst to run the hearing-protocol comparative analysis.
|
|
||||||
|
|
||||||
Triggered by the chair clicking "נתח את פרוטוקול הדיון" / "נתח מחדש" in the
|
|
||||||
"מה קרה בדיון" panel (#226). Same delegation shape as
|
|
||||||
``wake_analyst_for_argument_aggregation``: the FastAPI container cannot run
|
|
||||||
``analyze_protocol`` directly (it calls ``claude_session.query_json()``,
|
|
||||||
which needs the host-side ``claude`` CLI), so we create a child issue under
|
|
||||||
the case's main Paperclip issue, assign it to the company's analyst, and
|
|
||||||
trigger a wakeup. The analyst runs the MCP tool locally and reports back.
|
|
||||||
|
|
||||||
``document_id`` optionally pins the analysis to a specific protocol document
|
|
||||||
(when a case holds several protocols — #223).
|
|
||||||
|
|
||||||
Returns a dict shaped for the FastAPI endpoint to serialize as-is:
|
|
||||||
{"status": "queued", "sub_issue_id", "analyst_id", "main_issue_id"}
|
|
||||||
or {"status": "skipped", "reason": "..."} for non-fatal early outs.
|
|
||||||
"""
|
|
||||||
if not PAPERCLIP_BOARD_API_KEY:
|
|
||||||
logger.warning(
|
|
||||||
"PAPERCLIP_BOARD_API_KEY not set — cannot queue analyst wakeup "
|
|
||||||
"for protocol analysis on %s",
|
|
||||||
case_number,
|
|
||||||
)
|
|
||||||
return {"status": "skipped", "reason": "no_api_key"}
|
|
||||||
|
|
||||||
analyst_id = ANALYST_AGENTS.get(company_id)
|
|
||||||
if not analyst_id:
|
|
||||||
logger.info("No analyst configured for company %s — skipping", company_id)
|
|
||||||
return {"status": "skipped", "reason": "no_analyst", "company_id": company_id}
|
|
||||||
|
|
||||||
issues = await get_case_issues(case_number)
|
|
||||||
if not issues:
|
|
||||||
logger.warning(
|
|
||||||
"No Paperclip issues found for case %s — cannot queue analyst", case_number,
|
|
||||||
)
|
|
||||||
return {"status": "skipped", "reason": "no_issue"}
|
|
||||||
|
|
||||||
main_issue = next((i for i in issues if i.get("status") == "in_progress"), None) or issues[0]
|
|
||||||
main_issue_id = main_issue["id"]
|
|
||||||
|
|
||||||
doc_clause = f", document_id=\"{document_id}\"" if document_id.strip() else ""
|
|
||||||
description = (
|
|
||||||
f"חיים ביקש ניתוח פרוטוקול-דיון בתיק {case_number}.\n\n"
|
|
||||||
f"הרץ `mcp__legal-ai__analyze_protocol(case_number=\"{case_number}\"{doc_clause})` "
|
|
||||||
f"וכתוב comment בעברית עם תוצאת הניתוח — כמה טענות התחזקו בדיון, כמה נטענו "
|
|
||||||
f"לראשונה, וכמה ירדו. אם אין פרוטוקול ועדת-ערר בתיק או שאין טיעונים מאוגדים "
|
|
||||||
f"להשוואה, דווח ב-comment מה חסר וסגור את ה-issue כ-blocked."
|
|
||||||
)
|
|
||||||
child_resp = await pc_request(
|
|
||||||
"POST",
|
|
||||||
f"/api/issues/{main_issue_id}/children",
|
|
||||||
json={
|
|
||||||
"title": f"[ערר {case_number}] ניתוח פרוטוקול-דיון",
|
|
||||||
"description": description,
|
|
||||||
"status": "in_progress",
|
|
||||||
"priority": "medium",
|
|
||||||
"assigneeAgentId": analyst_id,
|
|
||||||
},
|
|
||||||
raise_on_error=True,
|
|
||||||
)
|
|
||||||
sub_issue = child_resp.json()
|
|
||||||
sub_issue_id = sub_issue["id"]
|
|
||||||
|
|
||||||
# Tag plugin_state so the case page surfaces this sub-issue too.
|
|
||||||
try:
|
|
||||||
conn = await asyncpg.connect(PAPERCLIP_DB_URL)
|
|
||||||
try:
|
|
||||||
await _link_case_to_issue(conn, sub_issue_id, case_number)
|
|
||||||
finally:
|
|
||||||
await conn.close()
|
|
||||||
except Exception as e:
|
|
||||||
logger.warning("plugin_state link failed for sub_issue=%s: %s", sub_issue_id, e)
|
|
||||||
|
|
||||||
wake_resp = await pc_request(
|
|
||||||
"POST",
|
|
||||||
f"/api/agents/{analyst_id}/wakeup",
|
|
||||||
json={
|
|
||||||
"source": "on_demand",
|
|
||||||
"triggerDetail": "manual",
|
|
||||||
"reason": f"analyze_protocol_{case_number}",
|
|
||||||
"payload": {
|
|
||||||
"issueId": sub_issue_id,
|
|
||||||
"mutation": "assignment",
|
|
||||||
"caseNumber": case_number,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
raise_on_error=True,
|
|
||||||
)
|
|
||||||
logger.info(
|
|
||||||
"Analyst wakeup for protocol analysis on case %s: sub_issue=%s "
|
|
||||||
"analyst=%s doc=%s wake=%s",
|
|
||||||
case_number, sub_issue_id, analyst_id, document_id or "auto", wake_resp.status_code,
|
|
||||||
)
|
|
||||||
return {
|
|
||||||
"status": "queued",
|
|
||||||
"sub_issue_id": sub_issue_id,
|
|
||||||
"analyst_id": analyst_id,
|
|
||||||
"main_issue_id": main_issue_id,
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user