# Implementation Plan: Filament JSON UI for Policy Views

**Branch**: `tenantpilot-v1` | **Date**: 2025-12-13 | **Spec**: [spec.md](./spec.md)
**Input**: Feature specification from `/specs/002-filament-json/spec.md`

## Summary

Improve readability of policy snapshots and settings in the admin UI by integrating `pepperfm/filament-json:^4` as a read-only JSON viewer component. Primary target is the **Policies → View Policy** page where raw JSON is currently hard to scan. This is a **UI-only feature** with no changes to sync, backup, restore logic, or Graph integration.

Key deliverables:
- JSON viewer component (fold/collapse, search, copy) on Policy View page
- Large payload handling (warnings, truncation, optional download)
- Preserve existing table views where appropriate (Settings Catalog)
- Tab-based UI: Settings (table) + JSON (viewer)
- Read-only display with no behavioral changes

## Technical Context

**Language/Version**: PHP 8.4.15  
**Primary Dependencies**: 
- Laravel 12
- Filament 4
- Livewire 3
- `pepperfm/filament-json:^4` (to be installed)

**Storage**: PostgreSQL (existing, no schema changes)  
**Testing**: Pest 4 (feature + browser tests)  
**Target Platform**: Web (Laravel Sail locally, Dokploy deployment)  
**Project Type**: Web application (Laravel + Filament admin panel)  
**Performance Goals**: 
- Render JSON up to 500 KB inline without freezing
- Large payloads (>500 KB) show warning + collapsed by default
- No additional Graph API calls

**Constraints**: 
- Read-only viewer (no editing/saving)
- Tenant-scoped (all actions respect current tenant context)
- No horizontal overflow beyond card bounds
- Must preserve existing Settings Catalog table functionality

**Scale/Scope**: 
- Single page modification: Policy View (PolicyResource ViewRecord)
- Optional: Policy Versions View (raw JSON section only)
- ~3-5 Filament infolist entries/components
- Asset publishing: document if `public/vendor/` assets must be committed

## Constitution Check

*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*

### I. Safety-First Design
- ✅ **PASS**: Read-only viewer, no destructive actions
- ✅ **PASS**: No changes to backup/restore/sync logic (FR-040)
- ✅ **PASS**: Large payload warnings prevent browser freeze (FR-038, NFR-036.1)

### II. Immutable Versioning
- ✅ **PASS**: No changes to versioning or snapshot storage
- ✅ **PASS**: Viewer displays existing snapshot data only (NFR-036.4)

### III. Defensive Restore
- ✅ **PASS**: No restore flow changes

### IV. Auditability
- ✅ **PASS**: No new audit requirements (FR-040)
- ✅ **PASS**: Copy/download actions use existing tenant-scoped records (NFR-036.3)

### V. Tenant-Aware Architecture
- ✅ **PASS**: All UI operates within tenant context (NFR-036.3)
- ✅ **PASS**: No cross-tenant data exposure

### VI. Graph Abstraction
- ✅ **PASS**: No new Graph calls (FR-040)
- ✅ **PASS**: No token storage changes

### VII. Spec-Driven Development
- ✅ **PASS**: Spec complete with 6 FRs, 3 user stories, 7 success criteria
- ✅ **PASS**: Exclusions documented (no global refactor, no editor mode)

**GATE STATUS**: ✅ **ALL GATES PASS** — Proceed to Phase 0

---

## Project Structure

### Documentation (this feature)

```text
specs/002-filament-json/
├── plan.md              # This file
├── research.md          # Phase 0: Package compatibility, asset publishing, integration patterns
├── data-model.md        # Phase 1: N/A (no schema changes)
├── quickstart.md        # Phase 1: Installation, usage examples
├── contracts/           # Phase 1: N/A (no API contracts)
└── tasks.md             # Phase 2: Task breakdown (created by /speckit.tasks)
```

### Source Code (repository root)

```text
app/
├── Filament/
│   └── Resources/
│       └── PolicyResource/
│           └── Pages/
│               └── ViewPolicy.php        # Primary modification target
├── View/
│   └── Components/
│       └── JsonViewer.php                # Optional: Blade component wrapper (if needed)

resources/
└── views/
    └── filament/
        └── resources/
            └── policy-resource/
                └── pages/
                    └── view-policy.blade.php   # If custom view needed

tests/
├── Feature/
│   └── Filament/
│       └── PolicyResourceViewTest.php    # Feature tests for Policy View UI
└── Browser/
    └── PolicyJsonViewerTest.php          # Pest 4 browser tests

config/
└── (no changes expected)

database/
└── (no changes - UI only)

public/
└── vendor/
    └── filament-json/                    # May appear after asset publishing
        └── (CSS/JS assets)
```

