# GPS Legal — System Journal

> Living document. Updated as decisions are made and architecture evolves.
> Last updated: 2026-05-06

---

## Purpose

This journal records key architectural decisions, the reasoning behind them, and the direction of the system. It is the authoritative reference for anyone building on this codebase — human or AI.

---

## Core Philosophy

### 1. Forecast → Confirm → Learn

The system never acts autonomously on client-affecting events. It forecasts, proposes, and waits for attorney confirmation. Every confirmation, correction, or rejection is a training signal.

```
AI forecasts obligation / action
    ↓
UI shows proposal to attorney
    ↓
Attorney: Accept | Edit | Reject
    ↓
Confirmed → scheduled, executed by agents
Edited    → correction logged (what changed, why)
Rejected  → reason logged
    ↓
Fine-tuning pipeline learns from the delta
```

This pattern applies everywhere:
- Deadline forecasting (90-day reports, visa renewals, etc.)
- Form field mappings after calibration
- Case strategy suggestions from Case Analyst
- Billing estimates
- Document classification

Year 1: frequent corrections. Year 3: system predicts better than a new associate.

### 2. Chain of Command — No Exceptions

Every agent has exactly one set of callers and one set of callees. No sideways communication. No skipping levels. Breaking the chain creates spider-webbing that becomes unmaintainable.

### 3. Generic Agents, Specific Knowledge

Agents contain no hardcoded legal rules. All domain knowledge lives in `law_corpus` (maintained by RAG Agent). Agents reason over whatever is in the corpus — making them automatically applicable to any practice area, jurisdiction, or matter type without code changes.

---

## The 10 Agents

| # | Agent | Role | Status |
|---|---|---|---|
| 1 | Prompt Analyst | Sole attorney UI entry point. Reads request, calls Doc Classifier, routes to Case Analyst or Comms Agent. Delegates only — never touches data. | Built |
| 2 | Onboarding Agent | All new data in. Peer to Prompt Analyst (not subordinate). Validates, conflict-checks, hands off to Prompt Analyst. Never writes client records directly. | Not built |
| 3 | Document Classifier | Called by Prompt Analyst before any routing. Returns type, matter ref, practice area, recommended action. Classification before routing — not optional. | Built |
| 4 | Case/Situation Analyst | Receives pre-classified requests from Prompt Analyst OR proactive pushes from Client Manager. Coordinates all specialist agents. Two jobs: (1) assess situation, (2) check if rules have changed via RAG. | Built (attorney-initiated only — proactive path not yet wired) |
| 5 | Client Manager | One per client. Owns the client folder and all active matters. Sets the tempo — monitors accounts, generates forecasted obligation timelines, pushes to Case Analyst when action is needed. | Not built |
| 6 | Comms Agent | Parallel track. Pure executor — receives fully packaged tasks from Case Analyst (who, what, when, channel). Never reads client folders directly. LINE + email + calendar. | Not built |
| 7 | RAG Agent | Two jobs: (1) Thai govt form retrieval + calibration, (2) law/statute/circular retrieval into law_corpus. Called by Case Analyst with a domain-scoped query only. | Built |
| 8 | Billing Agent | Deterministic rules only. Retainers, trust, invoicing, AR. Called by Case Analyst. | Not built as agent (billing data exists) |
| 9 | Judicial Intelligence | Career-long profiles on judges + court support teams. Cross-matter, cumulative. Called by Case Analyst. | Not built |
| 10 | Adversary Intelligence | Career-long profiles on opposing counsel, firms, AND govt officers/examiners (BOI, immigration, land office). Called by Case Analyst. | Not built |

---

## Strict Caller Table

```
CALLER                  MAY CALL                        MAY NOT CALL
─────────────────────────────────────────────────────────────────────────
Prompt Analyst          Doc Classifier                  Anyone below Case Analyst
                        Case Analyst
                        Comms Agent

Case Analyst            Client Manager                  Prompt Analyst
                        RAG Agent                       Comms Agent (except for
                        Billing Agent                   proactive/deadline tasks)
                        Judicial Intelligence           Onboarding Agent
                        Adversary Intelligence

Client Manager          Case Analyst (push only)        Any other agent
                        Data store (own client only)

Comms Agent             External channels only          Any agent or data store
                        (LINE, email, calendar)

Everyone else           Data store only                 Any agent
```

---

## Two Execution Tracks

### Track 1 — Attorney-Initiated (series)
```
Attorney → Prompt Analyst → [Doc Classifier] → Case Analyst
  → Client Manager + specialists → Case Analyst → Prompt Analyst → Attorney
```

### Track 2 — Proactive / Deadline-Driven (internally triggered)
```
Client Manager (clock)
  → detects upcoming obligation
  → pushes to Case Analyst
      → 1. assess current case status
      → 2. call RAG Agent: have rules changed?
      → 3. package task → Comms Agent
          → executes (LINE/email to client + attorney)
```

Prompt Analyst is NOT in Track 2. This is an internal system flow, not an attorney request.

---

## Deadline & Obligation System

### How it works

1. **RAG Agent** stores structured obligation entries in `law_corpus`:
   ```
   { matterType: "retirement_visa", obligation: "90-day report",
     anchorField: "arrivalDate", intervalDays: 90,
     leadTimeDays: 7, linkedForms: ["TM.47"] }
   ```

2. **Client Manager** reads matter types + client dates → queries law_corpus → generates `MatterDeadline[]` records (status: `proposed`)

