diff --git a/.gitignore b/.gitignore
index 1c0fb56..72d77ee 100644
--- a/.gitignore
+++ b/.gitignore
@@ -7,3 +7,27 @@ venv/
.env
*.log
.pytest_cache/
+
+# Logs
+logs
+npm-debug.log*
+yarn-debug.log*
+yarn-error.log*
+dev-debug.log
+# Dependency directories
+node_modules/
+# Environment variables
+# Editor directories and files
+.idea
+.vscode
+*.suo
+*.ntvs*
+*.njsproj
+*.sln
+*.sw?
+# OS specific
+.DS_Store
+
+# Task files
+# tasks.json
+# tasks/
diff --git a/.taskmaster/config.json b/.taskmaster/config.json
new file mode 100644
index 0000000..75c8952
--- /dev/null
+++ b/.taskmaster/config.json
@@ -0,0 +1,44 @@
+{
+ "models": {
+ "main": {
+ "provider": "anthropic",
+ "modelId": "claude-sonnet-4-20250514",
+ "maxTokens": 64000,
+ "temperature": 0.2
+ },
+ "research": {
+ "provider": "perplexity",
+ "modelId": "sonar",
+ "maxTokens": 8700,
+ "temperature": 0.1
+ },
+ "fallback": {
+ "provider": "anthropic",
+ "modelId": "claude-3-7-sonnet-20250219",
+ "maxTokens": 120000,
+ "temperature": 0.2
+ }
+ },
+ "global": {
+ "logLevel": "info",
+ "debug": false,
+ "defaultNumTasks": 10,
+ "defaultSubtasks": 5,
+ "defaultPriority": "medium",
+ "projectName": "Task Master",
+ "ollamaBaseURL": "http://localhost:11434/api",
+ "bedrockBaseURL": "https://bedrock.us-east-1.amazonaws.com",
+ "responseLanguage": "English",
+ "enableCodebaseAnalysis": true,
+ "enableProxy": false,
+ "anonymousTelemetry": true,
+ "userId": "1234567890"
+ },
+ "claudeCode": {},
+ "codexCli": {},
+ "grokCli": {
+ "timeout": 120000,
+ "workingDirectory": null,
+ "defaultModel": "grok-4-latest"
+ }
+}
\ No newline at end of file
diff --git a/.taskmaster/state.json b/.taskmaster/state.json
new file mode 100644
index 0000000..bbbe3a9
--- /dev/null
+++ b/.taskmaster/state.json
@@ -0,0 +1,6 @@
+{
+ "currentTag": "master",
+ "lastSwitched": "2026-04-19T06:09:58.720Z",
+ "branchTagMapping": {},
+ "migrationNoticeShown": true
+}
\ No newline at end of file
diff --git a/.taskmaster/templates/example_prd.txt b/.taskmaster/templates/example_prd.txt
new file mode 100644
index 0000000..194114d
--- /dev/null
+++ b/.taskmaster/templates/example_prd.txt
@@ -0,0 +1,47 @@
+
+# Overview
+[Provide a high-level overview of your product here. Explain what problem it solves, who it's for, and why it's valuable.]
+
+# Core Features
+[List and describe the main features of your product. For each feature, include:
+- What it does
+- Why it's important
+- How it works at a high level]
+
+# User Experience
+[Describe the user journey and experience. Include:
+- User personas
+- Key user flows
+- UI/UX considerations]
+
+
+# Technical Architecture
+[Outline the technical implementation details:
+- System components
+- Data models
+- APIs and integrations
+- Infrastructure requirements]
+
+# Development Roadmap
+[Break down the development process into phases:
+- MVP requirements
+- Future enhancements
+- Do not think about timelines whatsoever -- all that matters is scope and detailing exactly what needs to be build in each phase so it can later be cut up into tasks]
+
+# Logical Dependency Chain
+[Define the logical order of development:
+- Which features need to be built first (foundation)
+- Getting as quickly as possible to something usable/visible front end that works
+- Properly pacing and scoping each feature so it is atomic but can also be built upon and improved as development approaches]
+
+# Risks and Mitigations
+[Identify potential risks and how they'll be addressed:
+- Technical challenges
+- Figuring out the MVP that we can build upon
+- Resource constraints]
+
+# Appendix
+[Include any additional information:
+- Research findings
+- Technical specifications]
+
\ No newline at end of file
diff --git a/.taskmaster/templates/example_prd_rpg.txt b/.taskmaster/templates/example_prd_rpg.txt
new file mode 100644
index 0000000..5ad908f
--- /dev/null
+++ b/.taskmaster/templates/example_prd_rpg.txt
@@ -0,0 +1,511 @@
+
+# Repository Planning Graph (RPG) Method - PRD Template
+
+This template teaches you (AI or human) how to create structured, dependency-aware PRDs using the RPG methodology from Microsoft Research. The key insight: separate WHAT (functional) from HOW (structural), then connect them with explicit dependencies.
+
+## Core Principles
+
+1. **Dual-Semantics**: Think functional (capabilities) AND structural (code organization) separately, then map them
+2. **Explicit Dependencies**: Never assume - always state what depends on what
+3. **Topological Order**: Build foundation first, then layers on top
+4. **Progressive Refinement**: Start broad, refine iteratively
+
+## How to Use This Template
+
+- Follow the instructions in each `` block
+- Look at `` blocks to see good vs bad patterns
+- Fill in the content sections with your project details
+- The AI reading this will learn the RPG method by following along
+- Task Master will parse the resulting PRD into dependency-aware tasks
+
+## Recommended Tools for Creating PRDs
+
+When using this template to **create** a PRD (not parse it), use **code-context-aware AI assistants** for best results:
+
+**Why?** The AI needs to understand your existing codebase to make good architectural decisions about modules, dependencies, and integration points.
+
+**Recommended tools:**
+- **Claude Code** (claude-code CLI) - Best for structured reasoning and large contexts
+- **Cursor/Windsurf** - IDE integration with full codebase context
+- **Gemini CLI** (gemini-cli) - Massive context window for large codebases
+- **Codex/Grok CLI** - Strong code generation with context awareness
+
+**Note:** Once your PRD is created, `task-master parse-prd` works with any configured AI model - it just needs to read the PRD text itself, not your codebase.
+
+
+---
+
+
+
+Start with the problem, not the solution. Be specific about:
+- What pain point exists?
+- Who experiences it?
+- Why existing solutions don't work?
+- What success looks like (measurable outcomes)?
+
+Keep this section focused - don't jump into implementation details yet.
+
+
+## Problem Statement
+[Describe the core problem. Be concrete about user pain points.]
+
+## Target Users
+[Define personas, their workflows, and what they're trying to achieve.]
+
+## Success Metrics
+[Quantifiable outcomes. Examples: "80% task completion via autopilot", "< 5% manual intervention rate"]
+
+
+
+---
+
+
+
+Now think about CAPABILITIES (what the system DOES), not code structure yet.
+
+Step 1: Identify high-level capability domains
+- Think: "What major things does this system do?"
+- Examples: Data Management, Core Processing, Presentation Layer
+
+Step 2: For each capability, enumerate specific features
+- Use explore-exploit strategy:
+ * Exploit: What features are REQUIRED for core value?
+ * Explore: What features make this domain COMPLETE?
+
+Step 3: For each feature, define:
+- Description: What it does in one sentence
+- Inputs: What data/context it needs
+- Outputs: What it produces/returns
+- Behavior: Key logic or transformations
+
+
+Capability: Data Validation
+ Feature: Schema validation
+ - Description: Validate JSON payloads against defined schemas
+ - Inputs: JSON object, schema definition
+ - Outputs: Validation result (pass/fail) + error details
+ - Behavior: Iterate fields, check types, enforce constraints
+
+ Feature: Business rule validation
+ - Description: Apply domain-specific validation rules
+ - Inputs: Validated data object, rule set
+ - Outputs: Boolean + list of violated rules
+ - Behavior: Execute rules sequentially, short-circuit on failure
+
+
+
+Capability: validation.js
+ (Problem: This is a FILE, not a CAPABILITY. Mixing structure into functional thinking.)
+
+Capability: Validation
+ Feature: Make sure data is good
+ (Problem: Too vague. No inputs/outputs. Not actionable.)
+
+
+
+## Capability Tree
+
+### Capability: [Name]
+[Brief description of what this capability domain covers]
+
+#### Feature: [Name]
+- **Description**: [One sentence]
+- **Inputs**: [What it needs]
+- **Outputs**: [What it produces]
+- **Behavior**: [Key logic]
+
+#### Feature: [Name]
+- **Description**:
+- **Inputs**:
+- **Outputs**:
+- **Behavior**:
+
+### Capability: [Name]
+...
+
+
+
+---
+
+
+
+NOW think about code organization. Map capabilities to actual file/folder structure.
+
+Rules:
+1. Each capability maps to a module (folder or file)
+2. Features within a capability map to functions/classes
+3. Use clear module boundaries - each module has ONE responsibility
+4. Define what each module exports (public interface)
+
+The goal: Create a clear mapping between "what it does" (functional) and "where it lives" (structural).
+
+
+Capability: Data Validation
+ → Maps to: src/validation/
+ ├── schema-validator.js (Schema validation feature)
+ ├── rule-validator.js (Business rule validation feature)
+ └── index.js (Public exports)
+
+Exports:
+ - validateSchema(data, schema)
+ - validateRules(data, rules)
+
+
+
+Capability: Data Validation
+ → Maps to: src/utils.js
+ (Problem: "utils" is not a clear module boundary. Where do I find validation logic?)
+
+Capability: Data Validation
+ → Maps to: src/validation/everything.js
+ (Problem: One giant file. Features should map to separate files for maintainability.)
+
+
+
+## Repository Structure
+
+```
+project-root/
+├── src/
+│ ├── [module-name]/ # Maps to: [Capability Name]
+│ │ ├── [file].js # Maps to: [Feature Name]
+│ │ └── index.js # Public exports
+│ └── [module-name]/
+├── tests/
+└── docs/
+```
+
+## Module Definitions
+
+### Module: [Name]
+- **Maps to capability**: [Capability from functional decomposition]
+- **Responsibility**: [Single clear purpose]
+- **File structure**:
+ ```
+ module-name/
+ ├── feature1.js
+ ├── feature2.js
+ └── index.js
+ ```
+- **Exports**:
+ - `functionName()` - [what it does]
+ - `ClassName` - [what it does]
+
+
+
+---
+
+
+
+This is THE CRITICAL SECTION for Task Master parsing.
+
+Define explicit dependencies between modules. This creates the topological order for task execution.
+
+Rules:
+1. List modules in dependency order (foundation first)
+2. For each module, state what it depends on
+3. Foundation modules should have NO dependencies
+4. Every non-foundation module should depend on at least one other module
+5. Think: "What must EXIST before I can build this module?"
+
+
+Foundation Layer (no dependencies):
+ - error-handling: No dependencies
+ - config-manager: No dependencies
+ - base-types: No dependencies
+
+Data Layer:
+ - schema-validator: Depends on [base-types, error-handling]
+ - data-ingestion: Depends on [schema-validator, config-manager]
+
+Core Layer:
+ - algorithm-engine: Depends on [base-types, error-handling]
+ - pipeline-orchestrator: Depends on [algorithm-engine, data-ingestion]
+
+
+
+- validation: Depends on API
+- API: Depends on validation
+(Problem: Circular dependency. This will cause build/runtime issues.)
+
+- user-auth: Depends on everything
+(Problem: Too many dependencies. Should be more focused.)
+
+
+
+## Dependency Chain
+
+### Foundation Layer (Phase 0)
+No dependencies - these are built first.
+
+- **[Module Name]**: [What it provides]
+- **[Module Name]**: [What it provides]
+
+### [Layer Name] (Phase 1)
+- **[Module Name]**: Depends on [[module-from-phase-0], [module-from-phase-0]]
+- **[Module Name]**: Depends on [[module-from-phase-0]]
+
+### [Layer Name] (Phase 2)
+- **[Module Name]**: Depends on [[module-from-phase-1], [module-from-foundation]]
+
+[Continue building up layers...]
+
+
+
+---
+
+
+
+Turn the dependency graph into concrete development phases.
+
+Each phase should:
+1. Have clear entry criteria (what must exist before starting)
+2. Contain tasks that can be parallelized (no inter-dependencies within phase)
+3. Have clear exit criteria (how do we know phase is complete?)
+4. Build toward something USABLE (not just infrastructure)
+
+Phase ordering follows topological sort of dependency graph.
+
+
+Phase 0: Foundation
+ Entry: Clean repository
+ Tasks:
+ - Implement error handling utilities
+ - Create base type definitions
+ - Setup configuration system
+ Exit: Other modules can import foundation without errors
+
+Phase 1: Data Layer
+ Entry: Phase 0 complete
+ Tasks:
+ - Implement schema validator (uses: base types, error handling)
+ - Build data ingestion pipeline (uses: validator, config)
+ Exit: End-to-end data flow from input to validated output
+
+
+
+Phase 1: Build Everything
+ Tasks:
+ - API
+ - Database
+ - UI
+ - Tests
+ (Problem: No clear focus. Too broad. Dependencies not considered.)
+
+
+
+## Development Phases
+
+### Phase 0: [Foundation Name]
+**Goal**: [What foundational capability this establishes]
+
+**Entry Criteria**: [What must be true before starting]
+
+**Tasks**:
+- [ ] [Task name] (depends on: [none or list])
+ - Acceptance criteria: [How we know it's done]
+ - Test strategy: [What tests prove it works]
+
+- [ ] [Task name] (depends on: [none or list])
+
+**Exit Criteria**: [Observable outcome that proves phase complete]
+
+**Delivers**: [What can users/developers do after this phase?]
+
+---
+
+### Phase 1: [Layer Name]
+**Goal**:
+
+**Entry Criteria**: Phase 0 complete
+
+**Tasks**:
+- [ ] [Task name] (depends on: [[tasks-from-phase-0]])
+- [ ] [Task name] (depends on: [[tasks-from-phase-0]])
+
+**Exit Criteria**:
+
+**Delivers**:
+
+---
+
+[Continue with more phases...]
+
+
+
+---
+
+
+
+Define how testing will be integrated throughout development (TDD approach).
+
+Specify:
+1. Test pyramid ratios (unit vs integration vs e2e)
+2. Coverage requirements
+3. Critical test scenarios
+4. Test generation guidelines for Surgical Test Generator
+
+This section guides the AI when generating tests during the RED phase of TDD.
+
+
+Critical Test Scenarios for Data Validation module:
+ - Happy path: Valid data passes all checks
+ - Edge cases: Empty strings, null values, boundary numbers
+ - Error cases: Invalid types, missing required fields
+ - Integration: Validator works with ingestion pipeline
+
+
+
+## Test Pyramid
+
+```
+ /\
+ /E2E\ ← [X]% (End-to-end, slow, comprehensive)
+ /------\
+ /Integration\ ← [Y]% (Module interactions)
+ /------------\
+ / Unit Tests \ ← [Z]% (Fast, isolated, deterministic)
+ /----------------\
+```
+
+## Coverage Requirements
+- Line coverage: [X]% minimum
+- Branch coverage: [X]% minimum
+- Function coverage: [X]% minimum
+- Statement coverage: [X]% minimum
+
+## Critical Test Scenarios
+
+### [Module/Feature Name]
+**Happy path**:
+- [Scenario description]
+- Expected: [What should happen]
+
+**Edge cases**:
+- [Scenario description]
+- Expected: [What should happen]
+
+**Error cases**:
+- [Scenario description]
+- Expected: [How system handles failure]
+
+**Integration points**:
+- [What interactions to test]
+- Expected: [End-to-end behavior]
+
+## Test Generation Guidelines
+[Specific instructions for Surgical Test Generator about what to focus on, what patterns to follow, project-specific test conventions]
+
+
+
+---
+
+
+
+Describe technical architecture, data models, and key design decisions.
+
+Keep this section AFTER functional/structural decomposition - implementation details come after understanding structure.
+
+
+## System Components
+[Major architectural pieces and their responsibilities]
+
+## Data Models
+[Core data structures, schemas, database design]
+
+## Technology Stack
+[Languages, frameworks, key libraries]
+
+**Decision: [Technology/Pattern]**
+- **Rationale**: [Why chosen]
+- **Trade-offs**: [What we're giving up]
+- **Alternatives considered**: [What else we looked at]
+
+
+
+---
+
+
+
+Identify risks that could derail development and how to mitigate them.
+
+Categories:
+- Technical risks (complexity, unknowns)
+- Dependency risks (blocking issues)
+- Scope risks (creep, underestimation)
+
+
+## Technical Risks
+**Risk**: [Description]
+- **Impact**: [High/Medium/Low - effect on project]
+- **Likelihood**: [High/Medium/Low]
+- **Mitigation**: [How to address]
+- **Fallback**: [Plan B if mitigation fails]
+
+## Dependency Risks
+[External dependencies, blocking issues]
+
+## Scope Risks
+[Scope creep, underestimation, unclear requirements]
+
+
+
+---
+
+
+## References
+[Papers, documentation, similar systems]
+
+## Glossary
+[Domain-specific terms]
+
+## Open Questions
+[Things to resolve during development]
+
+
+---
+
+
+# How Task Master Uses This PRD
+
+When you run `task-master parse-prd .txt`, the parser:
+
+1. **Extracts capabilities** → Main tasks
+ - Each `### Capability:` becomes a top-level task
+
+2. **Extracts features** → Subtasks
+ - Each `#### Feature:` becomes a subtask under its capability
+
+3. **Parses dependencies** → Task dependencies
+ - `Depends on: [X, Y]` sets task.dependencies = ["X", "Y"]
+
+4. **Orders by phases** → Task priorities
+ - Phase 0 tasks = highest priority
+ - Phase N tasks = lower priority, properly sequenced
+
+5. **Uses test strategy** → Test generation context
+ - Feeds test scenarios to Surgical Test Generator during implementation
+
+**Result**: A dependency-aware task graph that can be executed in topological order.
+
+## Why RPG Structure Matters
+
+Traditional flat PRDs lead to:
+- ❌ Unclear task dependencies
+- ❌ Arbitrary task ordering
+- ❌ Circular dependencies discovered late
+- ❌ Poorly scoped tasks
+
+RPG-structured PRDs provide:
+- ✅ Explicit dependency chains
+- ✅ Topological execution order
+- ✅ Clear module boundaries
+- ✅ Validated task graph before implementation
+
+## Tips for Best Results
+
+1. **Spend time on dependency graph** - This is the most valuable section for Task Master
+2. **Keep features atomic** - Each feature should be independently testable
+3. **Progressive refinement** - Start broad, use `task-master expand` to break down complex tasks
+4. **Use research mode** - `task-master parse-prd --research` leverages AI for better task generation
+
diff --git a/api/routes/kb_public.py b/api/routes/kb_public.py
index 6e490d2..c8b5df2 100644
--- a/api/routes/kb_public.py
+++ b/api/routes/kb_public.py
@@ -92,8 +92,20 @@ async def list_sources(request: Request):
@router.get("/source/{source_id}/chunks")
-async def source_chunks(source_id: int, request: Request):
- """Browse mode: return all chunks of a single source, ordered."""
+async def source_chunks(
+ source_id: int,
+ request: Request,
+ around: int | None = None,
+ ctx: int = 2,
+):
+ """Browse mode: return chunks of a single source, ordered.
+
+ By default returns all chunks. With `around=&ctx=` it
+ returns only chunks with chunk_index in [around-k, around+k] inclusive,
+ so the search UI can show a matched chunk together with its surrounding
+ sections for context (instead of duplicating the same chunk in both
+ panes when the source has no PDF).
+ """
_verify_auth(request)
from api.services.kb.db import get_pool
pool = await get_pool()
@@ -105,13 +117,26 @@ async def source_chunks(source_id: int, request: Request):
)
if not source:
raise HTTPException(status_code=404, detail="source not found")
- chunks = await conn.fetch(
- """
- SELECT chunk_index, heading_path, section_ref, content, token_count
- FROM kb_chunk WHERE source_id = $1 ORDER BY chunk_index
- """,
- source_id,
- )
+ if around is not None:
+ ctx = max(0, min(ctx, 10))
+ chunks = await conn.fetch(
+ """
+ SELECT chunk_index, heading_path, section_ref, content, token_count
+ FROM kb_chunk
+ WHERE source_id = $1
+ AND chunk_index BETWEEN $2 AND $3
+ ORDER BY chunk_index
+ """,
+ source_id, around - ctx, around + ctx,
+ )
+ else:
+ chunks = await conn.fetch(
+ """
+ SELECT chunk_index, heading_path, section_ref, content, token_count
+ FROM kb_chunk WHERE source_id = $1 ORDER BY chunk_index
+ """,
+ source_id,
+ )
src = dict(source)
if src.get("published_at") is not None:
src["published_at"] = src["published_at"].isoformat()
diff --git a/api/services/kb/search.py b/api/services/kb/search.py
index 288e283..137f799 100644
--- a/api/services/kb/search.py
+++ b/api/services/kb/search.py
@@ -79,7 +79,7 @@ async def _retrieve_rrf(
) u GROUP BY id
)
SELECT
- c.id AS chunk_id,
+ c.id AS chunk_id, c.chunk_index,
s.id AS source_id, s.kind, s.title, s.identifier, s.source_url,
s.published_at, s.effective_at, s.original_path,
c.heading_path, c.section_ref, c.content, c.page_number,
diff --git a/api/services/prompt_builder.py b/api/services/prompt_builder.py
index 0d05e1f..c421e38 100644
--- a/api/services/prompt_builder.py
+++ b/api/services/prompt_builder.py
@@ -49,7 +49,9 @@ TOOL_RULES = (
"- CALL vs MEETING: When user reports they spoke/talked/called someone (שוחחתי, דיברתי, התקשרתי) — use create_call. When user reports a physical meeting or Zoom (נפגשתי, פגישה) — use create_meeting. NEVER use create_meeting for phone calls.\n"
"- OPEN QUESTIONS: If you asked the user a question and they did not answer it, repeat the question at the beginning of your next response. Track open questions until answered.\n"
"- BEHAVIORAL RULES: If assistantRules are provided in the context, you MUST follow them. When user asks to set a persistent rule (\"from now on always...\", \"whenever I say X do Y\"), use save_rule to save it.\n"
- "- DOCUMENTS: When user asks to summarize, analyze, or read a document — first use list_documents to see what files exist, then use read_document with the file path to extract the text.\n"
+ "- DOCUMENTS: Start with list_documents. If it shows files, use read_document / read_multiple_documents with the file paths.\n"
+ "- DOCUMENT DISCOVERY: If list_documents returns 'No documents' with a diagnostic, read the diagnostic. If the folder path is wrong/missing, call find_case_folder(query=) to search storage, pick the best match, then call set_case_folder_path(path=...) to persist it, then list_documents(refresh=true). Use browse_folder(path=...) only as a manual override when find_case_folder doesn't surface the right match.\n"
+ "- NEVER tell the user 'no documents' without first running find_case_folder — the folder might just be mis-mapped.\n"
"- When user asks to summarize multiple documents or the entire case folder — use read_multiple_documents with all relevant file paths.\n"
"- When user asks to rename or organize files — use batch_rename_documents with an array of rename operations.\n"
"- TEMPLATE GENERATION: When user asks to generate/create a document from a template — use generate_from_template. The templateId comes from availableTemplates in your context.\n"
@@ -101,6 +103,15 @@ def build_case_prompt(context: dict, user_profile: str = "", case_memory_notes:
docs_section += f'\n - {fi["name"]} (path: {fi["path"]})'
else:
docs_section = "\n\n=== DOCUMENTS ===\nNo documents"
+ resolved_path = documents.get("resolvedPath")
+ path_source = documents.get("pathSource")
+ folder_exists = documents.get("folderExists")
+ diagnostic = documents.get("diagnostic")
+ if resolved_path or diagnostic:
+ docs_section += f"\nResolvedPath: {resolved_path or '(none)'} | Source: {path_source or '(none)'} | FolderExists: {folder_exists}"
+ if diagnostic:
+ docs_section += f"\nDiagnostic: {diagnostic}"
+ docs_section += "\nRecovery: call list_documents(refresh=true) after a path change, or find_case_folder(query=...) to locate the folder and set_case_folder_path(path=...) to persist it."
# Memory section
ms = case_memory.get("_summary", {})
diff --git a/config/skills/medical-case-analysis/SKILL.md b/config/skills/medical-case-analysis/SKILL.md
new file mode 100644
index 0000000..f07d786
--- /dev/null
+++ b/config/skills/medical-case-analysis/SKILL.md
@@ -0,0 +1,118 @@
+---
+name: medical-case-analysis
+description: ניתוח מסמכים רפואיים בתיק וגיבוש סיפור מקרה מובנה שניתן להעביר ל-law-mate להכנת כתב תביעה או ערעור
+version: 1.0.0
+---
+
+# ניתוח רפואי של תיק → סיפור מקרה ל-law-mate
+
+## מתי להשתמש
+
+- המשתמש מבקש לעבור על המסמכים הרפואיים בתיק.
+- המשתמש אומר "תנתחי את התיק הרפואי", "תכיני לי סיפור מקרה", "תעבירי ל-law-mate", "תבדקי את הוועדות הרפואיות".
+- מדובר בתיקי נכות, תאונות, ביטוח לאומי, ביטוח פרטי, רשלנות רפואית, או כל תיק שבו יש חוות דעת / ועדות / תיק רפואי.
+
+**אין להפעיל את ה-skill הזה אוטומטית בכל שיחה על תיק** — רק כשהמשתמש מבקש במפורש.
+
+## שלב 1 — גילוי המסמכים
+
+הרץ `list_documents`.
+
+- **אם יש מסמכים:** המשך לשלב 2.
+- **אם אין מסמכים (totalFiles=0):** קרא את ה-`Diagnostic` בהודעה. אל תגיד למשתמש "אין מסמכים" מבלי לנסות לחפש.
+ 1. הרץ `find_case_folder` עם שם איש הקשר הראשי (מה-context `contacts[0].name`) או עם מספר התיק.
+ 2. אם יש התאמה אחת ברורה (score ≥ 80) — הצג אותה למשתמש ושאל "האם זו התיקייה של התיק?".
+ 3. אם יש כמה התאמות — הצג טבלה קצרה ובקש לבחור.
+ 4. אחרי אישור: `set_case_folder_path(path=...)` ואז `list_documents(refresh=true)`.
+
+## שלב 2 — סינון המסמכים הרפואיים
+
+עבור על רשימת המסמכים. סווג כ"רפואי" כל קובץ ששמו כולל אחד מהבאים (לא רגיש לאותיות, עברית/אנגלית):
+
+| קטגוריה | מילות מפתח |
+|---|---|
+| ועדות רפואיות | ועדה, ועדת ערר, פרוטוקול ועדה, committee |
+| חוות דעת רפואיות | חוות דעת, חו"ד, חו״ד, opinion |
+| תיק קופ"ח / בי"ח | סיכום אשפוז, discharge, שחרור, תיק רפואי, קופ"ח, מאוחדת, כללית, מכבי, לאומית |
+| בדיקות | בדיקה, MRI, CT, רנטגן, אולטרסאונד, ultrasound, EMG |
+| ביטוח לאומי | ביטוח לאומי, בל"ל, החלטה, ועדה רפואית מל"ל |
+| אחר רפואי | רופא, תעודה רפואית, דו"ח, אישור מחלה |
+
+הצג למשתמש את הרשימה המסוננת וכמה מסמכים שאין בה, ובקש אישור לפני קריאה (כדי לא לחרוג ב-tokens).
+
+## שלב 3 — קריאה וחילוץ
+
+`read_multiple_documents(filePaths=[...])` על כל המסמכים הרפואיים שסווגו. אם הרשימה ארוכה מ-10 קבצים — חלק לבאטצ'ים של 5-7 ושמור סיכומי ביניים ב-`save_case_memory` עם `category="documents_notes"`.
+
+לכל מסמך, חלץ ל-working notes:
+
+- **תאריך המסמך** (מהמסמך עצמו; אם חסר — ציין "לא מצוין").
+- **מקור** (שם בית חולים / קופ"ח / רופא / ועדה).
+- **אבחנה/ממצא עיקרי** (במילים של המסמך, לא פרשנות שלך).
+- **אחוזי נכות / אובדן כושר** אם מופיעים (כולל צירוף אחוזים, זמני/קבוע).
+- **המלצות טיפוליות / פעולות שדורשות המשך** אם מופיעות.
+- **ציטוט מפתח** אחד קצר (כדי שיהיה מה להצמיד לכתב התביעה).
+
+## שלב 4 — שאלות מובנות למשתמש
+
+לפני שכותבים סיפור מקרה, צריך מידע שלא נמצא במסמכים הרפואיים. שאל את המשתמש בסדר הזה, **שאלה אחת בכל פעם** (אל תציף):
+
+1. **נסיבות:** "מה הנסיבות המדויקות של האירוע / התאונה / תחילת המצב הרפואי? תאריך, מקום, מי היה מעורב."
+2. **תלונות סובייקטיביות:** "אילו כאבים / מגבלות / סימפטומים הלקוח מדווח עליהם היום?"
+3. **השפעה תפקודית:** "איך זה משפיע על חיי היומיום? עבודה, שינה, טיפול עצמי, חיי משפחה."
+4. **טיפול נוכחי:** "איזה טיפול רפואי הוא מקבל כרגע? תרופות, פיזיותרפיה, מעקב?"
+5. **מצב קודם:** "האם היו מחלות / פציעות קודמות רלוונטיות לאותו אזור?"
+6. **מסמכים חסרים:** הצג רשימת מסמכים שחסרים לפי מה שהיית מצפה לראות (לדוגמה: "לא מצאתי חוות דעת עדכנית מרופא אורתופד — יש כזו?").
+
+אחרי כל תשובה — שמור דרך `save_case_memory(category="key_facts", ...)`.
+
+## שלב 5 — סיפור מקרה (הפלט ל-law-mate)
+
+אחרי השאלות, הצג למשתמש סיכום בפורמט הזה (markdown, בעברית, ישיר — זה הטקסט שיועתק ל-law-mate):
+
+```markdown
+# סיפור מקרה — [שם הלקוח] (תיק #[מספר])
+
+## 1. נסיבות האירוע
+[פסקה של 3-5 משפטים בהתבסס על תשובת המשתמש לשאלה 1]
+
+## 2. ציר זמן רפואי
+| תאריך | גורם | ממצא/אבחנה |
+|---|---|---|
+| ... | ... | ... |
+
+## 3. ממצאים רפואיים מרכזיים
+- [ממצא 1] — [מקור, ציטוט קצר]
+- [ממצא 2] — ...
+- [אחוזי נכות שנקבעו, אם יש]
+
+## 4. תלונות סובייקטיביות והשפעה תפקודית
+[3-4 שורות מתשובות המשתמש לשאלות 2-3]
+
+## 5. טיפול נוכחי
+[תשובת המשתמש לשאלה 4]
+
+## 6. טענות משפטיות אפשריות (לבדיקה ב-law-mate)
+- [שאלה משפטית 1 — לדוגמה: "האם מוצדק ערעור על 20% נכות?"]
+- [שאלה משפטית 2]
+
+## 7. מסמכים שעדיין חסרים
+- [רשימה]
+
+## 8. ציטוטים מרכזיים מהמסמכים הרפואיים
+> "..."
+> — [שם המסמך, תאריך]
+```
+
+אחרי הצגת הסיכום, שאל את המשתמש: "להעתיק ל-law-mate? או שיש משהו להוסיף/לתקן?"
+
+## שלב 6 — שמירה לזיכרון התיק
+
+בסוף, שמור את הסיפור כ-`save_case_memory(category="strategy", name="סיפור מקרה לניתוח ב-law-mate", content=<הסיפור המלא>, importance="high")` כדי שהשיחה הבאה תוכל להמשיך מאותה נקודה.
+
+## כללים ואזהרות
+
+- **אל תמציא ממצאים רפואיים**. אם משהו לא כתוב במסמכים — ציין "לא מצוין במסמכים" במקום לנחש.
+- **אל תחרוג לפרשנות משפטית עצמאית** — מטרת ה-skill היא להכין את החומר ל-law-mate שיעשה את הניתוח.
+- **אחוזי נכות** — הצג תמיד כפי שהם כתובים במסמך (למשל "20% נכות כללית זמנית עד 31/12/2026"), לא כמספר בודד.
+- **שפה** — עברית בלבד בפלט ובשיחה עם המשתמש.