**Structure Decision**: Laravel web application with Filament admin panel. Modifications are scoped to:
1. `app/Filament/Resources/PolicyResource/Pages/ViewPolicy.php` (primary)
2. Optional custom Blade views if Filament infolist schema is insufficient
3. Tests in `tests/Feature/Filament/` and `tests/Browser/`

No database migrations, no new models, no service layer changes.

---

## Complexity Tracking

> **Fill ONLY if Constitution Check has violations that must be justified**

| Violation | Why Needed | Simpler Alternative Rejected Because |
|-----------|------------|-------------------------------------|
| *(none)*  | *(none)*   | *(none)*                           |

**Justification**: All constitution gates pass. This is a low-risk UI enhancement with no architectural deviations.

---

## Phase 0: Research & Prerequisites

**Goal**: Resolve all NEEDS CLARIFICATION items and gather integration patterns.

### Research Tasks

1. **Package Compatibility**
   - ✅ Verify `pepperfm/filament-json:^4` is Filament 4 compatible
   - ✅ Check if it supports **infolists** (read-only views) vs. forms
   - ✅ Identify available features: fold/collapse, search, copy, line numbers

2. **Asset Publishing**
   - ✅ Determine if `php artisan filament:assets` or similar is required
   - ✅ Check if published assets should be committed or generated during deployment
   - ✅ Test if assets work without explicit publishing (auto-serve from vendor)

3. **Integration Patterns**
   - ✅ Find best practice for adding JSON viewer to Filament infolist
   - ✅ Identify how to implement tabs (Settings table + JSON viewer)
   - ✅ Determine payload size detection method (string length, JSON byte count)

4. **Large Payload Handling**
   - ✅ Establish truncation strategy (client-side vs. server-side)
   - ✅ Identify safe download mechanism (streaming response, tenant-scoped)

5. **Testing Strategy**
   - ✅ Confirm Pest 4 browser tests can interact with Filament infolists
   - ✅ Check if Livewire testing helpers cover tab switching

**Output**: `research.md` with decisions, alternatives, and example code snippets.

---

## Phase 1: Design & Contracts

**Prerequisites**: Phase 0 research complete

### Design Artifacts

1. **Data Model** (`data-model.md`)
   - **N/A** — No schema changes. Document that feature uses existing `Policy` model's `snapshot` column.

2. **API Contracts** (`contracts/`)
   - **N/A** — No API endpoints. UI-only feature.

3. **Quickstart Guide** (`quickstart.md`)
   - Installation: `composer require pepperfm/filament-json:^4`
   - Asset publishing (if required): `php artisan vendor:publish --tag=filament-json-assets`
   - Usage example: How to add JSON viewer to PolicyResource ViewPolicy page
   - Configuration: Payload size thresholds (500 KB soft limit)
   - Testing: Run `./vendor/bin/pest --filter=PolicyJsonViewer`

4. **Component Design**
   - Filament infolist entry: `ViewEntry::make('snapshot')` with custom view rendering `pepperfm/filament-json` component
   - Tab structure: `Tabs::make()` with `Tab::make('Settings')` and `Tab::make('JSON')`
   - Payload size check: `strlen(json_encode($record->snapshot)) > 512000` (500 KB)
   - Warning badge: Filament `Badge::make()` with warning color

**Output**: 
- `quickstart.md`: Installation, usage, testing
- `data-model.md`: Brief note that no schema changes are needed
- Updated agent context (if new technology added)

---

## Phase 2: Task Breakdown

**Output**: `tasks.md` (created by `/speckit.tasks` command, NOT by `/speckit.plan`)

### Anticipated Task Categories

1. **Setup & Dependencies** (1-2 tasks)
   - Install `pepperfm/filament-json:^4`
   - Publish assets (if required) and document process

2. **Policy View UI Modification** (3-5 tasks)
   - Add JSON viewer component to ViewPolicy infolist
   - Implement tabs: Settings (table) + JSON (viewer)
   - Add large payload detection + warning badge
   - Implement copy-to-clipboard action
   - Optional: Add "Download JSON" action for large payloads

3. **Styling & Layout** (2-3 tasks)
   - Prevent horizontal overflow
   - Ensure monospace font, line wrapping
   - Match Filament section padding/spacing
   - Test dark mode compatibility

4. **Testing** (3-4 tasks)
   - Feature test: Verify JSON viewer renders with snapshot data
   - Feature test: Large payload shows warning, no freeze
   - Browser test: Tab switching works (Pest 4)
   - Browser test: Copy button populates clipboard

5. **Documentation** (1-2 tasks)
   - Update `README.md` or in-app help (if applicable)
   - Document asset publishing in deployment notes