3. **UI shows proposed events** to attorney per matter:
   - Accept | Edit | Reject per event
   - Edit = inline adjustment (date, form, reminder lead time)
   - Reject = prompt for reason
   - All actions logged as training data

4. **Confirmed events** enter the live timeline → Client Manager monitors → pushes to Case Analyst as deadlines approach

5. **Case Analyst** checks for rule changes → packages task → Comms Agent executes reminder

### Why attorney confirmation is required

- Law changes faster than the corpus updates
- Firm-specific practices differ from the general rule
- Every correction is a training signal that improves future forecasts
- Attorney remains professionally responsible — system is a tool, not a decision-maker

### MatterDeadline schema (to be built)
```typescript
{
  matterId, clientFolderId,
  obligationKey,       // e.g. "90_day_report"
  description,
  dueDate,             // calculated from anchor + interval
  anchorDate,          // the actual date used (arrivalDate value)
  intervalDays,        // for recurring
  recurringNext,       // next instance after this one
  linkedFormIds[],
  reminderLeadDays,
  status: 'proposed' | 'confirmed' | 'rejected' | 'sent' | 'completed',
  proposedBy: 'system',
  confirmedBy,         // attorney userId
  confirmedAt,
  rejectionReason,     // training signal
  editDelta,           // JSON diff if attorney edited before confirming
  source: 'law_corpus_id',
}
```

---

## Learning Pipeline

The confirm/edit/reject pattern feeds the weekly fine-tuning pipeline on Workbeast.

Training signals collected:
- What the system proposed vs. what the attorney confirmed
- Edit deltas (changed date, changed form, changed lead time — why?)
- Rejection reasons
- Steps the attorney added that the system didn't forecast

Over time the model learns:
- Firm-specific timing preferences
- Practice-area nuances (this firm's property matters follow a different sequence)
- Client-specific patterns (this client always needs an extra 14 days lead time)

---

## UI Pattern — Propose & Confirm

Used consistently throughout the system. Never auto-act on attorney-affecting decisions.

Components needed:
- `ProposedEventCard` — shows forecast with Accept/Edit/Reject
- `TimelineView` — per-matter forward-looking calendar of confirmed + proposed events
- `FirmCalendarView` — all upcoming deadlines across all active matters

---

## Key File Locations

### Backend (legal-service — port 3200)
```
src/agent/prompt-analyst.service.ts
src/agent/case-analyst.service.ts
src/agent/agent-tools.service.ts
src/document-classifier/document-classifier.service.ts
src/rag-agent/rag-agent.service.ts
src/form-templates/form-templates.service.ts
src/form-templates/form-calibration.agent.ts
src/form-templates/stock-library.ts
src/workflows/workflows.service.ts
src/common/schemas.ts                    ← all Mongoose schemas
```

### Frontend (Next.js — port 3100)
```
src/views/form-templates/FormTemplatesView.tsx
src/views/workflows/WorkflowsView.tsx
src/views/workflows/WorkflowBuilderView.tsx   ← flowchart builder (React Flow)
src/views/dashboard/AgentProgressBar.tsx
src/views/dashboard/AgentActivityCard.tsx
src/views/dashboard/AiAssistantCard.tsx
src/views/dashboard/toolActivityMap.ts
src/app/api/                                  ← Next.js proxy routes to legal-service
```

### Training pipeline (Workbeast)
```
~/ai-learning/scripts/finetune.py
~/ai-learning/scripts/weekly_finetune.sh
~/ai-learning/training-data/
```

---

## Build Queue (next up)

1. `MatterDeadline` schema
2. Client Manager agent (generic — reads law_corpus, generates proposed deadlines)
3. Proposed Events UI (per-matter timeline, Accept/Edit/Reject)
4. Comms Agent (LINE + email executor, receives tasks from Case Analyst only)
5. Wire proactive track: Client Manager → Case Analyst → Comms Agent
6. Firm-wide deadline calendar view

---

## Open Design Questions

1. **Comms Agent sub-contracts** — email triage, scheduling, LINE, calendar not yet fully mapped per task type
2. **Onboarding Agent** — conflict check logic, bulk import format not designed
3. **Matter close pipeline** — at close, Case Analyst triggers Client Manager to extract intelligence for Judicial + Adversary Intel. Not yet designed.
4. **party_type: official** on Adversary Intel — BOI officers, immigration examiners, land office staff need their own sub-schema
5. **Mobile app document scan** — should trigger Onboarding Agent / Document Classifier chain, currently just uploads

---

## Decision Log

| Date | Decision | Reason |
|---|---|---|
| 2026-05-06 | Workflow builder uses React Flow canvas | Expert-built first template, advanced tenant UI long-term |
| 2026-05-06 | Deadline system uses Forecast→Confirm→Learn loop | Attorney confirmation required; corrections become training data |
| 2026-05-06 | Client Manager pushes to Case Analyst (not Comms directly) | Preserves chain of command; Case Analyst checks for rule changes before action |
| 2026-05-06 | Generic agents, specific knowledge in law_corpus | No hardcoded rules per practice area; RAG agent maintains corpus |
| 2026-05-06 | Prompt Analyst excluded from proactive deadline track | Internal system flow, not attorney-initiated; no need for entry point agent |
| 2026-04-20 | 10-agent hierarchy confirmed | Clean separation of concerns, no sideways communication |
