# Periderm CLI

The Periderm CLI scans your repo for the things that quietly lose users or get you in legal trouble — and sends a verdict straight to your terminal.

**What's new:** PROMISE-trained ML defect predictor (Python/sklearn → pure-JS inference), context-aware scanning (admin dashboards & monorepos), AI false-positive triage, Flutter/React Native/Swift support, smarter favicon detection, dashboard web scan, and `periderm review --deep` on Scale/Unlimited plans.

## 1 · Installation

The easiest way to install Periderm CLI is using our installation script:

```bash
curl -fsSL https://periderm-cli.vercel.app/install.sh | bash
```

**Alternative (NPM):**

```bash
npm install -g periderm-cli
```

**Verify Installation:**

```bash
periderm --version
```

**Prereqs:** Node 18+ (for CLI). Flutter/Swift developers can use the install script or dashboard web scan without npm.

## Updating

To update Periderm CLI to the latest version, run the update command:

```bash
{{NPM_UPDATE_CMD}}
```

The CLI will automatically notify you when a new update is available in the npm registry.

## 2 · Log in

`periderm scan` requires a linked account. Run login once from any terminal:

```bash
periderm login
```

Your browser opens the dashboard CLI login page. After you approve the device, the CLI stores your token locally. Check the session anytime with `periderm whoami`.

## 3 · Your first scan

From the project you want to check:

```bash
cd ~/path/to/your-project
periderm scan
```

You get a terminal verdict plus report files at:

```
.periderm/last-report.md
.periderm/last-report.json
```

Scans **upload to your dashboard by default**. The CLI shows each file as it scans, detects your project type (web, mobile, monorepo), and filters findings that don't apply to admin/internal surfaces.