6. **Validation** (1 task)
   - Run `./vendor/bin/pest` and `./vendor/bin/pint --dirty`
   - Verify no backup/restore test failures (SC-005)

**Estimated Complexity**: 10-15 tasks total

---

## Constitution Check (Post-Design)

*Re-evaluate after Phase 1 design is complete.*

### Design Compliance Review

- ✅ **Safety-First**: Read-only viewer, large payload warnings implemented
- ✅ **Immutable Versioning**: No changes to snapshot storage or versioning logic
- ✅ **Defensive Restore**: No restore flow modifications
- ✅ **Auditability**: No new audit requirements; tenant-scoped actions preserved
- ✅ **Tenant-Aware**: All UI respects current tenant context
- ✅ **Graph Abstraction**: No new Graph calls or token management
- ✅ **Spec-Driven**: Design artifacts align with spec (FR-036 to FR-041, NFR-036.1 to NFR-036.5)

**POST-DESIGN GATE STATUS**: ✅ **ALL GATES PASS**

---

## Implementation Sequence

1. **Phase 0 (Research)**: 
   - Run research agents for package compatibility, asset publishing, integration patterns
   - Consolidate findings in `research.md`

2. **Phase 1 (Design)**:
   - Create `quickstart.md` with installation/usage examples
   - Document payload size thresholds and tab structure
   - Update agent context (if needed)

3. **Phase 2 (Task Generation)**:
   - Execute `/speckit.tasks` to generate `tasks.md`
   - Review task breakdown for completeness (FR coverage, NFR validation)

4. **Phase 3 (Implementation)** *(outside of /speckit.plan scope)*:
   - Execute tasks sequentially
   - Run tests after each UI modification
   - Validate no existing functionality breaks

5. **Phase 4 (Validation)** *(outside of /speckit.plan scope)*:
   - Full test suite: `./vendor/bin/pest`
   - Code style: `./vendor/bin/pint --dirty`
   - Manual QA: Large payloads, tab switching, copy actions
   - Deploy to Staging, validate before Production

---

## Risks & Mitigations

| Risk | Impact | Mitigation |
|------|--------|------------|
| **Asset publishing floods `public/`** | Large commit, slow CI | Document whether to commit assets or rely on deploy build steps; test auto-serving from vendor |
| **Browser freeze on large JSON** | Poor UX | Implement 500 KB soft limit, show warning + collapsed by default (NFR-036.1) |
| **Plugin incompatible with infolists** | Blocker | Phase 0 research must confirm infolist support; fallback to custom Blade component if needed |
| **Horizontal overflow breaks layout** | UX degradation | Add CSS constraints: `max-width: 100%; overflow-wrap: break-word;` (NFR-036.5) |
| **Existing Settings Catalog table broken** | Regression | Keep table as default tab, JSON as secondary; run existing tests (SC-005) |

---

## Success Criteria Validation

| Criterion | Validation Method | Phase |
|-----------|-------------------|-------|
| **SC-001**: JSON viewer visible on Policy View | Feature test: `assertSee('JSON')` | Phase 3 |
| **SC-002**: No content overflow | Browser test: Check card bounds | Phase 3 |
| **SC-003**: Large payload warning shown | Feature test: Mock 600 KB snapshot | Phase 3 |
| **SC-004**: Settings Catalog table usable | Feature test: Existing tests pass | Phase 3 |
| **SC-005**: No backup/restore changes | Pest suite: All tests pass | Phase 4 |
| **SC-006**: Build/CI passes | Terminal: `./vendor/bin/pest && ./vendor/bin/pint --dirty` | Phase 4 |
| **SC-007**: No unintended asset commits | Git diff review | Phase 3 |

---

## Definition of Done

- ✅ All 6 functional requirements (FR-036 to FR-041) implemented
- ✅ All 5 non-functional requirements (NFR-036.1 to NFR-036.5) validated
- ✅ 3 user stories tested (US-UI-01, US-UI-02, US-UI-03)
- ✅ Feature tests + Browser tests (Pest 4) passing
- ✅ Code style validated (`./vendor/bin/pint --dirty`)
- ✅ No regressions in backup/restore/sync tests
- ✅ Asset publishing documented (commit decision made)
- ✅ Quickstart guide complete
- ✅ Deployment impact assessed (Staging validation required)

---

## Next Steps

1. Execute Phase 0 research tasks → Generate `research.md`
2. Execute Phase 1 design tasks → Generate `quickstart.md`
3. Run `/speckit.tasks` to generate task breakdown
4. Begin implementation following generated tasks

**Branch Ready**: ✅ `tenantpilot-v1`  
**Spec Complete**: ✅ [spec.md](./spec.md)  
**Plan Complete**: ✅ This file
