# Webdev Agent OS v9 — Agency Command, Revenue, and Customer Success Engine

## Purpose

Webdev Agent OS v9 connects sales, delivery, finance evidence, and customer success to the technical systems introduced in v1–v8. It is designed to answer four operational questions without relying on vanity metrics:

1. What work is likely to close?
2. What revenue has actually been contracted, invoiced, and collected?
3. What does delivery cost, and is the relationship economically healthy?
4. Is the client receiving measurable value and likely to renew or expand?

All bundled commercial figures are illustrative sample records. They are not assertions of live revenue.

## Operating lifecycle

**Package → Opportunity → Proposal → Agreement → Subscription → Invoice → Payment → Delivery Cost → Onboarding → Success Plan → Renewal → Expansion**

The records are connected by stable IDs so financial, delivery, project, operations, and client-portal evidence can be reviewed together.

## Core records

### Service packages

Productized offers define setup pricing, recurring pricing, included hours, overage rates, target gross margin, features, deliverables, and ideal-client criteria. Packages are reusable commercial templates; changing a package does not silently rewrite an accepted proposal or signed agreement.

### Opportunities and weighted pipeline

Each opportunity records its source, stage, expected close date, setup and recurring value, probability, owner, need, next action, risks, and tags. Weighted pipeline uses:

`estimated setup revenue × probability + estimated monthly revenue × 12 × probability`

This is forecasting evidence, not recognized revenue.

### Proposals and agreements

Proposals preserve version, scope, assumptions, exclusions, commercial terms, validity, and decision history. Accepted proposals can be connected to agreements. Agreement records preserve the accepted terms and external document reference; v9 is not a legal-signature provider.

### Subscriptions, invoices, and payments

Subscriptions represent recurring service records. Invoices and payments are operational accounting evidence and can carry external IDs for a future accounting connector. Webdev Agent OS does not move money, charge cards, calculate tax obligations, or replace an accounting ledger.

### Delivery costs and profitability

Owner-only cost entries can record labor, infrastructure, software, contractors, and other delivery costs by client and project. Gross-profit and gross-margin reporting are based only on recorded collected revenue and recorded delivery cost. Missing costs produce incomplete profitability evidence.

Internal cost and margin data are excluded from the scoped client portal and generated client account reports.

### Onboarding

Onboarding plans contain accountable tasks, owners, statuses, evidence, target launch dates, and completion progress. They connect a sold agreement to an operational launch rather than allowing a new client to disappear between sales and delivery.

### Customer-success plans

Success plans define a desired outcome, primary metric, baseline, target, current value, unit, sentiment, review date, milestones, risks, opportunities, and touchpoints. Progress is presented as evidence toward a target; it does not imply causality unless the underlying measurement supports it.

### Renewals and expansion

Renewal records track expected renewal date and value, status, risk, owner, next action, expansion value, and notes. Account-health signals combine commercial, delivery, SLO, onboarding, outcome, and engagement evidence.

### White-label profiles

Brand profiles allow client-facing portals and reports to use a client or partner name, accent color, logo URL, support email, and custom domain record. Branding does not weaken client isolation or role authorization.

## Metrics and definitions

- **MRR:** active monthly subscription value. Non-monthly intervals are normalized conservatively.
- **ARR:** MRR × 12.
- **Invoiced:** total issued invoice value in the selected records.
- **Collected:** received payment evidence.
- **Outstanding:** invoice total minus recorded payments.
- **Overdue:** outstanding value with a due date before the current time.
- **Delivery cost:** recorded internal cost entries.
- **Gross profit:** collected revenue minus recorded delivery cost.
- **Gross margin:** gross profit divided by collected revenue.
- **Weighted pipeline:** probability-weighted setup plus first-year recurring value.
- **Renewal value:** expected amount on open renewal records due within the configured window.

These are management metrics, not GAAP financial statements.

## Account-health model