**No CLI?** Open your [dashboard](https://periderm-cli.vercel.app/dashboard) and click **run scan** to pick a folder or upload a zip.

**Admin dashboard in the same repo?** Add `.periderm/context.json`:

```json
{
  "profile": "monorepo",
  "internal_globs": ["**/_authenticated/**", "**/admin/**"]
}
```

## 4 · CLI commands

```bash
periderm scan
```

Scan the current directory, upload results to your Periderm dashboard, and write `.periderm/last-report.md` and `.periderm/last-report.json`. Requires login.

```bash
periderm scan --cwd <dir>
```

Scan a directory other than the current working directory.

```bash
periderm review --deep
```

**Scale/Unlimited.** AI agent review for edge cases static checks miss. Appends to your last report.

```bash
periderm login
```

Link the CLI to your Periderm account via browser.

```bash
periderm logout
```

Clear the locally stored CLI token.

```bash
periderm whoami
```

Print API URL, user id, plan, and remaining scan quota.

```bash
periderm watch
```

Re-run scans on file change (no login required; no report files written).

## Supported file types

`.js`, `.jsx`, `.ts`, `.tsx`, `.mjs`, `.cjs`, `.dart`, `.swift`

## Project context

Periderm uses route structure + optional AI classification to skip legal, SEO, and accessibility checks on internal admin surfaces. Override with `.periderm/context.json` in your repo root.

## 5 · Severity shorthand

When viewing scan reports in the dashboard, you may notice a string like `1c 5h · 5m · 2l`. This breaks down findings by severity:

- **c** (Critical): Application-breaking bugs, severe security vulnerabilities, or runaway cloud costs.
- **h** (High): Data corruption risks or major UI/accessibility failures.
- **m** (Medium): Standard technical debt, missing error boundaries, or minor logic flaws.
- **l** (Low): Best practice warnings and optimization suggestions.

## 6 · Deep review (Scale / Unlimited)

`periderm review --deep` runs an AI agent locally against your codebase **after** a scan. It is designed for nuanced edge cases that deterministic rules cannot enumerate upfront — legal copy mismatches, subtle UX traps, business-logic contradictions, and one-off launch risks.

**Requirements:**

- Scale or Unlimited plan (checked via your CLI token)
- A recent scan (`.periderm/last-report.json`)

```bash
periderm scan
periderm review --deep
```

Deep review **adds** findings; it does not replace the fast deterministic layer. Every scan also runs a lightweight AI context pass (when configured) to filter false positives like missing favicons when you already have one under a nonstandard path.

## 7 · Uninstalling

If you ever need to remove the CLI and its local configuration:

```bash
npm uninstall -g periderm-cli
rm -rf ~/.periderm
```

## 8 · Project context

Periderm detects **what kind of app you have** before applying consumer-facing checks.

## Automatic detection

- **Monorepo:** marketing routes + `_authenticated` / admin routes → legal & SEO only on public surfaces
- **Admin-only:** no public landing routes → skips legal, SEO globally
- **Mobile:** Flutter, Expo, React Native, Swift → skips web SEO checks

Detection uses route structure and manifests (`pubspec.yaml`, `app.json`, `Package.swift`) — not your project folder name.

## Manual override

Create `.periderm/context.json` in your repo:

```json
{
  "profile": "monorepo",
  "internal_globs": [
    "**/_authenticated/**",
    "**/routes/admin/**",
    "**/src/admin/**"
  ],
  "skip_categories": ["Legal & Compliance"],
  "skip_check_ids": ["missing-favicon"]
}
```

| Field | Purpose |
| --- | --- |
| `profile` | `consumer-app`, `admin-only`, `internal-tool`, `mobile-app`, `monorepo`, `library` |
| `internal_globs` | Paths where legal/SEO/accessibility checks are skipped |
| `skip_categories` | Categories to skip project-wide |
| `skip_check_ids` | Specific check IDs to always ignore |

## AI triage

When Groq is configured server-side (dashboard scans) or via `GROQ_API_KEY` locally, Periderm runs a post-scan triage pass to remove obvious false positives before writing your markdown report.

## 9 · Score definitions

When you run a scan, Periderm generates three distinct scores out of 100 to help you understand your app's readiness.

- **Launch confidence**: The overall score. It starts at 100 and is heavily penalized by critical and high-severity findings across all categories (including Security, Legal, SEO, and Best Practices). A score below 75 results in a `hold` verdict, while any critical finding immediately results in a `blocked` verdict.
- **Reality**: Measures your application's robustness against real-world chaos. This score drops when Periderm detects missing error boundaries, poor network failure handling, data integrity risks, or unhandled routing loops. If your app is built perfectly for the "happy path" but breaks when the network drops, your reality score will reflect it.
- **Perceived performance**: Measures how the application *feels* to the user. This score is penalized by unoptimized images, missing loading states, layout shifts, jarring transitions, and poor accessibility practices. It is completely independent of raw server speed.

It is common to see a Reality and Perceived Performance score of 100 while having a low Launch Confidence score. This simply means your app is robust and feels fast, but has blocking issues in other areas (such as missing legal pages or severe security vulnerabilities).

## 10 · GitHub Action (pull request checks)

Periderm can run on every pull request and leave **one comment** with the result. The comment is edited on every push, so a busy pull request never fills up with bot messages.

> **✓ 142 checks passed | 2 warnings**
> - Missing Terms of Service
> - Unbounded API retry on `/api/ai`

### Set it up (2 minutes)

1. In your repository, create `.github/workflows/periderm.yml`:

```yaml
name: Periderm
on:
  pull_request:
  push:
    branches: [main]

permissions:
  contents: read
  pull-requests: write

jobs:
  periderm:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: Prince-Japheth/periderm-action@v1
        with:
          # Public repos: leave this out. Private repos: add a Team token as a repo secret.
          token: ${{ secrets.PERIDERM_TOKEN }}
```

2. Commit it to your default branch.
3. Open a pull request. Periderm comments within a minute or two.

### Public and private repositories

- **Public repositories** are free. No account and no token needed.
- **Private repositories** need the **Team** plan ($29/month) or **Business** ($99/month, adds the team dashboard). Open **Dashboard → Integrations → GitHub**, create a CI token, and save it in GitHub under **Settings → Secrets and variables → Actions** as `PERIDERM_TOKEN`.

With a token, every pull request scan also shows up on your dashboard.

### Options

| Input | Default | What it does |
| --- | --- | --- |
| `fail-on` | `critical` | Fail the job at this severity or above: `critical`, `high`, `medium` or `never`. |
| `comment` | `true` | Post or update the pull request comment. |
| `working-directory` | `.` | Folder to scan, for monorepos. |

### Good to know

- Your code never leaves the GitHub runner. The scan runs inside the job.
- Findings also appear as inline annotations on the changed files and in the job summary.
- Pull requests from forks get a read-only GitHub token, so the comment can't be posted. The job summary still shows everything.
- Not on GitHub? Run `periderm ci` in any CI. It prints the result, writes `.periderm/last-report.md` and exits non-zero when `--fail-on` is hit.

## 11 · Ignoring folders (Unlimited)

On Unlimited, Team and Business, **Dashboard → Policies** holds ignore rules that every `periderm scan`, `periderm ci` and browser scan applies. The CLI prints how many rules it applied at the start of each scan.

Write one rule per line. These all ignore the `data` folder and everything in it:

```
data
/data
data/
data/**
```

A leading `/` means "from the project root". A name without `*` matches that file or folder and everything inside it. Use globs for patterns, for example `**/*.generated.ts`.

Periderm also skips anything in your `.gitignore`, plus `node_modules`, build output and test files.

## 10 · ML defect predictor

Every scan runs a **Random Forest classifier** trained on the **PROMISE ant-1.7** software-defect dataset (745 Java modules, 83% accuracy). It predicts whether each source file is likely to contain defects using five CK-style metrics extracted at scan time.

| Feature | What it measures |
| --- | --- |
| `loc` | Lines of code |
| `wmc` | Weighted methods / function count |
| `npm` | Number of public methods |
| `max_cc` | Max cyclomatic complexity (branch count) |
| `avg_cc` | Average cyclomatic complexity |

When a file's predicted defect probability exceeds 50%, Periderm emits a **HIGH** finding:

```
Check id : ai-defect-prediction
Category : Code Quality
Message  : AI Defect Prediction: High Risk
```

The scan detail page shows a dedicated **ML Defect Analysis** card with the predictor status badge, high-risk file count, and the list of flagged files.

## Python scripts

The ML layer is fully implemented in Python (scikit-learn). Three scripts cover the complete lifecycle:

```bash
# Train — exports defect_model.onnx + defect_model.json
pip install pandas scikit-learn skl2onnx onnx
python scripts/train_defect_model.py

# Evaluate — 5-fold CV, confusion matrix, ROC curve, feature importance
pip install pandas scikit-learn matplotlib seaborn
python scripts/evaluate_model.py

# Standalone Python scanner (no Node.js required)
pip install pandas scikit-learn requests rich
python scripts/analyze.py --cwd /path/to/project
python scripts/analyze.py --cwd /path/to/project --upload
```

`scripts/analyze.py` is a complete Python reimplementation of the scan pipeline — it extracts the same metrics, runs inference natively via sklearn, and optionally uploads findings to your dashboard.

## Debug

```bash
PERIDERM_DEBUG_ML=1 periderm scan
# [periderm-ml] model path: .../defect_model.json
# [periderm-ml] session loaded — 100 trees, pure-JS inference
```