The engine evaluates evidence such as:

- overdue balances;
- breached service objectives;
- unresolved onboarding work;
- negative or unknown customer sentiment;
- stalled outcome progress;
- renewal proximity and risk;
- unresolved service or delivery issues;
- absence of an active success plan;
- credible expansion opportunities.

Health classifications are decision support. A responsible account owner should review the underlying evidence before acting on the score.

## Roles and data boundaries

- **Owner:** full commercial records, internal costs, margin, export, and configuration.
- **Developer:** delivery-oriented agency operations and authorized writes.
- **Reviewer:** review and reporting access appropriate to governance tasks.
- **Client:** assigned-account proposals, invoices, onboarding, success plans, renewals, deliverables, requests, and SLOs; no internal cost or margin.
- **Viewer:** read-only internal summary based on the configured trust boundary.

Client tokens use the v8 portal boundary. Production deployments should use an external identity provider, short-lived sessions, CSRF protection, rate limits, secure cookies, and an auditable authorization service.

## Client Success Portal

The v9 portal combines scoped agency and delivery data. A client can see:

- current account-success health;
- onboarding progress;
- desired outcomes and metric progress;
- invoice totals and open balances;
- renewal date and risk state;
- deliverables and decisions;
- service requests;
- SLO results and status pages.

The portal does not expose opportunity pipeline, internal delivery costs, gross margin, other clients, production controls, or unrestricted data export.

## CLI

```bash
npm run agency:stats
npm run agency:report
node scripts/agency-cli.js view
node scripts/agency-cli.js view client-hdp-internal
node scripts/agency-cli.js opportunity path/to/opportunity.json
node scripts/agency-cli.js proposal path/to/proposal.json
node scripts/agency-cli.js proposal-decision <proposal-id> accepted "Approved terms"
node scripts/agency-cli.js invoice path/to/invoice.json
node scripts/agency-cli.js payment path/to/payment.json
node scripts/agency-cli.js cost path/to/cost.json
node scripts/agency-cli.js onboarding path/to/onboarding.json
node scripts/agency-cli.js success-plan path/to/success-plan.json
node scripts/agency-cli.js renewal path/to/renewal.json
```

Set `AGENCY_STORE` to move the writable JSON store outside the application directory.

## HTTP API

Read endpoints:

- `GET /api/agency`
- `GET /api/agency/stats`
- `GET /api/agency/export` — owner only
- `GET /api/agency/client-portal?clientId=...` — valid scoped portal token required

Write endpoints cover packages, opportunities, proposals and decisions, agreements, subscriptions, invoices, payments, costs, onboarding tasks, success plans and touchpoints, renewals, white-label profiles, and report generation. All writes use the server role boundary and persistent store queue.

## Reports

`npm run agency:report` produces:

```text
reports/agency-command/
  agency-report.html
  agency-report.json
  agency-report.md
  clients/<client-id>/
    account-report.html
    account-report.json
```

The agency report includes owner-level profitability evidence. Client reports intentionally exclude internal cost and gross-margin fields.

## Safety and production limitations

- Sample records must be replaced or explicitly verified before operational use.
- JSON persistence is suitable for a controlled single-process local deployment, not concurrent multi-instance production.
- Invoice records do not charge customers or replace accounting software.
- Agreement records do not provide legal advice or electronic-signature compliance.
- Profitability is only as complete as the cost and payment records entered.
- Customer-health scores are explainable heuristics, not autonomous account decisions.
- No proposal, invoice, contract, renewal, or client communication is sent externally without an explicit action and configured connector.
- Client report generation must remain separate from owner-only profitability reports.

## Verification contract

The v9 self-tests verify normalization, CRUD operations, role enforcement, client scoping, duplicate-safe persistence, proposal decisions, invoice and payment math, delivery-cost math, customer-success progress, onboarding completion, renewal records, report generation, API behavior, JSON Schema validation, and browser rendering.
